Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
init
Murtaza Nasir0c07f7bad3f1
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..2b51a294--- /dev/null+++ b/.gitignore@@ -0,0 +1,4 @@+venv/+__pycache__/+instance/+uploads/\ No newline at end of filediff --git a/app.ipynb b/app.ipynbnew file mode 100644index 00000000..b1b26aab--- /dev/null+++ b/app.ipynb@@ -0,0 +1,243 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "I'll continue with the remaining JavaScript code and add the deployment instructions.\n",+ "\n",+ "\n",+ "\n",+ "```html\n",+ "alert('Save failed: ' + error)\n",+ " }\n",+ " },\n",+ " async loadRecordings() {\n",+ " try {\n",+ " const response = await fetch('/recordings')\n",+ " const data = await response.json()\n",+ " this.recordings = data\n",+ " } catch (error) {\n",+ " alert('Failed to load recordings: ' + error)\n",+ " }\n",+ " },\n",+ " selectRecording(recording) {\n",+ " this.selectedRecording = recording\n",+ " }\n",+ " },\n",+ " mounted() {\n",+ " this.loadRecordings()\n",+ " }\n",+ " }).mount('#app')\n",+ " </script>\n",+ "</body>\n",+ "</html>\n",+ "\n",+ "```\n",+ "\n",+ "Now, let's create a deployment script and requirements file for easy setup on Ubuntu:\n",+ "\n",+ "```text\n",+ "# requirements.txt\n",+ "flask==2.3.3\n",+ "flask-sqlalchemy==3.1.1\n",+ "openai==1.3.0\n",+ "werkzeug==2.3.7\n",+ "gunicorn==21.2.0\n",+ "\n",+ "# deployment/setup.sh\n",+ "#!/bin/bash\n",+ "\n",+ "# Update system\n",+ "sudo apt-get update\n",+ "sudo apt-get upgrade -y\n",+ "\n",+ "# Install Python and pip if not already installed\n",+ "sudo apt-get install -y python3 python3-pip python3-venv\n",+ "\n",+ "# Create directory for the application\n",+ "sudo mkdir -p /opt/transcription-app\n",+ "sudo chown $USER:$USER /opt/transcription-app\n",+ "\n",+ "# Create and activate virtual environment\n",+ "python3 -m venv /opt/transcription-app/venv\n",+ "source /opt/transcription-app/venv/bin/activate\n",+ "\n",+ "# Install requirements\n",+ "pip install -r requirements.txt\n",+ "\n",+ "# Create systemd service file\n",+ "sudo tee /etc/systemd/system/transcription.service << EOF\n",+ "[Unit]\n",+ "Description=Transcription Web Application\n",+ "After=network.target\n",+ "\n",+ "[Service]\n",+ "User=$USER\n",+ "WorkingDirectory=/opt/transcription-app\n",+ "Environment=\"PATH=/opt/transcription-app/venv/bin\"\n",+ "ExecStart=/opt/transcription-app/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:5000 app:app\n",+ "\n",+ "[Install]\n",+ "WantedBy=multi-user.target\n",+ "EOF\n",+ "\n",+ "# Create directories for uploads and database\n",+ "mkdir -p /opt/transcription-app/uploads\n",+ "mkdir -p /opt/transcription-app/instance\n",+ "\n",+ "# Reload systemd and start service\n",+ "sudo systemctl daemon-reload\n",+ "sudo systemctl start transcription\n",+ "sudo systemctl enable transcription\n",+ "\n",+ "echo \"Installation complete! The application should be running on port 5000.\"\n",+ "\n",+ "```\n",+ "\n",+ "To deploy this application on Ubuntu:\n",+ "\n",+ "1. First, create a new directory for your project and copy all the files into it:\n",+ " ```bash\n",+ " mkdir transcription-app\n",+ " cd transcription-app\n",+ " ```\n",+ "\n",+ "2. Create the following directory structure:\n",+ " ```\n",+ " transcription-app/\n",+ " ├── app.py\n",+ " ├── requirements.txt\n",+ " ├── deployment/\n",+ " │ └── setup.sh\n",+ " └── templates/\n",+ " └── index.html\n",+ " ```\n",+ "\n",+ "3. Make the setup script executable and run it:\n",+ " ```bash\n",+ " chmod +x deployment/setup.sh\n",+ " ./deployment/setup.sh\n",+ " ```\n",+ "\n",+ "The application will be installed as a system service and will:\n",+ "- Run on port 5000\n",+ "- Auto-start on system boot\n",+ "- Use gunicorn for production-grade serving\n",+ "- Store uploads in `/opt/transcription-app/uploads`\n",+ "- Store the SQLite database in `/opt/transcription-app/instance`\n",+ "\n",+ "Key features of the application:\n",+ "\n",+ "1. Upload Page:\n",+ " - Drag and drop interface for audio files\n",+ " - Visual feedback during drag operations\n",+ " - Automatic transition to input page after upload\n",+ "\n",+ "2. Input Page:\n",+ " - Split view with transcription and metadata\n",+ " - Auto-save functionality (saves 1 second after last edit)\n",+ " - Manual save button for peace of mind\n",+ " - Clean, modern interface\n",+ "\n",+ "3. Gallery Page:\n",+ " - Time-based grouping (This Week, Last Week, Older)\n",+ " - Audio playback functionality\n",+ " - Detailed view of selected recording\n",+ " - Easy navigation between recordings\n",+ "\n",+ "4. Database:\n",+ " - SQLite for simplicity and portability\n",+ " - Stores all metadata and file paths\n",+ " - Automatic timestamps\n",+ "\n",+ "5. Security Features:\n",+ " - Secure filename handling\n",+ " - File size limits\n",+ " - File type validation\n",+ "\n",+ "To customize the application, you can:\n",+ "1. Modify the upload folder location in `app.py`\n",+ "2. Adjust the maximum file size (currently 16MB)\n",+ "3. Add additional metadata fields by updating both the database model and the frontend form\n",+ "4. Customize the styling using Tailwind classes\n",+ "5. Add user authentication if needed\n",+ "\n",+ "Would you like me to explain any particular part in more detail or make any modifications to the application?"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "Here's how to run the app directly using Python:\n",+ "\n",+ "\n",+ "\n",+ "1. First, activate the virtual environment. If you used the setup script, it would be:\n",+ "```bash\n",+ "source /opt/transcription-app/venv/bin/activate\n",+ "```\n",+ "\n",+ "You'll know the virtual environment is activated when you see `(venv)` at the start of your command prompt.\n",+ "\n",+ "2. Navigate to the application directory:\n",+ "```bash\n",+ "cd /opt/transcription-app\n",+ "```\n",+ "\n",+ "3. Run the application directly with Python:\n",+ "```bash\n",+ "python app.py\n",+ "```\n",+ "\n",+ "If you want to run it in development mode but on a different port:\n",+ "```bash\n",+ "export FLASK_ENV=development\n",+ "export FLASK_DEBUG=1\n",+ "python app.py\n",+ "```\n",+ "\n",+ "Alternative way using Flask CLI:\n",+ "```bash\n",+ "export FLASK_APP=app.py\n",+ "flask run --host=0.0.0.0 --port=8080\n",+ "```\n",+ "\n",+ "To stop the application, press `Ctrl+C`.\n",+ "\n",+ "Some useful commands for virtual environment management:\n",+ "```bash\n",+ "# Deactivate the virtual environment when you're done\n",+ "deactivate\n",+ "\n",+ "# If you need to install additional packages\n",+ "pip install package_name\n",+ "\n",+ "# To see all installed packages\n",+ "pip list\n",+ "\n",+ "# To update requirements.txt after installing new packages\n",+ "pip freeze > requirements.txt\n",+ "```\n",+ "\n",+ "If you're developing and want to see the logs in real-time:\n",+ "```bash\n",+ "# In development mode, logs will show directly in the terminal\n",+ "# If you want to see more detailed logs, you can add this to app.py:\n",+ "import logging\n",+ "logging.basicConfig(level=logging.DEBUG)\n",+ "```\n",+ "\n",+ "Would you like me to help you set up any specific development configuration?"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/app.py b/app.pynew file mode 100644index 00000000..cd7ead7b--- /dev/null+++ b/app.py@@ -0,0 +1,262 @@+# app.py+from flask import Flask, render_template, request, jsonify, send_file+from flask_sqlalchemy import SQLAlchemy+from datetime import datetime+import os+from openai import OpenAI+import json+from werkzeug.utils import secure_filename+from werkzeug.exceptions import RequestEntityTooLarge+from sqlalchemy import select+import threading # Import threading++app = Flask(__name__)+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///instance/transcriptions.db' # Make sure path is correct+app.config['UPLOAD_FOLDER'] = 'uploads'+app.config['MAX_CONTENT_LENGTH'] = 250 * 1024 * 1024 # 250MB max file size+db = SQLAlchemy()+db.init_app(app)++# Ensure upload and instance directories exist+os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)+os.makedirs(os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')), exist_ok=True)+++# --- Database Models ---+class Recording(db.Model):+ id = db.Column(db.Integer, primary_key=True)+ title = db.Column(db.String(200))+ participants = db.Column(db.String(500))+ notes = db.Column(db.Text)+ transcription = db.Column(db.Text, nullable=True) # Allow null initially+ status = db.Column(db.String(50), default='PENDING') # Add status field: PENDING, PROCESSING, COMPLETED, FAILED+ audio_path = db.Column(db.String(500))+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ file_size = db.Column(db.Integer) # Store file size in bytes++ def to_dict(self):+ return {+ 'id': self.id,+ 'title': self.title,+ 'participants': self.participants,+ 'notes': self.notes,+ 'transcription': self.transcription,+ 'status': self.status, # Include status+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'file_size': self.file_size+ }++with app.app_context():+ db.create_all()++# --- API client setup ---+# Ensure you have your API key and base URL configured correctly+# For local testing, you might use environment variables or a config file+client = OpenAI(+ api_key=os.environ.get("OPENAI_API_KEY", "cant-be-empty"), # Use env var or default+ base_url=os.environ.get("OPENAI_BASE_URL", "http://192.168.68.85:1611/v1/") # Use env var or default+)++# --- Background Transcription Task ---+def transcribe_audio_task(app_context, recording_id, filepath):+ """Runs the transcription in a background thread."""+ with app_context: # Need app context for db operations in thread+ recording = db.session.get(Recording, recording_id)+ if not recording:+ print(f"Error: Recording {recording_id} not found for transcription.")+ return++ try:+ print(f"Starting transcription for recording {recording_id}...")+ recording.status = 'PROCESSING'+ db.session.commit()++ with open(filepath, 'rb') as audio_file:+ transcript = client.audio.transcriptions.create(+ model="Systran/faster-distil-whisper-large-v3", # Or your desired model+ file=audio_file,+ language="en" # Specify language if known+ )++ recording.transcription = transcript.text+ recording.status = 'COMPLETED'+ print(f"Transcription COMPLETED for recording {recording_id}.")+ db.session.commit()++ except Exception as e:+ print(f"Transcription FAILED for recording {recording_id}: {str(e)}")+ recording.transcription = f"Transcription failed: {str(e)}" # Store error message+ recording.status = 'FAILED'+ db.session.commit()+++# --- Flask Routes ---[email protected]('/')+def index():+ return render_template('index.html')+[email protected]('/recordings', methods=['GET'])+def get_recordings():+ try:+ stmt = select(Recording).order_by(Recording.created_at.desc())+ recordings = db.session.execute(stmt).scalars().all()+ return jsonify([recording.to_dict() for recording in recordings])+ except Exception as e:+ app.logger.error(f"Error fetching recordings: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/save', methods=['POST'])+def save_metadata():+ # This route remains largely the same, just updates metadata+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ recording_id = data.get('id')+ if not recording_id:+ return jsonify({'error': 'No recording ID provided'}), 400++ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Update fields if provided+ if 'title' in data:+ recording.title = data['title']+ if 'participants' in data:+ recording.participants = data['participants']+ if 'notes' in data:+ recording.notes = data['notes']+ # Do not update transcription or status here++ db.session.commit()+ return jsonify({'success': True, 'recording': recording.to_dict()})++ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error saving metadata for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/upload', methods=['POST'])+def upload_file():+ try:+ if 'file' not in request.files:+ return jsonify({'error': 'No file provided'}), 400++ file = request.files['file']+ if file.filename == '':+ return jsonify({'error': 'No file selected'}), 400++ filename = secure_filename(file.filename)+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)++ # Get file size before saving+ file.seek(0, os.SEEK_END)+ file_size = file.tell()+ file.seek(0)++ # Check size limit again (Flask's MAX_CONTENT_LENGTH handles the actual request blocking)+ if file_size > app.config['MAX_CONTENT_LENGTH']:+ raise RequestEntityTooLarge()++ file.save(filepath)+ print(f"File saved to {filepath}")++ # Create initial database entry with PENDING status+ recording = Recording(+ audio_path=filepath,+ title=f"Untitled - {datetime.now().strftime('%Y-%m-%d %H:%M')}", # Simpler default title+ file_size=file_size,+ status='PENDING' # Explicitly set status+ )+ db.session.add(recording)+ db.session.commit()+ print(f"Initial recording record created with ID: {recording.id}")++ # --- Start transcription in background thread ---+ # Pass the app context to the thread+ thread = threading.Thread(+ target=transcribe_audio_task,+ args=(app.app_context(), recording.id, filepath)+ )+ thread.start()+ print(f"Background transcription thread started for recording ID: {recording.id}")++ # Return the initial recording data and ID immediately+ return jsonify(recording.to_dict()), 202 # 202 Accepted indicates processing started++ except RequestEntityTooLarge:+ max_size_mb = app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)+ app.logger.warning(f"Upload failed: File too large (>{max_size_mb}MB)")+ return jsonify({+ 'error': f'File too large. Maximum size is {max_size_mb:.0f} MB.',+ 'max_size_mb': max_size_mb+ }), 413+ except Exception as e:+ db.session.rollback() # Rollback if initial save failed+ app.logger.error(f"Error during file upload: {e}", exc_info=True)+ return jsonify({'error': str(e)}), 500++# --- NEW: Status Endpoint ---[email protected]('/status/<int:recording_id>', methods=['GET'])+def get_status(recording_id):+ """Endpoint to check the transcription status."""+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Return the full recording data, including status and transcription (if available)+ return jsonify(recording.to_dict())++ except Exception as e:+ app.logger.error(f"Error fetching status for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500++[email protected]('/audio/<int:recording_id>')+def get_audio(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording or not recording.audio_path:+ return jsonify({'error': 'Recording or audio file not found'}), 404+ # Ensure the file actually exists before trying to send it+ if not os.path.exists(recording.audio_path):+ return jsonify({'error': 'Audio file missing from server'}), 404+ return send_file(recording.audio_path)+ except Exception as e:+ app.logger.error(f"Error serving audio for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/recording/<int:recording_id>', methods=['DELETE'])+def delete_recording(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Delete the audio file first+ try:+ if recording.audio_path and os.path.exists(recording.audio_path):+ os.remove(recording.audio_path)+ print(f"Deleted audio file: {recording.audio_path}")+ except Exception as e:+ # Log error but proceed to delete DB record+ app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")++ # Delete the database record+ db.session.delete(recording)+ db.session.commit()+ print(f"Deleted recording record ID: {recording_id}")++ return jsonify({'success': True})+ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error deleting recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500++if __name__ == '__main__':+ # Use waitress or gunicorn in production instead of Flask's dev server+ # Example: waitress-serve --host 0.0.0.0 --port 8899 app:app+ app.run(host='0.0.0.0', port=8899, debug=True) # debug=True reloads, which can interfere with threads. Set False for testing threads properly. Consider waitress for better threading.\ No newline at end of filediff --git a/create_docs.py b/create_docs.pynew file mode 100644index 00000000..09375dc6--- /dev/null+++ b/create_docs.py@@ -0,0 +1,67 @@+import os+from pathlib import Path++def create_markdown_doc(base_dir):+ output = []++ # Add header+ output.append("# Project Files\n")+ output.append("Generated documentation of all project files.\n")++ # Function to read and format file content+ def add_file_content(filepath, relative_path):+ output.append(f"\n## {relative_path}\n")+ output.append("```" + get_file_extension(filepath) + "\n")+ try:+ with open(filepath, 'r', encoding='utf-8') as f:+ output.append(f.read())+ except Exception as e:+ output.append(f"Error reading file: {e}")+ output.append("```\n")++ def get_file_extension(filepath):+ ext = os.path.splitext(filepath)[1][1:].lower()+ # Map file extensions to markdown code block languages+ extension_map = {+ 'py': 'python',+ 'html': 'html',+ 'js': 'javascript',+ 'css': 'css',+ 'sh': 'bash',+ 'md': 'markdown',+ 'txt': 'text'+ }+ return extension_map.get(ext, '')++ # List of important file patterns to include+ patterns = [+ '*.py',+ '*.html',+ '*.js',+ '*.css',+ '*.sh',+ 'requirements.txt'+ ]++ # Walk through directory and add files+ for root, _, _ in os.walk(base_dir):+ for pattern in patterns:+ for filepath in Path(root).glob(pattern):+ if 'venv' not in str(filepath) and '__pycache__' not in str(filepath):+ relative_path = os.path.relpath(filepath, base_dir)+ add_file_content(filepath, relative_path)++ # Write to output file+ output_path = os.path.join(base_dir, 'project_files.md')+ with open(output_path, 'w', encoding='utf-8') as f:+ f.write('\n'.join(output))++ return output_path++if __name__ == "__main__":+ # Get the current directory+ current_dir = os.getcwd()++ # Create the markdown file+ output_file = create_markdown_doc(current_dir)+ print(f"Created markdown documentation at: {output_file}")\ No newline at end of filediff --git a/deployment/setup.sh b/deployment/setup.shnew file mode 100755index 00000000..901c9249--- /dev/null+++ b/deployment/setup.sh@@ -0,0 +1,62 @@+#!/bin/bash++# Create directory for the application+sudo mkdir -p /opt/transcription-app+sudo chown $USER:$USER /opt/transcription-app++# Copy application files+cp app.py /opt/transcription-app/+cp -r templates /opt/transcription-app/+cp requirements.txt /opt/transcription-app/+cp reset_db.py /opt/transcription-app/++# Create and activate virtual environment+python3 -m venv /opt/transcription-app/venv+source /opt/transcription-app/venv/bin/activate++# Install requirements+cd /opt/transcription-app+pip install -r requirements.txt++# Create directories for uploads and database with proper permissions+mkdir -p /opt/transcription-app/uploads+mkdir -p /opt/transcription-app/instance+chmod 755 /opt/transcription-app/uploads+chmod 755 /opt/transcription-app/instance++# Initialize the database+python reset_db.py++# Set proper ownership for all files+sudo chown -R $USER:$USER /opt/transcription-app++# Create systemd service file+sudo tee /etc/systemd/system/transcription.service << EOF+[Unit]+Description=Transcription Web Application+After=network.target++[Service]+User=$USER+WorkingDirectory=/opt/transcription-app+Environment="PATH=/opt/transcription-app/venv/bin"+Environment="PYTHONPATH=/opt/transcription-app"+ExecStart=/opt/transcription-app/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8899 --timeout 600 app:app+Restart=always+RestartSec=5++[Install]+WantedBy=multi-user.target+EOF++# Reload systemd and start service+sudo systemctl daemon-reload+sudo systemctl restart transcription+sudo systemctl enable transcription++# Check service status+echo "Checking service status..."+sleep 3+sudo systemctl status transcription++echo "Installation complete! The application should be running on port 8899."\ No newline at end of filediff --git a/notes.md b/notes.mdnew file mode 100644index 00000000..f7074339--- /dev/null+++ b/notes.md@@ -0,0 +1,5 @@+## Create flat file:++python create_docs.py++## start/stop\ No newline at end of filediff --git a/project_files.md b/project_files.mdnew file mode 100644index 00000000..06e3544f--- /dev/null+++ b/project_files.md@@ -0,0 +1,872 @@+# Project Files++Generated documentation of all project files.+++## reset_db.py++```python++#!/usr/bin/env python3++from app import app, db+import os++def reset_database():+ # Get the database file path+ db_path = os.path.join('instance', 'transcriptions.db')++ # Remove existing database if it exists+ if os.path.exists(db_path):+ print(f"Removing existing database at {db_path}")+ os.remove(db_path)++ # Create application context+ with app.app_context():+ print("Creating new database...")+ # Create all tables+ db.create_all()+ print("Database initialization complete!")++if __name__ == "__main__":+ reset_database()+```+++## app.py++```python++# app.py+from flask import Flask, render_template, request, jsonify, send_file+from flask_sqlalchemy import SQLAlchemy+from datetime import datetime+import os+from openai import OpenAI+import json+from werkzeug.utils import secure_filename+from werkzeug.exceptions import RequestEntityTooLarge+from sqlalchemy import select++app = Flask(__name__)+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///transcriptions.db'+app.config['UPLOAD_FOLDER'] = 'uploads'+app.config['MAX_CONTENT_LENGTH'] = 250 * 1024 * 1024 # 250MB max file size+db = SQLAlchemy()+db.init_app(app)++# Ensure upload directory exists+os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)++# Database Models+class Recording(db.Model):+ id = db.Column(db.Integer, primary_key=True)+ title = db.Column(db.String(200))+ participants = db.Column(db.String(500))+ notes = db.Column(db.Text)+ transcription = db.Column(db.Text)+ audio_path = db.Column(db.String(500))+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ file_size = db.Column(db.Integer) # Store file size in bytes++ def to_dict(self):+ return {+ 'id': self.id,+ 'title': self.title,+ 'participants': self.participants,+ 'notes': self.notes,+ 'transcription': self.transcription,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'file_size': self.file_size+ }++with app.app_context():+ db.create_all()++# API client setup+client = OpenAI(api_key="cant-be-empty", base_url="http://192.168.68.85:1611/v1/")+[email protected]('/')+def index():+ return render_template('index.html')+[email protected]('/recordings', methods=['GET'])+def get_recordings():+ try:+ stmt = select(Recording).order_by(Recording.created_at.desc())+ recordings = db.session.execute(stmt).scalars().all()+ return jsonify([recording.to_dict() for recording in recordings])+ except Exception as e:+ return jsonify({'error': str(e)}), 500+[email protected]('/save', methods=['POST'])+def save_metadata():+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ recording_id = data.get('id')+ if not recording_id:+ return jsonify({'error': 'No recording ID provided'}), 400++ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Update fields if provided+ if 'title' in data:+ recording.title = data['title']+ if 'participants' in data:+ recording.participants = data['participants']+ if 'notes' in data:+ recording.notes = data['notes']++ db.session.commit()+ return jsonify({'success': True, 'recording': recording.to_dict()})++ except Exception as e:+ db.session.rollback()+ return jsonify({'error': str(e)}), 500+[email protected]('/upload', methods=['POST'])+def upload_file():+ try:+ if 'file' not in request.files:+ return jsonify({'error': 'No file provided'}), 400++ file = request.files['file']+ if file.filename == '':+ return jsonify({'error': 'No file selected'}), 400++ filename = secure_filename(file.filename)+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)++ # Get file size before saving+ file.seek(0, os.SEEK_END)+ file_size = file.tell()+ file.seek(0)++ file.save(filepath)++ # Create initial database entry+ recording = Recording(+ audio_path=filepath,+ title=f"Untitled Recording - {datetime.now().strftime('%Y-%m-%d %H:%M')}",+ file_size=file_size+ )+ db.session.add(recording)+ db.session.commit()++ # Start transcription+ try:+ with open(filepath, 'rb') as audio_file:+ transcript = client.audio.transcriptions.create(+ model="Systran/faster-distil-whisper-large-v3",+ file=audio_file,+ language="en"+ )++ recording.transcription = transcript.text+ db.session.commit()++ return jsonify(recording.to_dict())++ except Exception as e:+ # If transcription fails, we still keep the file but mark the error+ recording.transcription = f"Transcription failed: {str(e)}"+ db.session.commit()+ return jsonify({'error': f'Transcription failed: {str(e)}'}), 500++ except RequestEntityTooLarge:+ return jsonify({+ 'error': 'File too large',+ 'max_size_mb': app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)+ }), 413+ except Exception as e:+ return jsonify({'error': str(e)}), 500+[email protected]('/audio/<int:recording_id>')+def get_audio(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404+ return send_file(recording.audio_path)+ except Exception as e:+ return jsonify({'error': str(e)}), 500+[email protected]('/recording/<int:recording_id>', methods=['DELETE'])+def delete_recording(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Delete the audio file+ try:+ if recording.audio_path and os.path.exists(recording.audio_path):+ os.remove(recording.audio_path)+ except Exception as e:+ print(f"Error deleting file: {e}")++ # Delete the database record+ db.session.delete(recording)+ db.session.commit()++ return jsonify({'success': True})+ except Exception as e:+ db.session.rollback()+ return jsonify({'error': str(e)}), 500++if __name__ == '__main__':+ app.run(host='0.0.0.0', port=8899, debug=True)+```+++## create_docs.py++```python++import os+from pathlib import Path++def create_markdown_doc(base_dir):+ output = []++ # Add header+ output.append("# Project Files\n")+ output.append("Generated documentation of all project files.\n")++ # Function to read and format file content+ def add_file_content(filepath, relative_path):+ output.append(f"\n## {relative_path}\n")+ output.append("```" + get_file_extension(filepath) + "\n")+ try:+ with open(filepath, 'r', encoding='utf-8') as f:+ output.append(f.read())+ except Exception as e:+ output.append(f"Error reading file: {e}")+ output.append("```\n")++ def get_file_extension(filepath):+ ext = os.path.splitext(filepath)[1][1:].lower()+ # Map file extensions to markdown code block languages+ extension_map = {+ 'py': 'python',+ 'html': 'html',+ 'js': 'javascript',+ 'css': 'css',+ 'sh': 'bash',+ 'md': 'markdown',+ 'txt': 'text'+ }+ return extension_map.get(ext, '')++ # List of important file patterns to include+ patterns = [+ '*.py',+ '*.html',+ '*.js',+ '*.css',+ '*.sh',+ 'requirements.txt'+ ]++ # Walk through directory and add files+ for root, _, _ in os.walk(base_dir):+ for pattern in patterns:+ for filepath in Path(root).glob(pattern):+ if 'venv' not in str(filepath) and '__pycache__' not in str(filepath):+ relative_path = os.path.relpath(filepath, base_dir)+ add_file_content(filepath, relative_path)++ # Write to output file+ output_path = os.path.join(base_dir, 'project_files.md')+ with open(output_path, 'w', encoding='utf-8') as f:+ f.write('\n'.join(output))++ return output_path++if __name__ == "__main__":+ # Get the current directory+ current_dir = os.getcwd()++ # Create the markdown file+ output_file = create_markdown_doc(current_dir)+ print(f"Created markdown documentation at: {output_file}")+```+++## requirements.txt++```text++flask==2.3.3+flask-sqlalchemy==3.1.1+openai==1.3.0+werkzeug==2.3.7+gunicorn==21.2.0+```+++## templates/index.html++```html++<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Audio Transcription App</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+</head>+<body class="bg-gray-100">+ <div id="app" class="container mx-auto px-4 py-8">+ <!-- Navigation -->+ <nav class="flex justify-between mb-8">+ <h1 class="text-2xl font-bold">Audio Transcription</h1>+ <div>+ <button @click="currentView = 'upload'" class="px-4 py-2 mr-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ New Recording+ </button>+ <button @click="currentView = 'gallery'" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Gallery+ </button>+ </div>+ </nav>++ <!-- Upload View -->+ <div v-if="currentView === 'upload'"+ @dragover.prevent="dragover = true"+ @dragleave.prevent="dragover = false"+ @drop.prevent="handleDrop"+ :class="{'border-blue-500 bg-blue-50': dragover}"+ class="border-2 border-dashed rounded-lg p-12 text-center transition-all duration-200">++ <!-- Loading State -->+ <div v-if="isProcessing" class="space-y-4">+ <div class="animate-spin mx-auto">+ <i class="fas fa-circle-notch text-4xl text-blue-500"></i>+ </div>+ <h2 class="text-xl mb-2">Processing your audio file...</h2>+ <div class="max-w-md mx-auto">+ <div class="w-full bg-gray-200 rounded-full h-2.5">+ <div class="bg-blue-500 h-2.5 rounded-full transition-all duration-500"+ :style="{ width: processingStatus.progress + '%' }"></div>+ </div>+ <p class="text-sm text-gray-600 mt-2">${ processingStatus.message }</p>+ </div>+ </div>++ <!-- Upload State -->+ <div v-else>+ <i class="fas fa-cloud-upload-alt text-4xl mb-4 text-blue-500"></i>+ <h2 class="text-xl mb-2">Drag and drop your audio file here</h2>+ <p class="text-gray-500">or</p>+ <input type="file" @change="handleFileSelect" accept="audio/*" class="hidden" ref="fileInput">+ <button @click="$refs.fileInput.click()" class="mt-4 px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Select File+ </button>+ </div>+ </div>++ <!-- Input View -->+ <div v-if="currentView === 'input'" class="grid grid-cols-2 gap-8">+ <div class="bg-white p-6 rounded-lg shadow">+ <h3 class="text-lg font-semibold mb-4">Transcription</h3>+ <div class="h-96 overflow-y-auto p-4 bg-gray-50 rounded">+ <span v-if="currentRecording">${ currentRecording.transcription }</span>+ </div>+ </div>++ <div class="bg-white p-6 rounded-lg shadow">+ <h3 class="text-lg font-semibold mb-4">Recording Details</h3>+ <div class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700">Title</label>+ <input v-model="currentRecording.title"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Participants</label>+ <input v-model="currentRecording.participants"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Notes</label>+ <textarea v-model="currentRecording.notes"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"+ rows="4"></textarea>+ </div>+ </div>+ </div>+ </div>++ <!-- Gallery View -->+ <div v-if="currentView === 'gallery'" class="grid grid-cols-4 gap-8">+ <!-- Left side: Recording list -->+ <div class="col-span-1 bg-white p-6 rounded-lg shadow">+ <h3 class="text-lg font-semibold mb-4">Recordings</h3>+ <div class="space-y-4">+ <div v-for="group in groupedRecordings" :key="group.title">+ <h4 class="font-medium text-gray-700 mb-2">${ group.title }</h4>+ <ul class="space-y-2">+ <li v-for="recording in group.items"+ :key="recording.id"+ @click="selectRecording(recording)"+ class="cursor-pointer p-2 rounded hover:bg-gray-100 flex justify-between items-center"+ :class="{'bg-blue-50': selectedRecording?.id === recording.id}">+ <span>${ recording.title }</span>+ <div class="flex space-x-2">+ <button @click.stop="editRecording(recording)"+ class="text-blue-500 hover:text-blue-700">+ <i class="fas fa-edit"></i>+ </button>+ <button @click.stop="confirmDelete(recording)"+ class="text-red-500 hover:text-red-700">+ <i class="fas fa-trash"></i>+ </button>+ </div>+ </li>+ </ul>+ </div>+ </div>+ </div>++ <!-- Right side: Selected recording details -->+ <div v-if="selectedRecording" class="col-span-3 bg-white p-6 rounded-lg shadow">+ <div class="flex justify-between items-start mb-4">+ <h3 class="text-xl font-semibold">${ selectedRecording.title }</h3>+ <div class="flex space-x-2">+ <button @click="editRecording(selectedRecording)"+ class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600">+ <i class="fas fa-edit mr-1"></i> Edit+ </button>+ <button @click="confirmDelete(selectedRecording)"+ class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600">+ <i class="fas fa-trash mr-1"></i> Delete+ </button>+ </div>+ </div>+ <div class="grid grid-cols-2 gap-8">+ <div>+ <h4 class="font-medium mb-2">Transcription</h4>+ <div class="h-96 overflow-y-auto p-4 bg-gray-50 rounded">+ ${ selectedRecording.transcription }+ </div>+ </div>+ <div class="space-y-4">+ <div>+ <h4 class="font-medium mb-2">Audio</h4>+ <audio controls class="w-full" :key="selectedRecording.id">+ <source :src="'/audio/' + selectedRecording.id" type="audio/mpeg">+ Your browser does not support the audio element.+ </audio>+ </div>+ <div>+ <h4 class="font-medium mb-2">Participants</h4>+ <p>${ selectedRecording.participants || 'None specified' }</p>+ </div>+ <div>+ <h4 class="font-medium mb-2">Notes</h4>+ <p class="whitespace-pre-wrap">${ selectedRecording.notes || 'No notes' }</p>+ </div>+ <div>+ <h4 class="font-medium mb-2">Created</h4>+ <p>${ new Date(selectedRecording.created_at).toLocaleString() }</p>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Edit Modal -->+ <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">+ <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-lg">+ <h3 class="text-lg font-semibold mb-4">Edit Recording</h3>+ <div class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700">Title</label>+ <input v-model="editingRecording.title"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Participants</label>+ <input v-model="editingRecording.participants"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Notes</label>+ <textarea v-model="editingRecording.notes"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"+ rows="4"></textarea>+ </div>+ <div class="flex justify-end space-x-2">+ <button @click="showEditModal = false"+ class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Cancel+ </button>+ <button @click="saveEdit"+ class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Save+ </button>+ </div>+ </div>+ </div>+ </div>++ <!-- Delete Confirmation Modal -->+ <div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">+ <div class="bg-white p-6 rounded-lg shadow-lg">+ <h3 class="text-lg font-semibold mb-4">Confirm Delete</h3>+ <p>Are you sure you want to delete this recording?</p>+ <p class="text-sm text-gray-500 mb-4">This action cannot be undone.</p>+ <div class="flex justify-end space-x-2">+ <button @click="showDeleteModal = false"+ class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Cancel+ </button>+ <button @click="deleteRecording"+ class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">+ Delete+ </button>+ </div>+ </div>+ </div>+ </div>++ <script>+ const { createApp } = Vue++ createApp({+ data() {+ return {+ currentView: 'upload',+ dragover: false,+ currentRecording: null,+ recordings: [],+ selectedRecording: null,+ showEditModal: false,+ showDeleteModal: false,+ editingRecording: null,+ recordingToDelete: null,+ autoSaveTimeout: null,+ isProcessing: false,+ processingStatus: {+ progress: 0,+ message: ''+ }+ }+ },+ computed: {+ groupedRecordings() {+ const now = new Date()+ const oneWeek = 7 * 24 * 60 * 60 * 1000++ return [+ {+ title: 'This Week',+ items: this.recordings.filter(r => {+ const date = new Date(r.created_at)+ return now - date < oneWeek+ })+ },+ {+ title: 'Last Week',+ items: this.recordings.filter(r => {+ const date = new Date(r.created_at)+ return now - date >= oneWeek && now - date < oneWeek * 2+ })+ },+ {+ title: 'Older',+ items: this.recordings.filter(r => {+ const date = new Date(r.created_at)+ return now - date >= oneWeek * 2+ })+ }+ ]+ }+ },+ delimiters: ['${', '}'], // Changed delimiters to avoid conflicts with Jinja2+ methods: {+ async handleDrop(e) {+ this.dragover = false+ const file = e.dataTransfer.files[0]+ if (file && file.type.startsWith('audio/')) {+ await this.uploadFile(file)+ }+ },+ async handleFileSelect(e) {+ const file = e.target.files[0]+ if (file) {+ await this.uploadFile(file)+ }+ },+ async uploadFile(file) {+ this.isProcessing = true+ this.processingStatus = {+ progress: 0,+ message: 'Starting upload...'+ }++ const formData = new FormData()+ formData.append('file', file)++ try {+ // Upload file+ this.processingStatus = {+ progress: 20,+ message: 'Uploading file...'+ }++ const response = await fetch('/upload', {+ method: 'POST',+ body: formData+ })++ if (!response.ok) {+ throw new Error('Upload failed')+ }++ // Start polling for status+ const data = await response.json()+ if (data.task_id) {+ await this.pollProcessingStatus(data.task_id)+ } else {+ // Handle immediate response+ this.handleProcessingComplete(data)+ }+ } catch (error) {+ alert('Upload failed: ' + error)+ this.isProcessing = false+ }+ },+++ async pollProcessingStatus(taskId) {+ const pollInterval = setInterval(async () => {+ try {+ const response = await fetch(`/status/${taskId}`)+ const data = await response.json()++ this.processingStatus = {+ progress: data.progress,+ message: data.message+ }++ if (data.status === 'completed') {+ clearInterval(pollInterval)+ this.handleProcessingComplete(data.result)+ } else if (data.status === 'failed') {+ clearInterval(pollInterval)+ throw new Error(data.error)+ }+ } catch (error) {+ clearInterval(pollInterval)+ alert('Processing failed: ' + error)+ this.isProcessing = false+ }+ }, 1000)+ },++ handleProcessingComplete(data) {+ this.currentRecording = {+ id: data.id,+ transcription: data.transcription,+ title: '',+ participants: '',+ notes: ''+ }+ this.isProcessing = false+ this.currentView = 'input'+ },++ autoSave() {+ clearTimeout(this.autoSaveTimeout)+ this.autoSaveTimeout = setTimeout(() => {+ this.saveRecording()+ }, 1000)+ },+ async saveRecording() {+ try {+ const response = await fetch('/save', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(this.currentRecording)+ })+ const data = await response.json()++ if (!response.ok) {+ throw new Error(data.error)+ }+ } catch (error) {+ alert('Save failed: ' + error)+ }+ },+ async loadRecordings() {+ try {+ const response = await fetch('/recordings')+ const data = await response.json()+ this.recordings = data+ } catch (error) {+ alert('Failed to load recordings: ' + error)+ }+ },++ editRecording(recording) {+ this.editingRecording = { ...recording };+ this.showEditModal = true;+ },++ async saveEdit() {+ try {+ const response = await fetch('/save', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(this.editingRecording)+ });++ if (!response.ok) {+ throw new Error('Failed to save changes');+ }++ const data = await response.json();++ // Update the recording in the list+ const index = this.recordings.findIndex(r => r.id === this.editingRecording.id);+ if (index !== -1) {+ this.recordings[index] = data.recording;+ if (this.selectedRecording?.id === data.recording.id) {+ this.selectedRecording = data.recording;+ }+ }++ this.showEditModal = false;+ } catch (error) {+ alert('Failed to save changes: ' + error);+ }+ },++ confirmDelete(recording) {+ this.recordingToDelete = recording;+ this.showDeleteModal = true;+ },++ async deleteRecording() {+ try {+ const response = await fetch(`/recording/${this.recordingToDelete.id}`, {+ method: 'DELETE'+ });++ if (!response.ok) {+ throw new Error('Failed to delete recording');+ }++ // Remove from recordings list+ this.recordings = this.recordings.filter(r => r.id !== this.recordingToDelete.id);++ // Clear selected recording if it was deleted+ if (this.selectedRecording?.id === this.recordingToDelete.id) {+ this.selectedRecording = null;+ }++ this.showDeleteModal = false;+ this.recordingToDelete = null;+ } catch (error) {+ alert('Failed to delete recording: ' + error);+ }+ },++ selectRecording(recording) {+ this.selectedRecording = recording+ }+ },+ mounted() {+ this.loadRecordings()+ }+ }).mount('#app')+ </script>+</body>+</html>+```+++## deployment/setup.sh++```bash++#!/bin/bash++# Create directory for the application+sudo mkdir -p /opt/transcription-app+sudo chown $USER:$USER /opt/transcription-app++# Copy application files+cp app.py /opt/transcription-app/+cp -r templates /opt/transcription-app/+cp requirements.txt /opt/transcription-app/+cp reset_db.py /opt/transcription-app/++# Create and activate virtual environment+python3 -m venv /opt/transcription-app/venv+source /opt/transcription-app/venv/bin/activate++# Install requirements+cd /opt/transcription-app+pip install -r requirements.txt++# Create directories for uploads and database with proper permissions+mkdir -p /opt/transcription-app/uploads+mkdir -p /opt/transcription-app/instance+chmod 755 /opt/transcription-app/uploads+chmod 755 /opt/transcription-app/instance++# Initialize the database+python reset_db.py++# Set proper ownership for all files+sudo chown -R $USER:$USER /opt/transcription-app++# Create systemd service file+sudo tee /etc/systemd/system/transcription.service << EOF+[Unit]+Description=Transcription Web Application+After=network.target++[Service]+User=$USER+WorkingDirectory=/opt/transcription-app+Environment="PATH=/opt/transcription-app/venv/bin"+Environment="PYTHONPATH=/opt/transcription-app"+ExecStart=/opt/transcription-app/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8899 app:app+Restart=always+RestartSec=5++[Install]+WantedBy=multi-user.target+EOF++# Reload systemd and start service+sudo systemctl daemon-reload+sudo systemctl restart transcription+sudo systemctl enable transcription++# Check service status+echo "Checking service status..."+sleep 3+sudo systemctl status transcription++echo "Installation complete! The application should be running on port 8899."+```diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 00000000..44947cd8--- /dev/null+++ b/requirements.txt@@ -0,0 +1,5 @@+flask==2.3.3+flask-sqlalchemy==3.1.1+openai==1.3.0+werkzeug==2.3.7+gunicorn==21.2.0\ No newline at end of filediff --git a/reset_db.py b/reset_db.pynew file mode 100644index 00000000..1d944baf--- /dev/null+++ b/reset_db.py@@ -0,0 +1,60 @@+#!/usr/bin/env python3++# Add this near the top if you run this standalone often outside app context+import os+import sys+# Add project root to path if necessary for 'app' import+# sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Adjust path as needed++# Check if running within app context already (e.g., via Flask command)+try:+ from flask import current_app+ app = current_app._get_current_object()+ db = app.extensions['sqlalchemy'].db # Access db via extensions typical pattern+except RuntimeError:+ # If not in app context, import directly (assuming reset_db.py is at the same level as app.py)+ # This might be needed if running `python reset_db.py` directly+ try:+ from app import app, db+ except ImportError:+ print("Error: Could not import 'app' and 'db'. Ensure reset_db.py is runnable.")+ print("Make sure your PYTHONPATH includes the project directory or run using 'flask run <command>'")+ sys.exit(1)+++def reset_database():+ # Determine the database path relative to the instance folder+ # Assuming app is configured with instance_relative_config=True (default)+ # or manually construct path if instance folder is known+ instance_path = app.instance_path if hasattr(app, 'instance_path') else os.path.join(os.getcwd(), 'instance')+ db_filename = app.config.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///instance/transcriptions.db').split('/')[-1]+ db_path = os.path.join(instance_path, db_filename)++ # Ensure instance directory exists+ os.makedirs(instance_path, exist_ok=True)++ # Remove existing database if it exists+ if os.path.exists(db_path):+ print(f"Removing existing database at {db_path}")+ try:+ os.remove(db_path)+ except OSError as e:+ print(f"Error removing database file: {e}. Check permissions or if it's in use.")+ # Optionally exit or continue to create tables anyway+ # sys.exit(1)++ # Create application context to work with the database+ with app.app_context():+ print("Creating new database schema...")+ # Create all tables defined in models+ try:+ db.create_all()+ print("Database schema created successfully!")+ except Exception as e:+ print(f"Error creating database schema: {e}")+ sys.exit(1)++if __name__ == "__main__":+ print("Attempting to reset the database...")+ reset_database()+ print("Database reset process finished.")\ No newline at end of filediff --git a/templates/index.html b/templates/index.htmlnew file mode 100644index 00000000..372dd337--- /dev/null+++ b/templates/index.html@@ -0,0 +1,680 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Audio Transcription App</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+</head>+<body class="bg-gray-100">+ <div id="app" class="container mx-auto px-4 py-8">+ <nav class="flex justify-between mb-8 items-center">+ <h1 class="text-2xl font-bold">Audio Transcription</h1>+ <div>+ <button @click="switchToUploadView" class="px-4 py-2 mr-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ <i class="fas fa-plus mr-1"></i> New Recording+ </button>+ <button @click="switchToGalleryView" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ <i class="fas fa-images mr-1"></i> Gallery+ </button>+ </div>+ </nav>++ <div v-if="globalError" class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded" role="alert">+ <strong class="font-bold">Error:</strong>+ <span class="block sm:inline">${ globalError }</span>+ </div>++ <div v-if="currentView === 'upload'"+ @dragover.prevent="dragover = true"+ @dragleave.prevent="dragover = false"+ @drop.prevent="handleDrop"+ :class="{'border-blue-500 bg-blue-50': dragover, 'border-gray-300': !dragover}"+ class="border-2 border-dashed rounded-lg p-12 text-center transition-all duration-200 bg-white shadow">++ <div v-if="isProcessing" class="space-y-4">+ <div class="animate-spin mx-auto h-12 w-12">+ <i class="fas fa-circle-notch text-4xl text-blue-500"></i>+ </div>+ <h2 class="text-xl mb-2">Processing your audio file...</h2>+ <p class="text-sm text-gray-600 mt-2">${ processingStatus.message }</p>+ <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mt-4 max-w-md mx-auto">+ <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: processingStatus.progress + '%' }"></div>+ </div>+ </div>++ <div v-else>+ <i class="fas fa-cloud-upload-alt text-4xl mb-4 text-blue-500"></i>+ <h2 class="text-xl mb-2">Drag and drop your audio file here</h2>+ <p class="text-gray-500">or</p>+ <input type="file" @change="handleFileSelect" accept="audio/*" class="hidden" ref="fileInput">+ <button @click="$refs.fileInput.click()" class="mt-4 px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Select File+ </button>+ <p class="text-xs text-gray-500 mt-4">Max file size: 250 MB</p>+ </div>+ </div>++ <div v-if="currentView === 'input' && currentRecording" class="grid md:grid-cols-2 gap-8">+ <div class="bg-white p-6 rounded-lg shadow">+ <h3 class="text-lg font-semibold mb-4">Transcription</h3>+ <div class="h-96 overflow-y-auto p-4 bg-gray-50 rounded border border-gray-200">+ <pre class="whitespace-pre-wrap text-sm">${ currentRecording.transcription || 'Transcription not available.' }</pre>+ </div>+ </div>++ <div class="bg-white p-6 rounded-lg shadow">+ <h3 class="text-lg font-semibold mb-4">Recording Details</h3>+ <div class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700">Title</label>+ <input v-model="currentRecording.title"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Participants</label>+ <input v-model="currentRecording.participants"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Notes</label>+ <textarea v-model="currentRecording.notes"+ @input="autoSave"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"+ rows="4"></textarea>+ </div>+ <div class="text-sm text-gray-500">+ <p>File Size: ${ formatFileSize(currentRecording.file_size) }</p>+ <p>Created: ${ new Date(currentRecording.created_at).toLocaleString() }</p>+ </div>+ <div class="pt-4 text-right">+ <button @click="switchToGalleryView" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Back to Gallery+ </button>+ </div>+ </div>+ </div>+ </div>+++ <div v-if="currentView === 'gallery'" class="grid lg:grid-cols-4 gap-8">+ <div class="lg:col-span-1 bg-white p-4 rounded-lg shadow overflow-y-auto max-h-[80vh]">+ <h3 class="text-lg font-semibold mb-4 sticky top-0 bg-white pb-2 border-b">Recordings</h3>+ <div v-if="recordings.length === 0" class="text-center text-gray-500 py-4">+ No recordings yet. Upload one!+ </div>+ <div v-else class="space-y-4">+ <div v-for="group in groupedRecordings" :key="group.title">+ <h4 v-if="group.items.length > 0" class="font-medium text-gray-700 mb-2 text-sm uppercase tracking-wide">${ group.title }</h4>+ <ul class="space-y-1">+ <li v-for="recording in group.items"+ :key="recording.id"+ @click="selectRecording(recording)"+ class="cursor-pointer p-2 rounded hover:bg-gray-100 flex justify-between items-center text-sm"+ :class="{'bg-blue-100 hover:bg-blue-200': selectedRecording?.id === recording.id}">+ <span class="truncate pr-2">${ recording.title }</span>+ <div class="flex space-x-2 flex-shrink-0">+ <span v-if="recording.status === 'PROCESSING' || recording.status === 'PENDING'" class="text-xs text-blue-500 italic">Processing...</span>+ <span v-else-if="recording.status === 'FAILED'" class="text-xs text-red-500 italic">Failed</span>+ <button @click.stop="editRecording(recording)"+ class="text-blue-500 hover:text-blue-700 text-xs" title="Edit Details">+ <i class="fas fa-edit"></i>+ </button>+ <button @click.stop="confirmDelete(recording)"+ class="text-red-500 hover:text-red-700 text-xs" title="Delete Recording">+ <i class="fas fa-trash"></i>+ </button>+ </div>+ </li>+ </ul>+ </div>+ </div>+ </div>++ <div v-if="selectedRecording" class="lg:col-span-3 bg-white p-6 rounded-lg shadow">+ <div class="flex justify-between items-start mb-4 border-b pb-3">+ <div>+ <h3 class="text-xl font-semibold">${ selectedRecording.title }</h3>+ <p class="text-sm text-gray-500">Created: ${ new Date(selectedRecording.created_at).toLocaleString() } (${ formatFileSize(selectedRecording.file_size) })</p>+ <span v-if="selectedRecording.status === 'PROCESSING' || selectedRecording.status === 'PENDING'" class="mt-1 inline-block px-2 py-0.5 text-xs font-semibold text-blue-800 bg-blue-100 rounded-full">Status: Processing</span>+ <span v-else-if="selectedRecording.status === 'FAILED'" class="mt-1 inline-block px-2 py-0.5 text-xs font-semibold text-red-800 bg-red-100 rounded-full">Status: Failed</span>+ <span v-else-if="selectedRecording.status === 'COMPLETED'" class="mt-1 inline-block px-2 py-0.5 text-xs font-semibold text-green-800 bg-green-100 rounded-full">Status: Completed</span>+ </div>+ <div class="flex space-x-2 flex-shrink-0">+ <button @click="editRecording(selectedRecording)"+ class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm">+ <i class="fas fa-edit mr-1"></i> Edit Details+ </button>+ <button @click="confirmDelete(selectedRecording)"+ class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm">+ <i class="fas fa-trash mr-1"></i> Delete+ </button>+ </div>+ </div>+ <div class="grid md:grid-cols-2 gap-8">+ <div>+ <h4 class="font-medium mb-2">Transcription</h4>+ <div v-if="selectedRecording.status === 'COMPLETED'" class="h-96 overflow-y-auto p-4 bg-gray-50 rounded border text-sm">+ <pre class="whitespace-pre-wrap">${ selectedRecording.transcription || 'No transcription available.' }</pre>+ </div>+ <div v-else-if="selectedRecording.status === 'FAILED'" class="h-96 overflow-y-auto p-4 bg-red-50 rounded border text-sm text-red-700">+ <p><strong>Transcription Failed:</strong></p>+ <pre class="whitespace-pre-wrap mt-2">${ selectedRecording.transcription || 'An unknown error occurred.' }</pre>+ </div>+ <div v-else class="h-96 flex items-center justify-center p-4 bg-gray-50 rounded border text-gray-500">+ <i class="fas fa-spinner fa-spin mr-2"></i> Transcription in progress...+ </div>+ </div>+ <div class="space-y-4">+ <div>+ <h4 class="font-medium mb-2">Audio Player</h4>+ <audio controls class="w-full" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id">+ Your browser does not support the audio element.+ </audio>+ </div>+ <div>+ <h4 class="font-medium mb-1">Participants</h4>+ <p class="text-sm bg-gray-50 p-2 rounded border">${ selectedRecording.participants || 'None specified' }</p>+ </div>+ <div>+ <h4 class="font-medium mb-1">Notes</h4>+ <pre class="text-sm bg-gray-50 p-2 rounded border whitespace-pre-wrap h-40 overflow-y-auto">${ selectedRecording.notes || 'No notes' }</pre>+ </div>++ </div>+ </div>+ </div>+ <div v-else class="lg:col-span-3 flex items-center justify-center bg-white p-6 rounded-lg shadow text-gray-500">+ Select a recording from the list to view details.+ </div>+ </div>++ <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">+ <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-lg">+ <h3 class="text-lg font-semibold mb-4">Edit Recording Details</h3>+ <div v-if="editingRecording" class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700">Title</label>+ <input v-model="editingRecording.title"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Participants</label>+ <input v-model="editingRecording.participants"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700">Notes</label>+ <textarea v-model="editingRecording.notes"+ class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"+ rows="4"></textarea>+ </div>+ <div class="flex justify-end space-x-2 pt-4">+ <button @click="cancelEdit"+ class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Cancel+ </button>+ <button @click="saveEdit"+ class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Save Changes+ </button>+ </div>+ </div>+ </div>+ </div>++ <div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">+ <div class="bg-white p-6 rounded-lg shadow-lg max-w-sm">+ <h3 class="text-lg font-semibold mb-4">Confirm Delete</h3>+ <p v-if="recordingToDelete" class="mb-2">Are you sure you want to delete the recording titled "<strong>${ recordingToDelete.title }</strong>"?</p>+ <p class="text-sm text-gray-600 mb-4">This action cannot be undone and will delete both the record and the audio file.</p>+ <div class="flex justify-end space-x-2">+ <button @click="cancelDelete"+ class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">+ Cancel+ </button>+ <button @click="deleteRecording"+ class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">+ Delete Permanently+ </button>+ </div>+ </div>+ </div>+ </div>++ <script>+ const { createApp, ref, reactive, computed, onMounted, watch } = Vue++ createApp({+ setup() {+ const currentView = ref('gallery'); // Start with gallery+ const dragover = ref(false);+ const currentRecording = ref(null); // For the input view after upload+ const recordings = ref([]); // Full list for gallery+ const selectedRecording = ref(null); // For gallery detail view+ const showEditModal = ref(false);+ const showDeleteModal = ref(false);+ const editingRecording = ref(null); // Temp object for modal+ const recordingToDelete = ref(null); // Temp object for modal+ const autoSaveTimeout = ref(null);+ const isProcessing = ref(false); // Controls upload/processing spinner+ const processingStatus = reactive({ progress: 0, message: '' });+ const pollInterval = ref(null);+ const globalError = ref(null); // For displaying errors to the user++ // --- Computed Properties ---+ const groupedRecordings = computed(() => {+ const groups = { today: [], yesterday: [], thisWeek: [], older: [] };+ const now = new Date();+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ const yesterdayStart = new Date(todayStart);+ yesterdayStart.setDate(todayStart.getDate() - 1);+ const weekStart = new Date(todayStart);+ weekStart.setDate(todayStart.getDate() - now.getDay()); // Assuming Sunday is start of week (0)++ recordings.value.forEach(r => {+ const date = new Date(r.created_at);+ if (date >= todayStart) groups.today.push(r);+ else if (date >= yesterdayStart) groups.yesterday.push(r);+ else if (date >= weekStart) groups.thisWeek.push(r);+ else groups.older.push(r);+ });++ return [+ { title: 'Today', items: groups.today },+ { title: 'Yesterday', items: groups.yesterday },+ { title: 'This Week', items: groups.thisWeek },+ { title: 'Older', items: groups.older }+ ].filter(g => g.items.length > 0); // Only show groups with items+ });++ // --- Methods ---+ const setGlobalError = (message) => {+ globalError.value = message;+ // Optionally clear the error after some time+ setTimeout(() => { globalError.value = null; }, 5000);+ };++ const formatFileSize = (bytes) => {+ if (bytes === 0 || !bytes) return '0 Bytes';+ const k = 1024;+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];+ };++ const switchToUploadView = () => {+ currentView.value = 'upload';+ selectedRecording.value = null; // Clear selection when switching+ isProcessing.value = false; // Ensure processing state is reset+ processingStatus.message = '';+ processingStatus.progress = 0;+ };++ const switchToGalleryView = async () => {+ await loadRecordings(); // Refresh recordings when going to gallery+ currentView.value = 'gallery';+ currentRecording.value = null; // Clear input view state+ isProcessing.value = false; // Ensure processing state is reset+ };++ const handleDrop = (e) => {+ dragover.value = false;+ const file = e.dataTransfer.files[0];+ if (file && file.type.startsWith('audio/')) {+ uploadFile(file);+ } else if (file) {+ setGlobalError('Invalid file type. Please upload an audio file.');+ }+ };++ const handleFileSelect = (e) => {+ const file = e.target.files[0];+ if (file) {+ uploadFile(file);+ }+ // Reset file input to allow selecting the same file again+ e.target.value = null;+ };++ const uploadFile = async (file) => {+ globalError.value = null; // Clear previous errors+ isProcessing.value = true;+ processingStatus.message = 'Preparing upload...';+ processingStatus.progress = 5;++ const formData = new FormData();+ formData.append('file', file);++ try {+ processingStatus.message = 'Uploading file...';+ processingStatus.progress = 10;++ const response = await fetch('/upload', {+ method: 'POST',+ body: formData+ });++ const data = await response.json();++ if (!response.ok) {+ // Handle specific errors like 413 Payload Too Large+ if (response.status === 413) {+ throw new Error(data.error || `File is too large. Maximum size: ${data.max_size_mb?.toFixed(0) || 'N/A'} MB.`);+ }+ throw new Error(data.error || `Upload failed with status ${response.status}`);+ }++ if (response.status === 202 && data.id) { // 202 Accepted+ processingStatus.message = 'Upload complete. Starting transcription...';+ processingStatus.progress = 30;+ // Start polling for the status using the returned recording ID+ // await loadRecordings(); // Add the new pending recording to the list+ recordings.value.unshift(data);+ pollProcessingStatus(data.id);+ } else {+ // Should not happen with the new backend logic, but handle defensively+ throw new Error('Unexpected response from server after upload.');+ }++ } catch (error) {+ console.error('Upload Error:', error);+ setGlobalError(`Upload failed: ${error.message}`);+ isProcessing.value = false;+ currentView.value = 'upload'; // Stay on upload view on error+ }+ };++ const pollProcessingStatus = (recordingId) => {+ // Clear any existing interval first+ if (pollInterval.value) {+ clearInterval(pollInterval.value);+ }++ processingStatus.message = 'Transcription queued...';+ processingStatus.progress = 40;++ pollInterval.value = setInterval(async () => {+ try {+ console.log(`Polling status for recording ID: ${recordingId}`);+ const response = await fetch(`/status/${recordingId}`);+ if (!response.ok) {+ // If record not found (404) or server error, stop polling+ throw new Error(`Status check failed with status ${response.status}`);+ }+ const data = await response.json();++ // Update list data if available+ const index = recordings.value.findIndex(r => r.id === recordingId);+ if (index !== -1) {+ recordings.value[index] = data;+ // If this is the selected recording, update it too+ if(selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data;+ }+ }++ if (data.status === 'COMPLETED') {+ processingStatus.message = 'Transcription complete!';+ processingStatus.progress = 100;+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ handleProcessingComplete(data); // Pass the final data+ } else if (data.status === 'FAILED') {+ processingStatus.message = 'Transcription failed.';+ processingStatus.progress = 0; // Indicate failure visually+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ setGlobalError(`Transcription failed for "${data.title || 'recording ' + data.id}". Check gallery for details.`);+ isProcessing.value = false;+ currentView.value = 'gallery'; // Go to gallery to see the failed item+ selectRecording(data); // Select the failed item+ } else if (data.status === 'PROCESSING') {+ processingStatus.message = 'Transcription in progress...';+ processingStatus.progress = 60; // Intermediate progress+ } else { // PENDING+ processingStatus.message = 'Waiting for transcription to start...';+ processingStatus.progress = 45;+ }+ } catch (error) {+ console.error('Polling Error:', error);+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ setGlobalError(`Error checking transcription status: ${error.message}`);+ isProcessing.value = false;+ // Decide where to navigate the user, maybe back to gallery+ currentView.value = 'gallery';+ }+ }, 3000); // Poll every 3 seconds+ };++ const handleProcessingComplete = (recordingData) => {+ // Update the recording list again just in case+ const index = recordings.value.findIndex(r => r.id === recordingData.id);+ if (index !== -1) {+ recordings.value[index] = recordingData;+ } else {+ recordings.value.unshift(recordingData); // Add if somehow missed+ }++ currentRecording.value = recordingData; // Set for the input view+ isProcessing.value = false;+ currentView.value = 'input'; // Switch to the input view to show result+ };++ const autoSave = () => {+ clearTimeout(autoSaveTimeout.value);+ autoSaveTimeout.value = setTimeout(() => {+ // Save only if in 'input' view and have a current recording+ if (currentView.value === 'input' && currentRecording.value) {+ saveMetadata(currentRecording.value);+ }+ // No auto-save needed in edit modal (uses explicit save button)+ }, 1000); // Save after 1 second of inactivity+ };++ // General function to save metadata (used by autosave and modal save)+ const saveMetadata = async (recordingDataToSave) => {+ globalError.value = null;+ if (!recordingDataToSave || !recordingDataToSave.id) return;++ console.log('Saving metadata for:', recordingDataToSave.id);+ try {+ const response = await fetch('/save', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ id: recordingDataToSave.id,+ title: recordingDataToSave.title,+ participants: recordingDataToSave.participants,+ notes: recordingDataToSave.notes+ })+ });+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Failed to save metadata');+ }+ console.log('Save successful:', data.recording.id);+ // Update the recording in the main list+ const index = recordings.value.findIndex(r => r.id === data.recording.id);+ if (index !== -1) {+ recordings.value[index] = { ...recordings.value[index], ...data.recording }; // Merge updates+ // If the updated item is the selected one in gallery, update it there too+ if (selectedRecording.value?.id === data.recording.id) {+ selectedRecording.value = { ...selectedRecording.value, ...data.recording };+ }+ }+ return data.recording; // Return updated data+ } catch (error) {+ console.error('Save Metadata Error:', error);+ setGlobalError(`Save failed: ${error.message}`);+ return null; // Indicate failure+ }+ };++ const loadRecordings = async () => {+ globalError.value = null;+ try {+ const response = await fetch('/recordings');+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Failed to load recordings');+ }+ recordings.value = data;++ // Check if any recordings are still processing and start polling for them+ recordings.value.forEach(r => {+ if ((r.status === 'PENDING' || r.status === 'PROCESSING') && !isProcessing.value) {+ // Avoid multiple pollers if one is already running from upload+ console.log(`Found pending/processing recording on load: ${r.id}. Starting poll.`);+ // Note: This might start multiple pollers if called frequently.+ // A more robust solution would track active pollers.+ pollProcessingStatus(r.id);+ }+ });++ } catch (error) {+ console.error('Load Recordings Error:', error);+ setGlobalError(`Failed to load recordings: ${error.message}`);+ recordings.value = []; // Clear list on error+ }+ };++ const selectRecording = (recording) => {+ selectedRecording.value = recording;+ // If the selected recording is processing, ensure polling is active+ if ((recording.status === 'PENDING' || recording.status === 'PROCESSING') && !isProcessing.value) {+ pollProcessingStatus(recording.id);+ }+ };++ const editRecording = (recording) => {+ // Create a deep copy for editing to avoid modifying the original object directly+ editingRecording.value = JSON.parse(JSON.stringify(recording));+ showEditModal.value = true;+ };++ const cancelEdit = () => {+ showEditModal.value = false;+ editingRecording.value = null;+ };++ const saveEdit = async () => {+ const updatedRecording = await saveMetadata(editingRecording.value);+ if (updatedRecording) { // Check if save was successful+ // Update the selected recording if it's the one being edited+ if (selectedRecording.value?.id === updatedRecording.id) {+ selectedRecording.value = updatedRecording;+ }+ cancelEdit(); // Close modal+ } else {+ // Keep modal open if save failed, error is shown via setGlobalError+ }+ };++ const confirmDelete = (recording) => {+ recordingToDelete.value = recording;+ showDeleteModal.value = true;+ };++ const cancelDelete = () => {+ showDeleteModal.value = false;+ recordingToDelete.value = null;+ };++ const deleteRecording = async () => {+ globalError.value = null;+ if (!recordingToDelete.value) return;++ const idToDelete = recordingToDelete.value.id;+ try {+ const response = await fetch(`/recording/${idToDelete}`, {+ method: 'DELETE'+ });+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Failed to delete recording');+ }++ // Remove from recordings list+ recordings.value = recordings.value.filter(r => r.id !== idToDelete);++ // Clear selected recording if it was deleted+ if (selectedRecording.value?.id === idToDelete) {+ selectedRecording.value = null;+ }++ cancelDelete(); // Close modal+ } catch (error) {+ console.error('Delete Error:', error);+ setGlobalError(`Failed to delete recording: ${error.message}`);+ // Keep modal open on error? Or close? Let's close it.+ cancelDelete();+ }+ };++ // --- Lifecycle Hooks ---+ onMounted(() => {+ loadRecordings(); // Load recordings when the app mounts+ // Set default view+ currentView.value = 'gallery';+ });++ // Watch for view changes to potentially stop polling if navigating away from processing view+ watch(currentView, (newView, oldView) => {+ if (newView !== 'upload' && newView !== 'input' && pollInterval.value) {+ // If navigating away from upload/input views while polling, consider stopping it+ // Or let it run in the background? For now, let's let it run.+ // console.log("Navigated away, polling continues in background.");+ }+ if (newView === 'gallery' && oldView !== 'gallery') {+ loadRecordings(); // Refresh gallery when navigating to it+ }+ });+++ return {+ currentView,+ dragover,+ currentRecording,+ recordings,+ selectedRecording,+ showEditModal,+ showDeleteModal,+ editingRecording,+ recordingToDelete,+ isProcessing,+ processingStatus,+ globalError,+ groupedRecordings,+ handleDrop,+ handleFileSelect,+ uploadFile,+ // pollProcessingStatus, // Not directly called from template+ // handleProcessingComplete, // Not directly called+ autoSave,+ // saveMetadata, // Internal helper+ loadRecordings,+ selectRecording,+ editRecording,+ cancelEdit,+ saveEdit,+ confirmDelete,+ cancelDelete,+ deleteRecording,+ switchToUploadView,+ switchToGalleryView,+ formatFileSize,+ setGlobalError+ }+ },+ delimiters: ['${', '}'] // Keep custom delimiters+ }).mount('#app');+ </script>++</body>+</html>\ No newline at end of file