Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add Docker and Docker Compose setup for easy deployment
Murtaza Nasir479b0c57660e
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 00000000..52524d17--- /dev/null+++ b/.dockerignore@@ -0,0 +1,48 @@+# Git+.git+.gitignore++# Docker+.dockerignore+Dockerfile+docker-compose.yml+docker-compose.override.yml+docker-compose.override.yml.example++# Python+__pycache__/+*.py[cod]+*$py.class+*.so+.Python+env/+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+*.egg-info/+.installed.cfg+*.egg+venv/+.venv/++# Data directories (these will be mounted as volumes)+data/+uploads/+instance/++# IDE files+.idea/+.vscode/+*.swp+*.swo++# Logs+*.logdiff --git a/Dockerfile b/Dockerfilenew file mode 100644index 00000000..e9dfebe3--- /dev/null+++ b/Dockerfile@@ -0,0 +1,35 @@+FROM python:3.11-slim++WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y --no-install-recommends \+ gcc \+ && rm -rf /var/lib/apt/lists/*++# Copy requirements first for better caching+COPY requirements.txt .+RUN pip install --no-cache-dir -r requirements.txt++# Copy application code+COPY . .++# Create necessary directories+RUN mkdir -p /data/uploads /data/instance+RUN chmod 755 /data/uploads /data/instance++# Set environment variables+ENV FLASK_APP=app.py+ENV SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db+ENV UPLOAD_FOLDER=/data/uploads++# Add entrypoint script+COPY docker-entrypoint.sh /usr/local/bin/+RUN chmod +x /usr/local/bin/docker-entrypoint.sh++# Expose the port+EXPOSE 8899++# Set entrypoint and default command+ENTRYPOINT ["docker-entrypoint.sh"]+CMD ["gunicorn", "--workers", "3", "--bind", "0.0.0.0:8899", "--timeout", "600", "app:app"]diff --git a/app.py b/app.pyindex edd3b238..e08387e5 100644--- a/app.py+++ b/app.py@@ -42,9 +42,9 @@ def md_to_html(text):return htmlapp = Flask(__name__)-# Ensure the path uses the directory structure from your setup script-app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////opt/transcription-app/instance/transcriptions.db'-app.config['UPLOAD_FOLDER'] = '/opt/transcription-app/uploads' # Use absolute path based on setup+# Use environment variables or default paths for Docker compatibility+app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')+app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', '/data/uploads')app.config['MAX_CONTENT_LENGTH'] = 250 * 1024 * 1024 # 250MB max file size# Set a secret key for session management and CSRF protectionapp.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'default-dev-key-change-in-production')diff --git a/docker-compose.override.yml.example b/docker-compose.override.yml.examplenew file mode 100644index 00000000..4f998143--- /dev/null+++ b/docker-compose.override.yml.example@@ -0,0 +1,16 @@+version: '3.8'++services:+ app:+ volumes:+ # Uncomment and modify these lines to use custom paths for data storage+ # - /path/to/your/uploads:/data/uploads+ # - /path/to/your/database:/data/instance+ environment:+ # Admin user creation (uncomment and set these to create an admin user on first run)+ # - ADMIN_USERNAME=admin+ # - [email protected]+ # - ADMIN_PASSWORD=securepassword++ # Application settings+ # - ALLOW_REGISTRATION=falsediff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..90a5611c--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,28 @@+version: '3.8'++services:+ app:+ build: .+ image: whispertranscribe:latest+ container_name: whispertranscribe+ restart: unless-stopped+ ports:+ - "8899:8899"+ volumes:+ - whispertranscribe-uploads:/data/uploads+ - whispertranscribe-instance:/data/instance+ env_file:+ - .env+ environment:+ - SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db+ - UPLOAD_FOLDER=/data/uploads+ # Admin user creation (uncomment and set these to create an admin user on first run)+ # - ADMIN_USERNAME=admin+ # - [email protected]+ # - ADMIN_PASSWORD=securepassword++volumes:+ whispertranscribe-uploads:+ name: whispertranscribe-uploads+ whispertranscribe-instance:+ name: whispertranscribe-instancediff --git a/docker-entrypoint.sh b/docker-entrypoint.shnew file mode 100644index 00000000..af714ae1--- /dev/null+++ b/docker-entrypoint.sh@@ -0,0 +1,25 @@+#!/bin/bash+set -e++# Create necessary directories+mkdir -p /data/uploads /data/instance+chmod 755 /data/uploads /data/instance++# Initialize the database if it doesn't exist+if [ ! -f /data/instance/transcriptions.db ]; then+ echo "Database doesn't exist. Creating new database..."+ python -c "from app import app, db; app.app_context().push(); db.create_all()"+ echo "Database created successfully."++ # Check if we need to create an admin user+ if [ -n "$ADMIN_USERNAME" ] && [ -n "$ADMIN_EMAIL" ] && [ -n "$ADMIN_PASSWORD" ]; then+ echo "Creating admin user using environment variables..."+ python docker_create_admin.py+ fi+else+ echo "Database exists. Checking for schema updates..."+ python -c "from app import app; app.app_context().push()"+fi++# Start the application+exec "$@"diff --git a/docker_create_admin.py b/docker_create_admin.pynew file mode 100644index 00000000..b071fc45--- /dev/null+++ b/docker_create_admin.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3++import os+import sys+from email_validator import validate_email, EmailNotValidError++# Try to import from app context+try:+ from flask import current_app+ app = current_app._get_current_object()+ with app.app_context():+ db = app.extensions['sqlalchemy'].db+ User = app.extensions['sqlalchemy'].db.metadata.tables['user']+ bcrypt = app.extensions.get('bcrypt')+except (RuntimeError, AttributeError, KeyError):+ # If not in app context, import directly+ try:+ from app import app, db, User, bcrypt+ except ImportError as e:+ print(f"Error: Could not import required modules: {e}")+ print("Make sure docker_create_admin.py is runnable and PYTHONPATH is set.")+ sys.exit(1)++def create_admin_user_from_env():+ """+ Create an admin user from environment variables.+ Required environment variables:+ - ADMIN_USERNAME+ - ADMIN_EMAIL+ - ADMIN_PASSWORD+ """+ print("Creating admin user for Speakr application from environment variables")+ print("=================================================================")++ # Get values from environment variables+ username = os.environ.get('ADMIN_USERNAME')+ email = os.environ.get('ADMIN_EMAIL')+ password = os.environ.get('ADMIN_PASSWORD')++ # Validate required environment variables+ if not username or not email or not password:+ print("Error: ADMIN_USERNAME, ADMIN_EMAIL, and ADMIN_PASSWORD environment variables must be set.")+ sys.exit(1)++ # Validate username+ if len(username) < 3:+ print("Error: Username must be at least 3 characters long.")+ sys.exit(1)++ # Validate email+ try:+ validate_email(email)+ except EmailNotValidError as e:+ print(f"Error: Invalid email: {str(e)}")+ sys.exit(1)++ # Validate password+ if len(password) < 8:+ print("Error: Password must be at least 8 characters long.")+ sys.exit(1)++ # Create user+ with app.app_context():+ # Check if username already exists+ existing_user = db.session.query(User).filter_by(username=username).first()+ if existing_user:+ print(f"User with username '{username}' already exists.")+ sys.exit(0)++ # Check if email already exists+ existing_email = db.session.query(User).filter_by(email=email).first()+ if existing_email:+ print(f"User with email '{email}' already exists.")+ sys.exit(0)++ # Create new admin user+ hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')+ new_user = User(username=username, email=email, password=hashed_password, is_admin=True)+ db.session.add(new_user)+ db.session.commit()++ print("\nAdmin user created successfully!")+ print(f"Username: {username}")+ print(f"Email: {email}")+ print("You can now log in to the application with these credentials.")++if __name__ == "__main__":+ create_admin_user_from_env()diff --git a/readme.md b/readme.mdindex f844fe71..07e767be 100644--- a/readme.md+++ b/readme.md@@ -58,9 +58,110 @@ Speakr is a personal, self-hosted web application designed for transcribing audi## Setup Instructions-Choose either **Local Development** or **Deployment**.--### 1. Local Development+Choose either **Docker**, **Local Development**, or **Deployment**.++### 1. Docker Installation++The easiest way to deploy Speakr is using Docker and Docker Compose.++1. **Clone the Repository:**+ ```bash+ git clone https://github.com/murtaza-nasir/speakr.git+ cd speakr+ ```++2. **Configure Environment Variables:**+ * Copy the example environment file:+ ```bash+ cp .env.example .env+ ```+ * Edit the `.env` file with your API keys and settings as described in the Configuration section.++3. **Build and Start the Container:**+ ```bash+ docker-compose up -d+ ```++4. **Create an Admin User:**++ You can create an admin user in one of the following ways:++ * **Option A: Using environment variables:**++ Create a `docker-compose.override.yml` file:+ ```bash+ cp docker-compose.override.yml.example docker-compose.override.yml+ ```++ Edit the file to uncomment and set the admin credentials:+ ```yaml+ services:+ app:+ environment:+ - ADMIN_USERNAME=admin+ - ADMIN_PASSWORD=securepassword+ ```++ Then restart the container:+ ```bash+ docker-compose down+ docker-compose up -d+ ```++ * **Option B: Using the create_admin.py script:**+ ```bash+ docker-compose exec app python create_admin.py+ ```+ Follow the interactive prompts to create an admin user.++5. **Access Speakr:** Open your web browser and navigate to `http://localhost:8899`.++#### Customizing Data Storage++By default, all data (database and uploaded audio files) is stored in Docker volumes. To use custom directories on your host system:++1. Create a `docker-compose.override.yml` file (if you haven't already):+ ```bash+ cp docker-compose.override.yml.example docker-compose.override.yml+ ```++2. Edit `docker-compose.override.yml` and uncomment the volume mappings:+ ```yaml+ services:+ app:+ volumes:+ - /path/to/your/uploads:/data/uploads+ - /path/to/your/database:/data/instance+ ```++3. Replace `/path/to/your/uploads` and `/path/to/your/database` with actual paths on your system.++4. Restart the container:+ ```bash+ docker-compose down+ docker-compose up -d+ ```++#### Updating the Docker Installation++To update the application to a newer version:++1. Pull the latest code:+ ```bash+ git pull+ ```++2. Rebuild and restart the container:+ ```bash+ docker-compose down+ docker-compose build+ docker-compose up -d+ ```++Your data will be preserved as it's stored in Docker volumes or your custom mapped directories.++### 2. Local DevelopmentFollow these steps to run Speakr on your local machine for development or testing.@@ -136,7 +237,7 @@ Follow these steps to run Speakr on your local machine for development or testin8. **Access Speakr:** Open your web browser and navigate to `http://localhost:8899` (or your server's IP address if running remotely).-### 2. Deployment (Linux with Systemd)+### 3. Deployment (Linux with Systemd)The `deployment/setup.sh` script automates the setup process on a Linux server using `systemd`.