Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
## Major UI Overhaul Summary
Murtaza Nasir4d15fb07cc8b
diff --git a/.env.example b/.env.exampleindex 86d423e2..bf249304 100644--- a/.env.example+++ b/.env.example@@ -16,6 +16,10 @@ WHISPER_MODEL="Systran/faster-distil-whisper-large-v3"# Use a valid TZ database name (e.g., "America/New_York", "Europe/London", "UTC").TIMEZONE="UTC"+# Set the logging level for the application.+# Options: DEBUG, INFO, WARNING, ERROR+LOG_LEVEL="INFO"+# Set to "false" to disable new account registrationALLOW_REGISTRATION="false"diff --git a/DEPLOYMENT_GUIDE.md b/DEPLOYMENT_GUIDE.mdindex 87ddfcf5..d7a8fb7f 100644--- a/DEPLOYMENT_GUIDE.md+++ b/DEPLOYMENT_GUIDE.md@@ -661,18 +661,26 @@ docker exec -it speakr sqlite3 /data/instance/transcriptions.db## Browser Recording Feature-Speakr includes a built-in browser recording feature available in the "New Recording" screen. This allows you to record audio directly from your browser's microphone without needing external recording software.+Speakr includes a powerful in-browser recording feature on the "New Recording" screen, allowing you to capture audio directly without external software.-### Important Requirements+### Recording Modes-**For HTTPS/SSL Sites:**-- Recording works automatically on sites with valid SSL certificates-- No additional configuration needed+- **Microphone:** Records audio from your microphone. This is ideal for dictating notes or recording your side of a conversation.+- **System Audio:** Captures all audio playing from your computer, such as online meetings (Zoom, Teams), videos, or other applications.+- **Both:** Reliably records both your microphone and system audio simultaneously into a single audio track. This is the recommended mode for capturing online meetings where you are an active participant.-**For HTTP Sites (Development/Local):**-Modern browsers require HTTPS for microphone access due to security policies. For development or local deployments without SSL, you need to enable browser flags:+### Important Requirements for System Audio-#### Google Chrome: Allow Microphone on HTTP Sites+The ability to record **system audio** (and therefore "both") relies on the browser's Screen Capture API. For security reasons, this API has strict requirements:++- **HTTPS is Mandatory:** You **must** access Speakr through a secure `https://` connection. This feature will not work over `http://`, with the exception of `http://localhost`.+- **User Permission:** When you start a system audio recording, your browser will prompt you to share your screen. You must select a screen or tab to share and **ensure you check the "Share system audio" (or similar) checkbox to grant permission.** Recording audio from a single application window is often not supported.++### Local Development Setup (HTTP)++For local development without setting up SSL, most browsers will block the system audio recording feature. To enable it for testing on `http://localhost`:++#### Google Chrome (Recommended)1. **Open Chrome**2. Go to: `chrome://flags`@@ -691,11 +699,13 @@ Modern browsers require HTTPS for microphone access due to security policies. Fo5. Double-click to change from `false` to `true`6. Restart Firefox-> **⚠️ Security Warning:** These settings reduce browser security. Only use for development/testing. For production deployments, always use HTTPS with valid SSL certificates.+**Note on Firefox System Audio:** While the above setting enables microphone recording on HTTP, Firefox's security model is very strict regarding system audio. As of recent tests, capturing system audio (and therefore "Both" mode) does not work reliably in Firefox even with SSL. **For system audio recording, Chrome is the recommended browser.**++> **⚠️ Security Warning:** Modifying browser flags reduces security. Only use these settings for local development and testing. For production deployments, **always use HTTPS with a valid SSL certificate.**### Production Deployment with SSL-For production use, deploy behind a reverse proxy with SSL:+For production use, it is essential to deploy Speakr behind a reverse proxy that handles SSL/TLS termination. This ensures the application is served over HTTPS, enabling all recording features securely.**Example with Nginx:**```nginx@@ -718,6 +728,7 @@ server {**Example with Traefik:**```yaml+# In your docker-compose.yml for the Speakr servicelabels:- "traefik.enable=true"- "traefik.http.routers.speakr.rule=Host(`your-domain.com`)"@@ -727,12 +738,12 @@ labels:### Recording Workflow-1. **Access Recording:** Go to "New Recording" screen-2. **Start Recording:** Click the record button (requires microphone permission)-3. **Record Audio:** Speak into your microphone-4. **Stop Recording:** Click stop when finished-5. **Upload:** Click upload to process the recording using your configured transcription service--**Note:** This is not live transcription - the audio is recorded first, then transcribed using your regular workflow (either OpenAI API or ASR endpoint).+1. **Access Recording:** Go to the "New Recording" screen.+2. **Choose Mode:** Select "Microphone", "System Audio", or "Both".+3. **Grant Permissions:**+ - For **Microphone**, allow access when prompted.+ - For **System Audio** or **Both**, select a screen or tab to share and **ensure you check the "Share system audio" box**.+4. **Record:** The visualizer(s) will confirm that audio is being captured.+5. **Stop & Upload:** Stop the recording when finished and click "Upload" to process it.This guide should cover all the deployment scenarios you need. Choose the method that best fits your infrastructure and requirements!diff --git a/README.md b/README.mdindex c11729e3..973765dd 100644--- a/README.md+++ b/README.md@@ -4,10 +4,12 @@This project is dual-licensed. See the [License](#license) section for details.-Speakr is a personal, self-hosted web application designed for transcribing audio recordings (like meetings), generating concise summaries and titles, and interacting with the content through a chat interface. Keep all your meeting notes and insights securely on your own server.+Speakr is your intelligent note-taking companion - a personal, self-hosted web application that transforms audio recordings into organized, searchable notes. Whether you're capturing meetings on your phone, recording lectures, or documenting interviews, Speakr automatically transcribes your audio with speaker identification, generates concise summaries, and lets you interact with your content through an AI chat interface. Keep all your notes and insights securely on your own server, accessible from any device.++**Perfect for mobile note-taking:** Start the app on your phone, hit record, and get back diarized transcriptions that identify who said what - turning any conversation into structured, searchable notes.<div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">- <img src="static/img/hero-shot.png" alt="Hero Shot" style="max-width: 48%; height: auto;"/>+ <img src="static/img/main.png" alt="Hero Shot" style="max-width: 48%; height: auto;"/><img src="static/img/multilingual-support.png" alt="Multilingual Support" style="max-width: 48%; height: auto;"/></div>@@ -70,50 +72,47 @@ Speakr is a personal, self-hosted web application designed for transcribing audi</details><details>-<summary><strong>ASR and API Options</strong></summary>+<summary><strong>Record Meetings & Take Notes</strong></summary><div style="display: flex; justify-content: space-around; flex-wrap: wrap;"><figure>- <img src="static/img/transcription-with-asr.png" alt="Transcription with ASR" width="400"/>- <figcaption style="text-align: center;">With ASR Webservice</figcaption>+ <img src="static/img/rec1.png" alt="Transcription with ASR" width="400"/>+ <figcaption style="text-align: center;">Recording options</figcaption></figure><figure>- <img src="static/img/transcription-without-asr.png" alt="Transcription without ASR" width="400"/>- <figcaption style="text-align: center;">With OpenAI-Compatible API</figcaption>+ <img src="static/img/rec2.png" alt="Transcription without ASR" width="400"/>+ <figcaption style="text-align: center;">Record Phone/Computer Microphone</figcaption></figure>-</div>-</details>--<details>-<summary><strong>Advanced Features</strong></summary>-<div style="display: flex; justify-content: space-around; flex-wrap: wrap;">- <figure>- <img src="static/img/reprocessing-transcript.png" alt="Reprocessing Transcript" width="400"/>- <figcaption style="text-align: center;">Reprocess with New Settings</figcaption>+ <figure>+ <img src="static/img/rec3.png" alt="Transcription without ASR" width="400"/>+ <figcaption style="text-align: center;">Record both Microphone and Computer Sounds (e.g., zoom meeting)</figcaption></figure></div></details>## What's New?-* **Simplified Docker Setup:** Configuration is now managed via a single `.env` file, making setup faster and easier.-* **Advanced ASR Integration:** Added support for ASR endpoints using the [`onerahmet/openai-whisper-asr-webservice`](https://github.com/ahmetoner/whisper-asr-webservice) package. This integration is necessary for the speaker diarization feature.-* **Speaker Diarization:** Identify and label different speakers in your recordings. **Note: This feature requires the ASR Webservice method with the `whisperx` engine.**-* **Speaker Auto-Detection:** When using speaker diarization, the system can automatically attemtpt to detect participant names based on the transcript, so you don't have to specify it manually. **(/ASR method only)**-* **Clickable Timestamps:** Each transcribed sentence now includes a timestamp. Clicking it will jump the audio player to that specific point in the recording, making it easier to identify speakers and verify transcription accuracy. **(/ASR method only)**-* **Intuitive Speaker Labeling:** A new, more intuitive interface for identifying and labeling speakers. **(/ASR method only)**-* **Transcription Reprocessing:** A new "Reprocess" button allows you to re-run transcription with different settings (e.g., to add diarization).-* **Speaker Identification:** A new modal helps you name speakers, with highlighting for clarity. You can also automatically identify speakers using an LLM. **(/ASR method only)**-* **Saved Speaker Profiles:** Save identified speakers for auto-completion in future transcriptions. View and manage them on your Account page. **(/ASR method only)**-* **Enhanced Summaries:** Summarization now includes user context (name, title) and allows for custom prompts.-* **Streaming Chat Responses:** The chat interface now streams responses, providing a more interactive and responsive experience.-* **UI Preferences Saved:** Your preferences for audio volume and transcription view (simple vs. bubble) are now saved locally in your browser and automatically applied on your next visit.-* **Last Viewed Recording:** The application now remembers the last recording you viewed and will take you there directly when you revisit the page.-* **Performance Tracking:** The processing time for transcriptions is now tracked and displayed, giving you insight into the performance of your setup.+* **Secure Sharing System:** Share your transcriptions publicly with customizable permissions - control whether to include summaries and notes, manage shared links, and revoke access anytime.+* **Enhanced Recording & Note-Taking:** Completely redesigned recording interface with real-time notepad during recording. Perfect for mobile note-taking with improved system audio capture and dual visualizers.+* **Advanced Speaker Diarization:** Automatically identify and label different speakers in your recordings with AI-powered speaker detection and saved speaker profiles for future sessions.+* **Mobile-Optimized Experience:** Seamless recording and note-taking on phones and tablets - start recording on your phone and get back diarized transcriptions with speaker identification.+* **Automated File Processing:** "Black hole" directory feature for automatic audio file processing - drag and drop recordings from your computer's audio devices for instant transcription.+* **AMR File Support:** Added support for AMR audio files commonly used by mobile devices and voice recorders.+* **Transcript Editing:** Edit and update transcriptions in both simple and ASR modes to perfect your notes.+* **Enhanced Markdown Editor:** Improved summary and notes editor with markdown support for better formatting and organization.+* **Configurable Logging:** Dynamic logging control for better debugging and troubleshooting.+* **Clickable Timestamps:** Jump to specific points in recordings by clicking timestamps in transcriptions for easy verification and speaker identification.+* **Streaming Chat Responses:** Interactive AI chat with real-time streaming responses for better user experience.## Features-* **Audio Upload:** Upload audio files (MP3, WAV, M4A, etc. depending on your transcription endpoint) via drag-and-drop or file selection.-* **Browser Recording:** Record audio directly in your browser from the "New Recording" screen (requires HTTPS or browser configuration for HTTP - see [Deployment Guide](DEPLOYMENT_GUIDE.md#browser-recording-feature)).+* **Audio Upload:** Upload audio files (MP3, WAV, M4A, AMR, and many other formats) via drag-and-drop or file selection.+* **Automated File Processing:** "Black hole" directory monitoring for automatic batch processing of audio files without manual uploads.+* **Advanced Browser Recording:** Record audio directly in your browser with multiple options:+ * **Microphone:** Record your voice.+ - **System Audio:** Capture audio from other applications (e.g., online meetings). **Note: To record system audio, you must select to share a "tab" or "screen" in your browser's screen sharing prompt and ensure the "share audio" checkbox is enabled.**+ - **Both:** Reliably record both your microphone and system audio simultaneously.+ * Features dual real-time audio visualizers.+ * *(Note: System audio capture requires a secure context (HTTPS) or specific browser configuration. See the [Deployment Guide](DEPLOYMENT_GUIDE.md#browser-recording-feature) for details.)** **Transcription:** Choose between a standard OpenAI-compatible API or a more advanced ASR Webservice.* **Speaker Diarization:** (ASR/WhisperX only) Automatically detect and separate different speakers in the transcript.* **Intuitive Speaker Labeling:** A new, more intuitive interface for identifying and labeling speakers.@@ -345,7 +344,9 @@ Speakr has been tested with the recommended `onerahmet/openai-whisper-asr-webser* View and manage your saved speakers.3. **Upload or Record:*** **Upload:** Go to **New Recording** or drag-and-drop an audio file onto the page- * **Record:** Use the browser recording feature in the "New Recording" screen to record directly from your microphone (requires HTTPS or browser configuration - see [Browser Recording Setup](DEPLOYMENT_GUIDE.md#browser-recording-feature))+ * **Record:** Use the browser recording feature in the "New Recording" screen to record directly from your microphone (requires HTTPS or browser configuration - see [Browser Recording Setup](DEPLOYMENT_GUIDE.md#browser-recording-feature)).+ * **System Audio Recording:** To capture system audio (e.g., from a video conference), you must select to share a specific **browser tab** or your **entire screen** in the browser's sharing dialog. Make sure to also check the box to **"Share tab audio"** or **"Share system audio"**. Recording audio from a single application window is often not supported.+ * **Automated Processing:** Drop files into the monitored directory for automatic batch processing (see [Automated File Processing](#automated-file-processing) below)* The upload and processing status will appear in a popup.4. **View and Interact:*** The main **Gallery** lists your recordings. Click one to view its details.@@ -362,6 +363,185 @@ Speakr has been tested with the recommended `onerahmet/openai-whisper-asr-webser* Saved speakers will be suggested for auto-completion in future sessions.* You can also use the **Reprocess** button to re-transcribe the audio with different diarization settings if needed.+## Automated File Processing++Speakr includes a powerful "black hole" directory monitoring feature that automatically processes audio files without manual uploads. This is perfect for batch processing scenarios where you want to drop files into a directory and have them automatically transcribed.++### How It Works++1. **File Monitoring:** Speakr monitors a designated directory for new audio files+2. **Automatic Detection:** When new audio files are detected, they are automatically queued for processing+3. **File Stability Check:** Files are checked for stability (not being written to) before processing+4. **Automatic Processing:** Files are moved to the uploads directory and processed using your configured transcription settings+5. **Database Integration:** Processed recordings appear in your gallery with the title "Auto-processed - [filename]"++### Setup Instructions++#### 1. Enable Auto-Processing++Add these environment variables to your `.env` file:++```dotenv+# Enable automated file processing+ENABLE_AUTO_PROCESSING=true++# Directory to monitor (inside container)+AUTO_PROCESS_WATCH_DIR=/data/auto-process++# How often to check for new files (seconds)+AUTO_PROCESS_CHECK_INTERVAL=30++# Processing mode (see modes below)+AUTO_PROCESS_MODE=admin_only+```++#### 2. Mount the Auto-Process Directory++Update your `docker-compose.yml` to mount the auto-process directory:++```yaml+services:+ app:+ image: learnedmachine/speakr:latest+ container_name: speakr+ restart: unless-stopped+ ports:+ - "8899:8899"+ env_file:+ - .env+ volumes:+ - ./uploads:/data/uploads+ - ./instance:/data/instance+ - ./auto-process:/data/auto-process # Add this line+```++#### 3. Create the Directory++Create the auto-process directory on your host system:++```bash+mkdir auto-process+```++#### 4. Restart the Container++```bash+docker compose down+docker compose up -d+```++### Processing Modes++Speakr supports three different auto-processing modes:++#### Mode 1: Admin Only (Default)+```dotenv+AUTO_PROCESS_MODE=admin_only+```+- All files in the main auto-process directory are assigned to the admin user+- Simple setup, good for single-user scenarios++#### Mode 2: User Directories+```dotenv+AUTO_PROCESS_MODE=user_directories+```+- Create subdirectories for each user: `auto-process/user123/` or `auto-process/123/`+- Files are automatically assigned to the corresponding user+- Example structure:+ ```+ auto-process/+ ├── user1/ # Files for user ID 1+ ├── user5/ # Files for user ID 5+ └── 123/ # Files for user ID 123+ ```++#### Mode 3: Single User+```dotenv+AUTO_PROCESS_MODE=single_user+AUTO_PROCESS_DEFAULT_USERNAME=john_doe+```+- All files are assigned to a specific username+- Useful when you want all auto-processed files to go to a specific non-admin user++### Supported File Formats++The auto-processor supports the same audio formats as manual uploads:+- **Common formats:** MP3, WAV, M4A, FLAC, AAC, OGG+- **Mobile formats:** AMR, 3GP, 3GPP+- **Video formats:** MP4, MOV, WEBM, WMA++Files in unsupported formats are automatically converted to WAV using ffmpeg.++### Usage Examples++#### Basic Usage (Admin Mode)+```bash+# Copy files to the auto-process directory+cp /path/to/meeting1.mp3 auto-process/+cp /path/to/meeting2.wav auto-process/++# Files will be automatically processed within 30 seconds (default interval)+```++#### User Directory Mode+```bash+# Create user directories+mkdir -p auto-process/user1+mkdir -p auto-process/user5++# Drop files for specific users+cp meeting_with_john.mp3 auto-process/user1/+cp team_standup.wav auto-process/user5/+```++#### Batch Processing+```bash+# Process multiple files at once+cp /recordings/*.mp3 auto-process/+cp /meetings/2024-01/*.wav auto-process/+```++### Monitoring and Logs++Check the container logs to monitor auto-processing activity:++```bash+docker logs speakr -f+```++You'll see log entries like:+```+File monitor started in 'admin_only' mode, watching: /data/auto-process+Found new audio file for user 1: /data/auto-process/meeting.mp3+Copied /data/auto-process/meeting.mp3 to /data/uploads/auto_20250119021530_meeting.mp3+Created recording record with ID: 123 for user: admin+Started background processing for recording ID: 123+```++### Best Practices++1. **File Naming:** Use descriptive filenames as they become part of the auto-generated title+2. **Batch Processing:** You can drop multiple files at once; they'll be processed sequentially+3. **Network Shares:** Mount network drives or NAS shares to the auto-process directory for remote file drops+4. **Monitoring:** Set up log monitoring to track processing status and catch any errors+5. **Cleanup:** Processed files are automatically moved and deleted from the auto-process directory++### Troubleshooting++**Files not being processed:**+- Check that `ENABLE_AUTO_PROCESSING=true` in your `.env` file+- Verify the auto-process directory is properly mounted+- Check container logs for error messages++**Permission issues:**+- Ensure the auto-process directory has proper read/write permissions+- The container runs as the user specified in the Docker configuration++**Processing errors:**+- Check that your transcription API is properly configured+- Verify ffmpeg is available in the container for file conversion+- Monitor container logs for specific error messages+## LicenseThis project is **dual-licensed**:diff --git a/app.py b/app.pyindex 0f8638b3..6e6cd061 100644--- a/app.py+++ b/app.py@@ -2,6 +2,7 @@import osimport sysfrom flask import Flask, render_template, request, jsonify, send_file, redirect, url_for, flash, Response+from urllib.parse import urlparse, urljointry:from flask import Markupexcept ImportError:@@ -12,6 +13,7 @@ from openai import OpenAI # Keep using the OpenAI libraryimport jsonfrom werkzeug.utils import secure_filenamefrom werkzeug.exceptions import RequestEntityTooLarge+from werkzeug.middleware.proxy_fix import ProxyFixfrom sqlalchemy import selectimport threadingfrom dotenv import load_dotenv # Import load_dotenv@@ -23,14 +25,237 @@ import markdownfrom flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_userfrom flask_bcrypt import Bcryptfrom flask_wtf import FlaskForm+from flask_wtf.csrf import CSRFProtectfrom wtforms import StringField, PasswordField, SubmitField, BooleanFieldfrom wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError+from flask_limiter import Limiter+from flask_limiter.util import get_remote_addressimport pytzfrom babel.dates import format_datetime+import ast+import logging+import secrets# Load environment variables from .env fileload_dotenv()+# Configure logging+log_level = os.environ.get('LOG_LEVEL', 'INFO').upper()+handler = logging.StreamHandler(sys.stdout)+handler.setLevel(log_level)+formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')+handler.setFormatter(formatter)++# Get the root logger+root_logger = logging.getLogger()+root_logger.setLevel(log_level)+root_logger.addHandler(handler)++# Also configure Flask's logger+app_logger = logging.getLogger('werkzeug')+app_logger.setLevel(log_level)+app_logger.addHandler(handler)++# --- Rate Limiting Setup ---+limiter = Limiter(+ get_remote_address,+ app=None, # Defer initialization+ default_limits=["200 per day", "50 per hour"]+)++def auto_close_json(json_string):+ """+ Attempts to close an incomplete JSON string by appending necessary brackets and braces.+ This is a simplified parser and may not handle all edge cases, but is+ designed to fix unterminated strings from API responses.+ """+ if not isinstance(json_string, str):+ return json_string++ stack = []+ in_string = False+ escape_next = False++ for char in json_string:+ if escape_next:+ escape_next = False+ continue++ if char == '\\':+ escape_next = True+ continue++ if char == '"':+ # We don't handle escaped quotes inside strings perfectly,+ # but this is a simple heuristic.+ if not escape_next:+ in_string = not in_string++ if not in_string:+ if char == '{':+ stack.append('}')+ elif char == '[':+ stack.append(']')+ elif char == '}':+ if stack and stack[-1] == '}':+ stack.pop()+ elif char == ']':+ if stack and stack[-1] == ']':+ stack.pop()++ # If we are inside a string at the end, close it.+ if in_string:+ json_string += '"'++ # Close any remaining open structures+ while stack:+ json_string += stack.pop()++ return json_string++def safe_json_loads(json_string, fallback_value=None):+ """+ Safely parse JSON with preprocessing to handle common LLM JSON formatting issues.++ Args:+ json_string (str): The JSON string to parse+ fallback_value: Value to return if parsing fails (default: None)++ Returns:+ Parsed JSON object or fallback_value if parsing fails+ """+ if not json_string or not isinstance(json_string, str):+ app.logger.warning(f"Invalid JSON input: {type(json_string)} - {json_string}")+ return fallback_value++ # Step 1: Clean the input string+ cleaned_json = json_string.strip()++ # Step 2: Extract JSON from markdown code blocks if present+ json_match = re.search(r'```(?:json)?\s*(.*?)\s*```', cleaned_json, re.DOTALL)+ if json_match:+ cleaned_json = json_match.group(1).strip()++ # Step 3: Try multiple parsing strategies+ parsing_strategies = [+ # Strategy 1: Direct parsing (for well-formed JSON)+ lambda x: json.loads(x),++ # Strategy 2: Fix common escape issues+ lambda x: json.loads(preprocess_json_escapes(x)),++ # Strategy 3: Use ast.literal_eval as fallback for simple cases+ lambda x: ast.literal_eval(x) if x.startswith(('{', '[')) else None,++ # Strategy 4: Extract JSON object/array using regex+ lambda x: json.loads(extract_json_object(x)),++ # Strategy 5: Auto-close incomplete JSON and parse+ lambda x: json.loads(auto_close_json(x)),+ ]++ for i, strategy in enumerate(parsing_strategies):+ try:+ result = strategy(cleaned_json)+ if result is not None:+ if i > 0: # Log if we had to use a fallback strategy+ app.logger.info(f"JSON parsed successfully using strategy {i+1}")+ return result+ except (json.JSONDecodeError, ValueError, SyntaxError) as e:+ if i == 0: # Only log the first failure to avoid spam+ app.logger.debug(f"JSON parsing strategy {i+1} failed: {e}")+ continue++ # All strategies failed+ app.logger.error(f"All JSON parsing strategies failed for: {cleaned_json[:200]}...")+ return fallback_value++def preprocess_json_escapes(json_string):+ """+ Preprocess JSON string to fix common escape issues from LLM responses.+ Uses a more sophisticated approach to handle nested quotes properly.+ """+ if not json_string:+ return json_string++ result = []+ i = 0+ in_string = False+ escape_next = False+ expecting_value = False # Track if we're expecting a value (after :)++ while i < len(json_string):+ char = json_string[i]++ if escape_next:+ # This character is escaped, add it as-is+ result.append(char)+ escape_next = False+ elif char == '\\':+ # This is an escape character+ result.append(char)+ escape_next = True+ elif char == ':' and not in_string:+ # We found a colon, next string will be a value+ result.append(char)+ expecting_value = True+ elif char == ',' and not in_string:+ # We found a comma, reset expecting_value+ result.append(char)+ expecting_value = False+ elif char == '"':+ if not in_string:+ # Starting a string+ in_string = True+ result.append(char)+ else:+ # We're in a string, check if this quote should be escaped+ # Look ahead to see if this is the end of the string value+ j = i + 1+ while j < len(json_string) and json_string[j].isspace():+ j += 1++ # For keys (not expecting_value), only end on colon+ # For values (expecting_value), end on comma, closing brace, or closing bracket+ if expecting_value:+ end_chars = ',}]'+ else:+ end_chars = ':'++ if j < len(json_string) and json_string[j] in end_chars:+ # This is the end of the string+ in_string = False+ result.append(char)+ if not expecting_value:+ # We just finished a key, next will be expecting value+ expecting_value = True+ else:+ # This is an inner quote that should be escaped+ result.append('\\"')+ else:+ result.append(char)++ i += 1++ return ''.join(result)++def extract_json_object(text):+ """+ Extract the first complete JSON object or array from text using regex.+ """+ # Look for JSON object+ obj_match = re.search(r'\{.*\}', text, re.DOTALL)+ if obj_match:+ return obj_match.group(0)++ # Look for JSON array+ arr_match = re.search(r'\[.*\]', text, re.DOTALL)+ if arr_match:+ return arr_match.group(0)++ # Return original if no JSON structure found+ return text+# Initialize Flask-Bcryptbcrypt = Bcrypt()@@ -120,15 +345,29 @@ 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')++# Apply ProxyFix to handle headers from a reverse proxy (like Nginx or Caddy)+# This is crucial for request.is_secure to work correctly behind an SSL-terminating proxy.+app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)++# --- Secure Session Cookie Configuration ---+# In a production environment (e.g., when not in debug mode), these should be enabled.+if not app.debug:+ app.config['SESSION_COOKIE_SECURE'] = True+ app.config['SESSION_COOKIE_HTTPONLY'] = True+ app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'+db = SQLAlchemy()db.init_app(app)-# Initialize Flask-Login+# Initialize Flask-Login and other extensionslogin_manager = LoginManager()login_manager.init_app(app)login_manager.login_view = 'login'login_manager.login_message_category = 'info'bcrypt.init_app(app)+limiter.init_app(app) # Initialize the limiter+csrf = CSRFProtect(app)# Add context processor to make 'now' available to all templates@app.context_processor@@ -212,6 +451,93 @@ class Speaker(db.Model):'use_count': self.use_count}+class SystemSetting(db.Model):+ id = db.Column(db.Integer, primary_key=True)+ key = db.Column(db.String(100), unique=True, nullable=False)+ value = db.Column(db.Text, nullable=True)+ description = db.Column(db.Text, nullable=True)+ setting_type = db.Column(db.String(50), nullable=False, default='string') # string, integer, boolean, float+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'key': self.key,+ 'value': self.value,+ 'description': self.description,+ 'setting_type': self.setting_type,+ 'created_at': self.created_at,+ 'updated_at': self.updated_at+ }++ @staticmethod+ def get_setting(key, default_value=None):+ """Get a system setting value by key, with optional default."""+ setting = SystemSetting.query.filter_by(key=key).first()+ if setting:+ # Convert value based on type+ if setting.setting_type == 'integer':+ try:+ return int(setting.value) if setting.value is not None else default_value+ except (ValueError, TypeError):+ return default_value+ elif setting.setting_type == 'boolean':+ return setting.value.lower() in ('true', '1', 'yes') if setting.value else default_value+ elif setting.setting_type == 'float':+ try:+ return float(setting.value) if setting.value is not None else default_value+ except (ValueError, TypeError):+ return default_value+ else: # string+ return setting.value if setting.value is not None else default_value+ return default_value++ @staticmethod+ def set_setting(key, value, description=None, setting_type='string'):+ """Set a system setting value."""+ setting = SystemSetting.query.filter_by(key=key).first()+ if setting:+ setting.value = str(value) if value is not None else None+ setting.updated_at = datetime.utcnow()+ if description:+ setting.description = description+ if setting_type:+ setting.setting_type = setting_type+ else:+ setting = SystemSetting(+ key=key,+ value=str(value) if value is not None else None,+ description=description,+ setting_type=setting_type+ )+ db.session.add(setting)+ db.session.commit()+ return setting++class Share(db.Model):+ id = db.Column(db.Integer, primary_key=True)+ public_id = db.Column(db.String(32), unique=True, nullable=False, default=lambda: secrets.token_urlsafe(16))+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ share_summary = db.Column(db.Boolean, default=True)+ share_notes = db.Column(db.Boolean, default=True)++ user = db.relationship('User', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))+ recording = db.relationship('Recording', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'public_id': self.public_id,+ 'recording_id': self.recording_id,+ 'created_at': local_datetime_filter(self.created_at),+ 'share_summary': self.share_summary,+ 'share_notes': self.share_notes,+ 'recording_title': self.recording.title if self.recording else "N/A"+ }+class Recording(db.Model):# Add user_id foreign key to associate recordings with usersuser_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)@@ -233,6 +559,8 @@ class Recording(db.Model):mime_type = db.Column(db.String(100), nullable=True)completed_at = db.Column(db.DateTime, nullable=True)processing_time_seconds = db.Column(db.Integer, nullable=True)+ processing_source = db.Column(db.String(50), default='upload') # upload, auto_process, recording+ error_message = db.Column(db.Text, nullable=True) # Store detailed error messagesdef to_dict(self):return {@@ -258,10 +586,100 @@ class Recording(db.Model):}# --- Forms for Authentication ---+# --- Custom Password Validator ---+def password_check(form, field):+ password = field.data+ if len(password) < 8:+ raise ValidationError('Password must be at least 8 characters long.')+ if not re.search(r'[A-Z]', password):+ raise ValidationError('Password must contain at least one uppercase letter.')+ if not re.search(r'[a-z]', password):+ raise ValidationError('Password must contain at least one lowercase letter.')+ if not re.search(r'[0-9]', password):+ raise ValidationError('Password must contain at least one number.')+ if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):+ raise ValidationError('Password must contain at least one special character.')++# --- Share Routes ---[email protected]('/share/<string:public_id>', methods=['GET'])+def view_shared_recording(public_id):+ share = Share.query.filter_by(public_id=public_id).first_or_404()+ recording = share.recording++ # Create a limited dictionary for the public view+ recording_data = {+ 'id': recording.id,+ 'public_id': share.public_id,+ 'title': recording.title,+ 'participants': recording.participants,+ 'transcription': recording.transcription,+ 'summary': md_to_html(recording.summary) if share.share_summary else None,+ 'notes': md_to_html(recording.notes) if share.share_notes else None,+ 'meeting_date': recording.meeting_date.isoformat() if recording.meeting_date else None,+ 'mime_type': recording.mime_type+ }++ return render_template('share.html', recording=recording_data)+[email protected]('/api/recording/<int:recording_id>/share', methods=['POST'])+@login_required+def create_share(recording_id):+ if not request.is_secure:+ return jsonify({'error': 'Sharing is only available over a secure (HTTPS) connection.'}), 403++ recording = db.session.get(Recording, recording_id)+ if not recording or recording.user_id != current_user.id:+ return jsonify({'error': 'Recording not found or you do not have permission to share it.'}), 404++ data = request.json+ share_summary = data.get('share_summary', True)+ share_notes = data.get('share_notes', True)++ share = Share(+ recording_id=recording.id,+ user_id=current_user.id,+ share_summary=share_summary,+ share_notes=share_notes+ )+ db.session.add(share)+ db.session.commit()++ share_url = url_for('view_shared_recording', public_id=share.public_id, _external=True)++ return jsonify({'success': True, 'share_url': share_url, 'share': share.to_dict()}), 201+[email protected]('/api/shares', methods=['GET'])+@login_required+def get_shares():+ shares = Share.query.filter_by(user_id=current_user.id).order_by(Share.created_at.desc()).all()+ return jsonify([share.to_dict() for share in shares])+[email protected]('/api/share/<int:share_id>', methods=['PUT'])+@login_required+def update_share(share_id):+ share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()+ data = request.json++ if 'share_summary' in data:+ share.share_summary = data['share_summary']+ if 'share_notes' in data:+ share.share_notes = data['share_notes']++ db.session.commit()+ return jsonify({'success': True, 'share': share.to_dict()})+[email protected]('/api/share/<int:share_id>', methods=['DELETE'])+@login_required+def delete_share(share_id):+ share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()+ db.session.delete(share)+ db.session.commit()+ return jsonify({'success': True})+class RegistrationForm(FlaskForm):username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])email = StringField('Email', validators=[DataRequired(), Email()])- password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])+ password = PasswordField('Password', validators=[DataRequired(), password_check])confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])submit = SubmitField('Sign Up')@@ -337,6 +755,29 @@ with app.app_context():app.logger.info("Added completed_at column to recording table")if add_column_if_not_exists(engine, 'recording', 'processing_time_seconds', 'INTEGER'):app.logger.info("Added processing_time_seconds column to recording table")+ if add_column_if_not_exists(engine, 'recording', 'processing_source', 'VARCHAR(50) DEFAULT "upload"'):+ app.logger.info("Added processing_source column to recording table")+ if add_column_if_not_exists(engine, 'recording', 'error_message', 'TEXT'):+ app.logger.info("Added error_message column to recording table")++ # Initialize default system settings+ if not SystemSetting.query.filter_by(key='transcript_length_limit').first():+ SystemSetting.set_setting(+ key='transcript_length_limit',+ value='30000',+ description='Maximum number of characters to send from transcript to LLM for summarization and chat. Use -1 for no limit.',+ setting_type='integer'+ )+ app.logger.info("Initialized default transcript_length_limit setting")++ if not SystemSetting.query.filter_by(key='max_file_size_mb').first():+ SystemSetting.set_setting(+ key='max_file_size_mb',+ value='250',+ description='Maximum file size allowed for audio uploads in megabytes (MB).',+ setting_type='integer'+ )+ app.logger.info("Initialized default max_file_size_mb setting")except Exception as e:app.logger.error(f"Error during database migration: {e}")@@ -439,12 +880,20 @@ JSON Response:"""language_directive = f"Please provide the title and summary in {user_output_language}." if user_output_language else ""+ # Get configurable transcript length limit+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ # No limit+ transcript_text = recording.transcription+ else:+ transcript_text = recording.transcription[:transcript_limit]+if user_summary_prompt:prompt_text = f"""Analyze the following audio transcription and generate a concise title and a summary according to the following instructions.Transcription:\"\"\"-{recording.transcription[:50000]}+{transcript_text}\"\"\"Generate a response STRICTLY as a JSON object with two keys: "title" and "summary". The summary should be markdown, not JSON.@@ -456,7 +905,7 @@ For the "summary": {user_summary_prompt}.JSON Response:"""else:- prompt_text = default_summary_prompt.format(transcription=recording.transcription[:30000], language_directive=language_directive)+ prompt_text = default_summary_prompt.format(transcription=transcript_text, language_directive=language_directive)system_message_content = "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."if user_output_language:@@ -478,7 +927,7 @@ JSON Response:"""json_match = re.search(r'```(?:json)?(.*?)```|(.+)', response_content, re.DOTALL)sanitized_response = json_match.group(1) if json_match.group(1) else json_match.group(2)sanitized_response = sanitized_response.strip()- summary_data = json.loads(sanitized_response)+ summary_data = safe_json_loads(sanitized_response, {})raw_title = summary_data.get("title")raw_summary = summary_data.get("summary")@@ -968,11 +1417,19 @@ def identify_speakers_from_text(transcription):if not speaker_labels:return {}+ # Get configurable transcript length limit+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ # No limit+ transcript_text = formatted_transcription+ else:+ transcript_text = formatted_transcription[:transcript_limit]+prompt = f"""Analyze the following transcription and identify the names of the speakers. The speakers are labeled as {', '.join(speaker_labels)}. Based on the context of the conversation, determine the most likely name for each speaker label.Transcription:----{formatted_transcription[:28000]}+{transcript_text}---Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_00") and values are the identified full names. If a name cannot be determined, use the value "Unknown".@@ -998,7 +1455,7 @@ JSON Response:response_format={"type": "json_object"})response_content = completion.choices[0].message.content- speaker_map = json.loads(response_content)+ speaker_map = safe_json_loads(response_content, {})# Post-process the map to replace "Unknown" with an empty stringfor speaker_label, identified_name in speaker_map.items():@@ -1023,6 +1480,14 @@ def identify_unidentified_speakers_from_text(transcription, unidentified_speakerif not unidentified_speakers:return {}+ # Get configurable transcript length limit+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ # No limit+ transcript_text = formatted_transcription+ else:+ transcript_text = formatted_transcription[:transcript_limit]+prompt = f"""Analyze the following conversation transcript and identify the names of the UNIDENTIFIED speakers based on the context and content of their dialogue.The speakers that need to be identified are: {', '.join(unidentified_speakers)}@@ -1035,7 +1500,7 @@ Look for clues in the conversation such as:Here is the complete conversation transcript:-{formatted_transcription[:28000]}+{transcript_text}Based on the conversation above, identify the most likely real names for the unidentified speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.@@ -1062,7 +1527,7 @@ JSON Response:response_format={"type": "json_object"})response_content = completion.choices[0].message.content- speaker_map = json.loads(response_content)+ speaker_map = safe_json_loads(response_content, {})# Post-process the map to replace "Unknown" with an empty stringfor speaker_label, identified_name in speaker_map.items():@@ -1171,6 +1636,14 @@ def chat_with_transcription():formatted_transcription = format_transcription_for_llm(recording.transcription)+ # Get configurable transcript length limit for chat+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ # No limit+ chat_transcript = formatted_transcription+ else:+ chat_transcript = formatted_transcription[:transcript_limit]+system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {user_name}, who is a(n) {user_title} at {user_company}. {language_instruction} Analyze the following meeting information and respond to the specific request.Following are the meeting participants and their roles:@@ -1178,7 +1651,7 @@ Following are the meeting participants and their roles:Following is the meeting transcript:<<start transcript>>-{formatted_transcription or "No transcript available."}+{chat_transcript or "No transcript available."}<<end transcript>>Additional context and notes about the meeting:@@ -1247,8 +1720,9 @@ def reprocess_transcription(recording_id):filename_for_asr = recording.original_filename or os.path.basename(filepath)filename_lower = filename_for_asr.lower()- if not (filename_lower.endswith('.wav') or filename_lower.endswith('.mp3') or filename_lower.endswith('.flac')):- app.logger.info(f"Reprocessing: Unsupported format detected ({filename_lower}). Converting to WAV.")+ supported_formats = ('.wav', '.mp3', '.flac')+ if not filename_lower.endswith(supported_formats):+ app.logger.info(f"Reprocessing: Converting {filename_lower} format to WAV.")base_filepath, file_ext = os.path.splitext(filepath)temp_wav_filepath = f"{base_filepath}_temp.wav"final_wav_filepath = f"{base_filepath}.wav"@@ -1413,12 +1887,20 @@ JSON Response:"""language_directive = f"Please provide the title and summary in {user_output_language}." if user_output_language else ""+ # Get configurable transcript length limit for reprocessing+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ # No limit+ transcript_text = recording.transcription+ else:+ transcript_text = recording.transcription[:transcript_limit]+if user_summary_prompt:prompt_text = f"""Analyze the following audio transcription and generate a concise title and a summary according to the following instructions.Transcription:\"\"\"-{recording.transcription[:50000]}+{transcript_text}\"\"\"Generate a response STRICTLY as a JSON object with two keys: "title" and "summary". The summary should be markdown, not JSON.@@ -1430,7 +1912,7 @@ For the "summary": {user_summary_prompt}.JSON Response:"""else:- prompt_text = default_summary_prompt.format(transcription=recording.transcription[:30000], language_directive=language_directive)+ prompt_text = default_summary_prompt.format(transcription=transcript_text, language_directive=language_directive)system_message_content = "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."if user_output_language:@@ -1484,7 +1966,7 @@ JSON Response:"""db.session.commit()return- summary_data = json.loads(sanitized_response)+ summary_data = safe_json_loads(sanitized_response, {})# Check if the parsed JSON is empty or doesn't contain expected keysif not summary_data or (not summary_data.get("title") and not summary_data.get("summary")):@@ -1582,7 +2064,7 @@ JSON Response:"""@app.route('/recording/<int:recording_id>/reset_status', methods=['POST'])@login_requireddef reset_status(recording_id):- """Resets the status of a stuck recording to FAILED."""+ """Resets the status of a stuck or failed recording."""try:recording = db.session.get(Recording, recording_id)if not recording:@@ -1591,15 +2073,15 @@ def reset_status(recording_id):if recording.user_id and recording.user_id != current_user.id:return jsonify({'error': 'You do not have permission to modify this recording'}), 403- # Only allow resetting if it's stuck in a processing state- if recording.status in ['PROCESSING', 'SUMMARIZING']:+ # Allow resetting if it's stuck or failed+ if recording.status in ['PROCESSING', 'SUMMARIZING', 'FAILED']:recording.status = 'FAILED'- recording.summary = (recording.summary or "") + "\n\n[Manually reset from stuck state]"+ recording.error_message = "Manually reset from stuck or failed state."db.session.commit()app.logger.info(f"Manually reset status for recording {recording_id} to FAILED.")return jsonify({'success': True, 'message': 'Recording status has been reset.', 'recording': recording.to_dict()})else:- return jsonify({'error': f'Recording is not in a processing state. Current status: {recording.status}'}), 400+ return jsonify({'error': f'Recording is not in a state that can be reset. Current status: {recording.status}'}), 400except Exception as e:db.session.rollback()@@ -1608,6 +2090,7 @@ def reset_status(recording_id):# --- Authentication Routes ---@app.route('/register', methods=['GET', 'POST'])[email protected]("10 per minute")def register():# Check if registration is allowedallow_registration = os.environ.get('ALLOW_REGISTRATION', 'true').lower() == 'true'@@ -1630,7 +2113,13 @@ def register():return render_template('register.html', title='Register', form=form)+def is_safe_url(target):+ ref_url = urlparse(request.host_url)+ test_url = urlparse(urljoin(request.host_url, target))+ return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc+@app.route('/login', methods=['GET', 'POST'])[email protected]("10 per minute")def login():if current_user.is_authenticated:return redirect(url_for('index'))@@ -1641,6 +2130,8 @@ def login():if user and bcrypt.check_password_hash(user.password, form.password.data):login_user(user, remember=form.remember.data)next_page = request.args.get('next')+ if not is_safe_url(next_page):+ return redirect(url_for('index'))return redirect(next_page) if next_page else redirect(url_for('index'))else:flash('Login unsuccessful. Please check email and password.', 'danger')@@ -1650,7 +2141,7 @@ def login():@app.route('/logout')def logout():logout_user()- return redirect(url_for('index'))+ return redirect(url_for('login'))@app.route('/account', methods=['GET', 'POST'])@login_required@@ -1692,6 +2183,7 @@ def account():@app.route('/change_password', methods=['POST'])@login_required[email protected]("10 per minute")def change_password():current_password = request.form.get('current_password')new_password = request.form.get('new_password')@@ -1705,6 +2197,13 @@ def change_password():if new_password != confirm_password:flash('New password and confirmation do not match.', 'danger')return redirect(url_for('account'))++ # Custom validation for new password+ try:+ password_check(None, type('obj', (object,), {'data': new_password}))+ except ValidationError as e:+ flash(str(e), 'danger')+ return redirect(url_for('account'))# Check if current password is correctif not bcrypt.check_password_hash(current_user.password, current_password):@@ -1956,8 +2455,82 @@ def admin_get_stats():'total_queries': total_queries})[email protected]('/admin/settings', methods=['GET'])+@login_required+def admin_get_settings():+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ settings = SystemSetting.query.all()+ return jsonify([setting.to_dict() for setting in settings])+[email protected]('/admin/settings', methods=['POST'])+@login_required+def admin_update_setting():+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ key = data.get('key')+ value = data.get('value')+ description = data.get('description')+ setting_type = data.get('setting_type', 'string')++ if not key:+ return jsonify({'error': 'Setting key is required'}), 400++ # Validate setting type+ valid_types = ['string', 'integer', 'boolean', 'float']+ if setting_type not in valid_types:+ return jsonify({'error': f'Invalid setting type. Must be one of: {", ".join(valid_types)}'}), 400++ # Validate value based on type+ if setting_type == 'integer':+ try:+ int(value) if value is not None and value != '' else None+ except (ValueError, TypeError):+ return jsonify({'error': 'Value must be a valid integer'}), 400+ elif setting_type == 'float':+ try:+ float(value) if value is not None and value != '' else None+ except (ValueError, TypeError):+ return jsonify({'error': 'Value must be a valid number'}), 400+ elif setting_type == 'boolean':+ if value not in ['true', 'false', '1', '0', 'yes', 'no', True, False, 1, 0]:+ return jsonify({'error': 'Value must be a valid boolean (true/false, 1/0, yes/no)'}), 400++ try:+ setting = SystemSetting.set_setting(key, value, description, setting_type)+ return jsonify(setting.to_dict())+ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error updating setting {key}: {e}")+ return jsonify({'error': str(e)}), 500++# --- Configuration API ---[email protected]('/api/config', methods=['GET'])+def get_config():+ """Get application configuration settings for the frontend."""+ try:+ # Get configurable file size limit+ max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)++ return jsonify({+ 'max_file_size_mb': max_file_size_mb,+ 'use_asr_endpoint': USE_ASR_ENDPOINT+ })+ except Exception as e:+ app.logger.error(f"Error fetching configuration: {e}")+ return jsonify({'error': str(e)}), 500+# --- Flask Routes ---@app.route('/')+@login_requireddef index():# Pass the ASR config to the templatereturn render_template('index.html', use_asr_endpoint=USE_ASR_ENDPOINT)@@ -1977,6 +2550,23 @@ def get_recordings():app.logger.error(f"Error fetching recordings: {e}")return jsonify({'error': str(e)}), 500[email protected]('/api/inbox_recordings', methods=['GET'])+@login_required+def get_inbox_recordings():+ """Get recordings that are in the inbox and currently processing."""+ try:+ stmt = select(Recording).where(+ Recording.user_id == current_user.id,+ Recording.is_inbox == True,+ Recording.status.in_(['PENDING', 'PROCESSING', 'SUMMARIZING'])+ ).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 inbox recordings: {e}")+ return jsonify({'error': str(e)}), 500+@app.route('/save', methods=['POST'])@login_requireddef save_metadata():@@ -2019,8 +2609,42 @@ def save_metadata():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+ app.logger.error(f"Error saving metadata for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred while saving.'}), 500+[email protected]('/recording/<int:recording_id>/update_transcription', methods=['POST'])+@login_required+def update_transcription(recording_id):+ """Updates the transcription content for a recording."""+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403++ data = request.json+ new_transcription = data.get('transcription')++ if new_transcription is None:+ return jsonify({'error': 'No transcription data provided'}), 400++ # The incoming data could be a JSON string (from ASR edit) or plain text+ recording.transcription = new_transcription++ # Optional: If the transcription changes, we might want to indicate that the summary is outdated.+ # For now, we'll just save the transcript. A "regenerate summary" button could be a good follow-up.++ db.session.commit()+ app.logger.info(f"Transcription for recording {recording_id} was updated.")++ return jsonify({'success': True, 'message': 'Transcription updated successfully.', 'recording': recording.to_dict()})++ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error updating transcription for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred while updating the transcription.'}), 500# Toggle inbox status endpoint@app.route('/recording/<int:recording_id>/toggle_inbox', methods=['POST'])@@ -2042,8 +2666,8 @@ def toggle_inbox(recording_id):return jsonify({'success': True, 'is_inbox': recording.is_inbox})except Exception as e:db.session.rollback()- app.logger.error(f"Error toggling inbox status for recording {recording_id}: {e}")- return jsonify({'error': str(e)}), 500+ app.logger.error(f"Error toggling inbox status for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500# Toggle highlighted status endpoint@app.route('/recording/<int:recording_id>/toggle_highlight', methods=['POST'])@@ -2065,8 +2689,8 @@ def toggle_highlight(recording_id):return jsonify({'success': True, 'is_highlighted': recording.is_highlighted})except Exception as e:db.session.rollback()- app.logger.error(f"Error toggling highlighted status for recording {recording_id}: {e}")- return jsonify({'error': str(e)}), 500+ app.logger.error(f"Error toggling highlighted status for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500@app.route('/upload', methods=['POST'])@@ -2096,10 +2720,16 @@ def upload_file():file.save(filepath)app.logger.info(f"File saved to {filepath}")- # --- Convert non-wav/mp3 files to WAV ---+ # --- Convert non-wav/mp3/flac files to WAV ---filename_lower = original_filename.lower()- if not (filename_lower.endswith('.wav') or filename_lower.endswith('.mp3') or filename_lower.endswith('.flac')):- app.logger.info(f"Unsupported format detected ({filename_lower}). Converting to WAV.")+ supported_formats = ('.wav', '.mp3', '.flac')+ convertible_formats = ('.amr', '.3gp', '.3gpp', '.m4a', '.aac', '.ogg', '.wma', '.webm')++ if not filename_lower.endswith(supported_formats):+ if filename_lower.endswith(convertible_formats):+ app.logger.info(f"Converting {filename_lower} format to WAV for processing.")+ else:+ app.logger.info(f"Attempting to convert unknown format ({filename_lower}) to WAV.")base_filepath, _ = os.path.splitext(filepath)temp_wav_filepath = f"{base_filepath}_temp.wav"@@ -2135,6 +2765,9 @@ def upload_file():mime_type, _ = mimetypes.guess_type(filepath)app.logger.info(f"Final MIME type: {mime_type} for file {filepath}")+ # Get notes from the form+ notes = request.form.get('notes')+# Create initial database entryrecording = Recording(audio_path=filepath,@@ -2144,7 +2777,9 @@ def upload_file():status='PENDING',meeting_date=datetime.utcnow().date(),user_id=current_user.id,- mime_type=mime_type+ mime_type=mime_type,+ notes=notes,+ processing_source='upload' # Track that this was manually uploaded)db.session.add(recording)db.session.commit()@@ -2171,7 +2806,7 @@ def upload_file():except Exception as e:db.session.rollback()app.logger.error(f"Error during file upload: {e}", exc_info=True)- return jsonify({'error': str(e)}), 500+ return jsonify({'error': 'An unexpected error occurred during upload.'}), 500# Status Endpoint@@ -2190,8 +2825,8 @@ def get_status(recording_id):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+ app.logger.error(f"Error fetching status for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500# Get Audio Endpoint@app.route('/audio/<int:recording_id>')@@ -2210,8 +2845,23 @@ def get_audio(recording_id):return jsonify({'error': 'Audio file missing from server'}), 404return 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+ app.logger.error(f"Error serving audio for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500+[email protected]('/share/audio/<string:public_id>')+def get_shared_audio(public_id):+ try:+ share = Share.query.filter_by(public_id=public_id).first_or_404()+ recording = share.recording+ if not recording or not recording.audio_path:+ return jsonify({'error': 'Recording or audio file not found'}), 404+ if not os.path.exists(recording.audio_path):+ app.logger.error(f"Audio file missing from server: {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 shared audio for public_id {public_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500# Delete Recording Endpoint@app.route('/recording/<int:recording_id>', methods=['DELETE'])@@ -2242,9 +2892,126 @@ def delete_recording(recording_id):return jsonify({'success': True})except Exception as e:db.session.rollback()- app.logger.error(f"Error deleting recording {recording_id}: {e}")+ app.logger.error(f"Error deleting recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred while deleting.'}), 500+++# --- Auto-Processing File Monitor Integration ---+def initialize_file_monitor():+ """Initialize file monitor after app is fully loaded to avoid circular imports."""+ try:+ # Import here to avoid circular imports+ import file_monitor+ file_monitor.start_file_monitor()+ app.logger.info("File monitor initialization completed")+ except Exception as e:+ app.logger.warning(f"File monitor initialization failed: {e}")++def get_file_monitor_functions():+ """Get file monitor functions, handling import errors gracefully."""+ try:+ import file_monitor+ return file_monitor.start_file_monitor, file_monitor.stop_file_monitor, file_monitor.get_file_monitor_status+ except ImportError as e:+ app.logger.warning(f"File monitor not available: {e}")++ # Create stub functions if file_monitor is not available+ def start_file_monitor():+ pass+ def stop_file_monitor():+ pass+ def get_file_monitor_status():+ return {'running': False, 'error': 'File monitor module not available'}++ return start_file_monitor, stop_file_monitor, get_file_monitor_status++# --- Auto-Processing API Endpoints ---[email protected]('/admin/auto-process/status', methods=['GET'])+@login_required+def admin_get_auto_process_status():+ """Get the status of the automated file processing system."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ _, _, get_file_monitor_status = get_file_monitor_functions()+ status = get_file_monitor_status()++ # Add configuration info+ config = {+ 'enabled': os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true',+ 'watch_directory': os.environ.get('AUTO_PROCESS_WATCH_DIR', '/data/auto-process'),+ 'check_interval': int(os.environ.get('AUTO_PROCESS_CHECK_INTERVAL', '30')),+ 'mode': os.environ.get('AUTO_PROCESS_MODE', 'admin_only'),+ 'default_username': os.environ.get('AUTO_PROCESS_DEFAULT_USERNAME')+ }++ return jsonify({+ 'status': status,+ 'config': config+ })++ except Exception as e:+ app.logger.error(f"Error getting auto-process status: {e}")return jsonify({'error': str(e)}), 500[email protected]('/admin/auto-process/start', methods=['POST'])+@login_required+def admin_start_auto_process():+ """Start the automated file processing system."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ start_file_monitor, _, _ = get_file_monitor_functions()+ start_file_monitor()+ return jsonify({'success': True, 'message': 'Auto-processing started'})+ except Exception as e:+ app.logger.error(f"Error starting auto-process: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/admin/auto-process/stop', methods=['POST'])+@login_required+def admin_stop_auto_process():+ """Stop the automated file processing system."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ _, stop_file_monitor, _ = get_file_monitor_functions()+ stop_file_monitor()+ return jsonify({'success': True, 'message': 'Auto-processing stopped'})+ except Exception as e:+ app.logger.error(f"Error stopping auto-process: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/admin/auto-process/config', methods=['POST'])+@login_required+def admin_update_auto_process_config():+ """Update auto-processing configuration (requires restart)."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No configuration data provided'}), 400++ # This endpoint would typically update environment variables or config files+ # For now, we'll just return the current config and note that restart is required+ return jsonify({+ 'success': True,+ 'message': 'Configuration updated. Restart required to apply changes.',+ 'note': 'Environment variables need to be updated manually and application restarted.'+ })++ except Exception as e:+ app.logger.error(f"Error updating auto-process config: {e}")+ return jsonify({'error': str(e)}), 500++# Initialize file monitor after app setup+with app.app_context():+ initialize_file_monitor()if __name__ == '__main__':# Consider using waitress or gunicorn for productiondiff --git a/diff.txt b/diff.txtnew file mode 100644index 00000000..e69de29bdiff --git a/env.asr.example b/env.asr.exampleindex bd91af10..7af6d660 100644--- a/env.asr.example+++ b/env.asr.example@@ -30,11 +30,31 @@ ALLOW_REGISTRATION=falseSUMMARY_MAX_TOKENS=8000CHAT_MAX_TOKENS=5000+# Set the logging level for the application.+# Options: DEBUG, INFO, WARNING, ERROR+LOG_LEVEL="INFO"+# --- Admin User (created on first run) ---ADMIN_USERNAME=adminADMIN_PASSWORD=changeme+# --- Automated File Processing (Black Hole Directory) ---+# Set to "true" to enable automated file processing+ENABLE_AUTO_PROCESSING=false++# Processing mode: admin_only, user_directories, or single_user+AUTO_PROCESS_MODE=admin_only++# Directory to watch for new audio files+AUTO_PROCESS_WATCH_DIR=/data/auto-process++# How often to check for new files (seconds)+AUTO_PROCESS_CHECK_INTERVAL=30++# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)+# AUTO_PROCESS_DEFAULT_USERNAME=admin+# --- Docker Settings (rarely need to be changed) ---SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.dbUPLOAD_FOLDER=/data/uploadsdiff --git a/env.whisper.example b/env.whisper.exampleindex ab22bd33..6482103b 100644--- a/env.whisper.example+++ b/env.whisper.example@@ -23,11 +23,31 @@ ALLOW_REGISTRATION=falseSUMMARY_MAX_TOKENS=8000CHAT_MAX_TOKENS=5000+# Set the logging level for the application.+# Options: DEBUG, INFO, WARNING, ERROR+LOG_LEVEL="INFO"+# --- Admin User (created on first run) ---ADMIN_USERNAME=adminADMIN_PASSWORD=changeme+# --- Automated File Processing (Black Hole Directory) ---+# Set to "true" to enable automated file processing+ENABLE_AUTO_PROCESSING=false++# Processing mode: admin_only, user_directories, or single_user+AUTO_PROCESS_MODE=admin_only++# Directory to watch for new audio files+AUTO_PROCESS_WATCH_DIR=/data/auto-process++# How often to check for new files (seconds)+AUTO_PROCESS_CHECK_INTERVAL=30++# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)+# AUTO_PROCESS_DEFAULT_USERNAME=admin+# --- Docker Settings (rarely need to be changed) ---SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.dbUPLOAD_FOLDER=/data/uploadsdiff --git a/file_monitor.py b/file_monitor.pynew file mode 100644index 00000000..237c0ecb--- /dev/null+++ b/file_monitor.py@@ -0,0 +1,456 @@+#!/usr/bin/env python3+"""+File Monitor for Automated Audio Processing+Monitors directories for new audio files and automatically processes them.+Supports multiple user modes:+1. Admin-only: Files go to admin user only+2. User-specific directories: Each user has their own folder (e.g., /auto-process/user123/)+3. Single default user: All files go to one specified user+"""++import os+import time+import threading+import logging+from datetime import datetime+from pathlib import Path+import mimetypes+import subprocess+from werkzeug.utils import secure_filename++# Flask app components will be imported inside functions to avoid circular imports++class FileMonitor:+ def __init__(self, base_watch_directory, check_interval=30, mode='admin_only'):+ """+ Initialize the file monitor.++ Args:+ base_watch_directory (str): Base directory to monitor for new files+ check_interval (int): How often to check for new files (seconds)+ mode (str): Processing mode - 'admin_only', 'user_directories', or 'single_user'+ """+ self.base_watch_directory = Path(base_watch_directory)+ self.check_interval = check_interval+ self.mode = mode+ self.running = False+ self.thread = None++ # Ensure base directory exists+ self.base_watch_directory.mkdir(parents=True, exist_ok=True)++ # Setup logging+ self.logger = logging.getLogger('file_monitor')+ self.logger.setLevel(logging.INFO)++ # Supported audio file extensions+ self.supported_extensions = {+ '.wav', '.mp3', '.flac', '.amr', '.3gp', '.3gpp',+ '.m4a', '.aac', '.ogg', '.wma', '.webm', '.mp4', '.mov'+ }++ # Cache for admin user and valid users+ self._admin_user_id = None+ self._valid_users = {} # Maps user_id to username+ self._username_to_id = {} # Maps username to user_id+ self._last_user_cache_update = 0++ def start(self):+ """Start the file monitoring in a background thread."""+ if self.running:+ self.logger.warning("File monitor is already running")+ return++ self.running = True+ self.thread = threading.Thread(target=self._monitor_loop, daemon=True)+ self.thread.start()+ self.logger.info(f"File monitor started in '{self.mode}' mode, watching: {self.base_watch_directory}")++ def stop(self):+ """Stop the file monitoring."""+ self.running = False+ if self.thread:+ self.thread.join(timeout=5)+ self.logger.info("File monitor stopped")++ def _update_user_cache(self):+ """Update the cache of valid users and admin user."""+ current_time = time.time()+ # Update cache every 5 minutes+ if current_time - self._last_user_cache_update < 300:+ return++ # Import Flask components inside function to avoid circular imports+ from app import app, db, User++ with app.app_context():+ try:+ # Find admin user+ admin_user = User.query.filter_by(is_admin=True).first()+ self._admin_user_id = admin_user.id if admin_user else None++ # Cache all valid users+ users = User.query.all()+ self._valid_users = {user.id: user.username for user in users}+ self._username_to_id = {user.username: user.id for user in users}++ self._last_user_cache_update = current_time+ self.logger.debug(f"Updated user cache: {len(self._valid_users)} users, admin: {self._admin_user_id}")++ except Exception as e:+ self.logger.error(f"Error updating user cache: {e}")++ def _monitor_loop(self):+ """Main monitoring loop."""+ while self.running:+ try:+ self._update_user_cache()++ if self.mode == 'admin_only':+ self._scan_admin_directory()+ elif self.mode == 'user_directories':+ self._scan_user_directories()+ elif self.mode == 'single_user':+ self._scan_single_user_directory()++ except Exception as e:+ self.logger.error(f"Error during directory scan: {e}", exc_info=True)++ # Wait for next check+ time.sleep(self.check_interval)++ def _scan_admin_directory(self):+ """Scan the main directory for files to process as admin user."""+ if not self._admin_user_id:+ self.logger.warning("No admin user found, skipping admin directory scan")+ return++ self._scan_directory_for_user(self.base_watch_directory, self._admin_user_id)++ def _scan_user_directories(self):+ """Scan user-specific subdirectories."""+ if not self.base_watch_directory.exists():+ return++ # Look for user directories (e.g., user123, user456)+ for item in self.base_watch_directory.iterdir():+ if not item.is_dir():+ continue++ # Extract user ID from directory name+ user_id = self._extract_user_id_from_dirname(item.name)+ if user_id and user_id in self._valid_users:+ self._scan_directory_for_user(item, user_id)+ elif item.name.startswith('user'):+ self.logger.warning(f"Found user directory '{item.name}' but user ID {user_id} is not valid")++ def _scan_single_user_directory(self):+ """Scan directory for a single configured user."""+ default_username = os.environ.get('AUTO_PROCESS_DEFAULT_USERNAME')+ if not default_username:+ self.logger.warning("AUTO_PROCESS_DEFAULT_USERNAME not configured for single_user mode")+ return++ user_id = self._username_to_id.get(default_username)+ if user_id:+ self._scan_directory_for_user(self.base_watch_directory, user_id)+ else:+ self.logger.warning(f"Configured default username '{default_username}' is not valid")++ def _scan_directory_for_user(self, directory, user_id):+ """Scan a specific directory for files to process for a specific user."""+ if not directory.exists():+ return++ for file_path in directory.iterdir():+ if not file_path.is_file():+ continue++ # Skip hidden files, processing files, or non-supported files+ if file_path.name.startswith('.') or file_path.suffix == '.processing':+ continue++ if file_path.suffix.lower() not in self.supported_extensions:+ continue++ # Check if file is still being written (size stability check)+ try:+ if not self._is_file_stable(file_path):+ continue+ except FileNotFoundError:+ # File might have been picked up by another worker after iterdir()+ continue++ self.logger.info(f"Found potential audio file for user {user_id}: {file_path}")++ # --- Atomic Lock via Rename ---+ processing_path = file_path.with_suffix(file_path.suffix + '.processing')++ try:+ file_path.rename(processing_path)+ self.logger.info(f"Acquired lock for {file_path}, renamed to {processing_path}")+ except FileNotFoundError:+ self.logger.debug(f"Could not acquire lock for {file_path}, already processed by another worker.")+ continue+ except Exception as e:+ self.logger.error(f"Error acquiring lock for {file_path}: {e}")+ continue++ # --- Process the locked file ---+ try:+ self._process_file(processing_path, user_id)+ except Exception as e:+ self.logger.error(f"Error processing file {processing_path}: {e}", exc_info=True)+ # If processing fails, unlock the file by renaming it back+ try:+ original_path = processing_path.with_suffix(processing_path.suffix.replace('.processing', ''))+ processing_path.rename(original_path)+ self.logger.info(f"Unlocked file {processing_path} back to {original_path} after processing error.")+ except Exception as rename_err:+ self.logger.error(f"CRITICAL: Failed to unlock file {processing_path} after error: {rename_err}")++ def _extract_user_id_from_dirname(self, dirname):+ """+ Extract user ID from directory name.++ Expected formats: user123, 123++ Args:+ dirname (str): Directory name++ Returns:+ int or None: User ID if found, None otherwise+ """+ import re++ # Pattern: user123 or just 123+ patterns = [+ r'^user(\d+)$', # user123+ r'^(\d+)$' # 123+ ]++ for pattern in patterns:+ match = re.match(pattern, dirname, re.IGNORECASE)+ if match:+ try:+ return int(match.group(1))+ except ValueError:+ continue++ return None++ def _is_file_stable(self, file_path, stability_time=5):+ """+ Check if a file is stable (not being written to).++ Args:+ file_path (Path): Path to the file+ stability_time (int): Time in seconds to wait for size stability++ Returns:+ bool: True if file appears stable+ """+ try:+ initial_size = file_path.stat().st_size+ initial_mtime = file_path.stat().st_mtime++ # Wait a bit and check again+ time.sleep(min(stability_time, 2))++ current_size = file_path.stat().st_size+ current_mtime = file_path.stat().st_mtime++ # File is stable if size and modification time haven't changed+ return initial_size == current_size and initial_mtime == current_mtime++ except (OSError, FileNotFoundError):+ return False++ def _process_file(self, processing_path, user_id):+ """+ Process a single locked audio file for a specific user.++ Args:+ processing_path (Path): Path to the locked audio file (e.g., file.mp3.processing)+ user_id (int): ID of the user to assign the recording to+ """+ # Import Flask components inside function to avoid circular imports+ from app import app, db, Recording, User, transcribe_audio_task++ with app.app_context():+ try:+ # Verify user exists+ user = db.session.get(User, user_id)+ if not user:+ self.logger.error(f"User ID {user_id} not found in database for file {processing_path}")+ # We must raise an exception to trigger the unlock mechanism+ raise ValueError(f"User ID {user_id} not found")++ # Derive original filename by removing .processing suffix+ original_filename = processing_path.name.replace('.processing', '')+ safe_filename = secure_filename(original_filename)+ timestamp = datetime.now().strftime('%Y%m%d%H%M%S')+ new_filename = f"auto_{timestamp}_{safe_filename}"++ uploads_dir = Path(app.config['UPLOAD_FOLDER'])+ uploads_dir.mkdir(parents=True, exist_ok=True)+ destination_path = uploads_dir / new_filename++ # Copy locked file to uploads directory+ import shutil+ shutil.copy(str(processing_path), str(destination_path))+ self.logger.info(f"Copied {processing_path} to {destination_path}")++ # Delete the locked file from watch directory after successful copy+ try:+ processing_path.unlink()+ self.logger.info(f"Deleted locked file: {processing_path}")+ except FileNotFoundError:+ # This should not happen if the lock is held, but good to log+ self.logger.warning(f"Locked file {processing_path} was already deleted.")++ # Convert file if necessary (same logic as upload_file)+ final_path = self._convert_file_if_needed(destination_path, original_filename)++ # Get file size and MIME type+ file_size = final_path.stat().st_size+ mime_type, _ = mimetypes.guess_type(str(final_path))++ # Create database record+ recording = Recording(+ audio_path=str(final_path),+ original_filename=original_filename,+ title=f"Auto-processed - {original_filename}",+ file_size=file_size,+ status='PENDING',+ meeting_date=datetime.utcnow().date(),+ user_id=user_id,+ mime_type=mime_type,+ is_inbox=True, # Auto-processed files go to inbox+ processing_source='auto_process' # Track that this was auto-processed+ )++ db.session.add(recording)+ db.session.commit()++ self.logger.info(f"Created recording record with ID: {recording.id} for user: {user.username}")++ # Start background processing+ start_time = datetime.utcnow()+ thread = threading.Thread(+ target=transcribe_audio_task,+ args=(app.app_context(), recording.id, str(final_path), final_path.name, start_time)+ )+ thread.start()++ self.logger.info(f"Started background processing for recording ID: {recording.id}")+ self.logger.info(f"Successfully processed and moved file from: {processing_path}")++ except Exception as e:+ self.logger.error(f"Error processing file {processing_path} for user {user_id}: {e}", exc_info=True)+ # Re-raise the exception to be caught by the calling method, which will handle unlocking.+ raise++ def _convert_file_if_needed(self, file_path, original_filename):+ """+ Convert audio file to supported format if needed.++ Args:+ file_path (Path): Current file path+ original_filename (str): Original filename for format detection++ Returns:+ Path: Path to the final (possibly converted) file+ """+ filename_lower = original_filename.lower()+ supported_formats = ('.wav', '.mp3', '.flac')++ if filename_lower.endswith(supported_formats):+ return file_path++ # Need to convert+ self.logger.info(f"Converting {filename_lower} format to WAV")++ base_path = file_path.with_suffix('')+ temp_wav_path = base_path.with_suffix('.temp.wav')+ final_wav_path = base_path.with_suffix('.wav')++ try:+ # Convert using ffmpeg+ subprocess.run([+ 'ffmpeg', '-i', str(file_path), '-y',+ '-acodec', 'pcm_s16le', '-ar', '16000', '-ac', '1',+ str(temp_wav_path)+ ], check=True, capture_output=True, text=True)++ self.logger.info(f"Successfully converted {file_path} to {temp_wav_path}")++ # Remove original and rename temp file+ file_path.unlink()+ temp_wav_path.rename(final_wav_path)++ return final_wav_path++ except FileNotFoundError:+ self.logger.error("ffmpeg not found. Please ensure ffmpeg is installed.")+ raise+ except subprocess.CalledProcessError as e:+ self.logger.error(f"ffmpeg conversion failed: {e.stderr}")+ raise+++# Global file monitor instance+file_monitor = None++def start_file_monitor():+ """Start the file monitor with configuration from environment variables."""+ global file_monitor++ if file_monitor and file_monitor.running:+ return++ # Import Flask app inside function to avoid circular imports+ from app import app++ # Get configuration from environment+ watch_dir = os.environ.get('AUTO_PROCESS_WATCH_DIR', '/data/auto-process')+ check_interval = int(os.environ.get('AUTO_PROCESS_CHECK_INTERVAL', '30'))+ mode = os.environ.get('AUTO_PROCESS_MODE', 'admin_only') # admin_only, user_directories, single_user++ # Validate mode+ valid_modes = ['admin_only', 'user_directories', 'single_user']+ if mode not in valid_modes:+ app.logger.error(f"Invalid AUTO_PROCESS_MODE: {mode}. Must be one of: {valid_modes}")+ return++ # Only start if auto-processing is enabled+ if os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true':+ file_monitor = FileMonitor(+ base_watch_directory=watch_dir,+ check_interval=check_interval,+ mode=mode+ )+ file_monitor.start()+ app.logger.info(f"Automated file processing started in '{mode}' mode")+ else:+ app.logger.info("Automated file processing is disabled")++def stop_file_monitor():+ """Stop the file monitor."""+ global file_monitor+ if file_monitor:+ file_monitor.stop()+ file_monitor = None++def get_file_monitor_status():+ """Get the current status of the file monitor."""+ global file_monitor+ if file_monitor and file_monitor.running:+ return {+ 'running': True,+ 'mode': file_monitor.mode,+ 'watch_directory': str(file_monitor.base_watch_directory),+ 'check_interval': file_monitor.check_interval+ }+ else:+ return {'running': False}diff --git a/requirements.txt b/requirements.txtindex 98f68889..fdee27ec 100644--- a/requirements.txt+++ b/requirements.txt@@ -3,6 +3,7 @@ flask-sqlalchemy==3.1.1flask-login==0.6.3flask-wtf==1.2.2flask-bcrypt==1.0.1+Flask-Limiter==3.5.0email-validator==2.2.0openai==1.3.0werkzeug==2.3.7diff --git a/resize_logo.py b/resize_logo.pynew file mode 100644index 00000000..58399ada--- /dev/null+++ b/resize_logo.py@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""+Logo Resizer Script for Speakr+Resizes a source PNG image to all required icon sizes for PWA and favicon support.++Usage:+ python resize_logo.py <source_image.png>++Requirements:+ pip install Pillow++This script will create all the necessary icon sizes in the static/img/ directory.+"""++import sys+import os+from PIL import Image, ImageDraw+import argparse++def create_maskable_version(image, size):+ """Create a maskable version with safe zone padding (20% on all sides)"""+ # Calculate the size of the logo with padding+ logo_size = int(size * 0.6) # Logo takes 60% of the canvas (20% padding on each side)++ # Create new image with transparent background+ maskable = Image.new('RGBA', (size, size), (0, 0, 0, 0))++ # Resize the original logo+ logo_resized = image.resize((logo_size, logo_size), Image.Resampling.LANCZOS)++ # Calculate position to center the logo+ x = (size - logo_size) // 2+ y = (size - logo_size) // 2++ # Paste the logo onto the center of the canvas+ maskable.paste(logo_resized, (x, y), logo_resized if logo_resized.mode == 'RGBA' else None)++ return maskable++def resize_logo(source_path, output_dir="static/img"):+ """Resize the source image to all required sizes"""++ # Check if source file exists+ if not os.path.exists(source_path):+ print(f"Error: Source file '{source_path}' not found!")+ return False++ # Create output directory if it doesn't exist+ os.makedirs(output_dir, exist_ok=True)++ try:+ # Open the source image+ with Image.open(source_path) as img:+ # Convert to RGBA if not already (for transparency support)+ if img.mode != 'RGBA':+ img = img.convert('RGBA')++ print(f"Source image: {img.size[0]}x{img.size[1]} pixels")+ print(f"Output directory: {output_dir}")+ print()++ # Define all the sizes we need+ sizes = {+ # Essential PWA icons+ 'icon-192x192.png': 192,+ 'icon-512x512.png': 512,++ # Additional recommended icons+ 'icon-16x16.png': 16,+ 'icon-32x32.png': 32,+ 'icon-180x180.png': 180, # Apple touch icon++ # Maskable version+ 'icon-maskable-512x512.png': 512,+ }++ # Resize to each required size+ for filename, size in sizes.items():+ output_path = os.path.join(output_dir, filename)++ if 'maskable' in filename:+ # Create maskable version with safe zone+ resized = create_maskable_version(img, size)+ print(f"✓ Created maskable icon: {filename} ({size}x{size})")+ else:+ # Regular resize+ resized = img.resize((size, size), Image.Resampling.LANCZOS)+ print(f"✓ Created icon: {filename} ({size}x{size})")++ # Save the resized image+ resized.save(output_path, 'PNG', optimize=True)++ print()+ print("🎉 All icons created successfully!")+ print()+ print("Next steps:")+ print("1. Replace static/img/favicon.svg with your SVG version (if you have one)")+ print("2. Clear browser cache and test the new icons")+ print("3. Test PWA installation to verify icons appear correctly")++ return True++ except Exception as e:+ print(f"Error processing image: {e}")+ return False++def create_ico_favicon(source_path, output_dir="static/img"):+ """Create a multi-size ICO favicon file"""+ try:+ with Image.open(source_path) as img:+ if img.mode != 'RGBA':+ img = img.convert('RGBA')++ # Create different sizes for the ICO file+ sizes = [16, 32, 48]+ images = []++ for size in sizes:+ resized = img.resize((size, size), Image.Resampling.LANCZOS)+ images.append(resized)++ # Save as ICO file+ ico_path = os.path.join(output_dir, 'favicon.ico')+ images[0].save(ico_path, format='ICO', sizes=[(img.width, img.height) for img in images])+ print(f"✓ Created favicon.ico with sizes: {sizes}")++ except Exception as e:+ print(f"Warning: Could not create favicon.ico: {e}")++def main():+ parser = argparse.ArgumentParser(description='Resize logo for Speakr PWA icons')+ parser.add_argument('source', help='Source PNG image file')+ parser.add_argument('--output-dir', default='static/img', help='Output directory (default: static/img)')+ parser.add_argument('--create-ico', action='store_true', help='Also create favicon.ico file')++ args = parser.parse_args()++ print("🎨 Speakr Logo Resizer")+ print("=" * 50)++ # Resize the logo+ success = resize_logo(args.source, args.output_dir)++ if success and args.create_ico:+ print()+ create_ico_favicon(args.source, args.output_dir)++ if success:+ print()+ print("📁 Files created in", args.output_dir + ":")+ for file in os.listdir(args.output_dir):+ if file.startswith('icon-') and file.endswith('.png'):+ file_path = os.path.join(args.output_dir, file)+ size = os.path.getsize(file_path)+ print(f" {file} ({size:,} bytes)")++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python resize_logo.py <source_image.png>")+ print("Example: python resize_logo.py my_logo.png")+ sys.exit(1)++ main()diff --git a/resize_logo.sh b/resize_logo.shnew file mode 100755index 00000000..dcf0e069--- /dev/null+++ b/resize_logo.sh@@ -0,0 +1,83 @@+#!/bin/bash++# Logo Resizer Script for Speakr (ImageMagick version)+# Resizes a source PNG image to all required icon sizes for PWA and favicon support.+#+# Usage: ./resize_logo.sh <source_image.png>+# Requirements: ImageMagick (sudo apt install imagemagick)++set -e++# Check if source file is provided+if [ $# -eq 0 ]; then+ echo "Usage: $0 <source_image.png>"+ echo "Example: $0 my_logo.png"+ exit 1+fi++SOURCE_FILE="$1"+OUTPUT_DIR="static/img"++# Check if source file exists+if [ ! -f "$SOURCE_FILE" ]; then+ echo "Error: Source file '$SOURCE_FILE' not found!"+ exit 1+fi++# Check if ImageMagick is installed+if ! command -v convert &> /dev/null; then+ echo "Error: ImageMagick is not installed!"+ echo "Install it with: sudo apt install imagemagick"+ exit 1+fi++# Create output directory if it doesn't exist+mkdir -p "$OUTPUT_DIR"++echo "🎨 Speakr Logo Resizer (ImageMagick)"+echo "=================================================="+echo "Source file: $SOURCE_FILE"+echo "Output directory: $OUTPUT_DIR"+echo++# Define sizes+declare -A SIZES=(+ ["icon-16x16.png"]=16+ ["icon-32x32.png"]=32+ ["icon-180x180.png"]=180+ ["icon-192x192.png"]=192+ ["icon-512x512.png"]=512+)++# Resize to each size+for filename in "${!SIZES[@]}"; do+ size=${SIZES[$filename]}+ output_path="$OUTPUT_DIR/$filename"++ convert "$SOURCE_FILE" -resize "${size}x${size}" "$output_path"+ echo "✓ Created icon: $filename (${size}x${size})"+done++# Create maskable version with padding+echo "✓ Creating maskable icon with safe zone..."+convert "$SOURCE_FILE" -resize 307x307 -gravity center -extent 512x512 -background transparent "$OUTPUT_DIR/icon-maskable-512x512.png"+echo "✓ Created maskable icon: icon-maskable-512x512.png (512x512)"++# Create favicon.ico (optional)+if command -v convert &> /dev/null; then+ echo "✓ Creating favicon.ico..."+ convert "$SOURCE_FILE" -resize 16x16 -resize 32x32 -resize 48x48 "$OUTPUT_DIR/favicon.ico"+ echo "✓ Created favicon.ico"+fi++echo+echo "🎉 All icons created successfully!"+echo+echo "📁 Files created:"+ls -la "$OUTPUT_DIR"/icon-*.png "$OUTPUT_DIR"/favicon.ico 2>/dev/null || true++echo+echo "Next steps:"+echo "1. Replace static/img/favicon.svg with your SVG version (if you have one)"+echo "2. Clear browser cache and test the new icons"+echo "3. Test PWA installation to verify icons appear correctly"diff --git a/static/css/styles.css b/static/css/styles.cssindex d4badfcb..9606c0e8 100644--- a/static/css/styles.css+++ b/static/css/styles.css@@ -1,3 +1,12 @@+body.unloaded {+ opacity: 0;+ transition: opacity 0.5s ease-in-out;+}++[v-cloak] {+ display: none;+}+/* Color Scheme CSS Variables */:root {/* Default Light Theme (Blue) */@@ -16,7 +25,7 @@--bg-success-light: #d1fae5; /* green-100 */--bg-pending-light: #f5f5f4; /* stone-100 */--bg-input: #ffffff; /* white */- --bg-audio-player: linear-gradient(to right, #eff6ff, #eef2ff); /* blue-50, indigo-50 */+ --bg-audio-player: var(--bg-tertiary);--text-primary: #1f2937; /* gray-800 */--text-secondary: #374151; /* gray-700 */@@ -56,13 +65,14 @@--bg-accent-hover: #e6f7ea; /* slightly deeper green */--bg-button: #059669; /* keep button visible */--bg-button-hover: #047857; /* keep button visible */+ --bg-input: #ffffff; /* white input background */--text-accent: #047857; /* keep accent text visible */--border-primary: #e8f5eb; /* light green border */--border-secondary: #d1f2d8; /* soft green border */--border-accent: #b8e6c1; /* medium green border */--border-focus: #10b981; /* keep focus visible */--ring-focus: #e6f7ea; /* soft green ring */- --bg-audio-player: linear-gradient(to right, #f1fcf3, #f6fdf8); /* soft green gradient */+ --bg-audio-player: var(--bg-tertiary);}.theme-light-purple {@@ -73,13 +83,14 @@--bg-accent-hover: #ebe4ff; /* slightly deeper purple */--bg-button: #7c3aed; /* keep button visible */--bg-button-hover: #6d28d9; /* keep button visible */+ --bg-input: #ffffff; /* white input background */--text-accent: #6d28d9; /* keep accent text visible */--border-primary: #ede9fe; /* light purple border */--border-secondary: #ddd6fe; /* soft purple border */--border-accent: #c4b5fd; /* medium purple border */--border-focus: #8b5cf6; /* keep focus visible */--ring-focus: #ebe4ff; /* soft purple ring */- --bg-audio-player: linear-gradient(to right, #f5f2ff, #faf8ff); /* soft purple gradient */+ --bg-audio-player: var(--bg-tertiary);}.theme-light-rose {@@ -90,13 +101,14 @@--bg-accent-hover: #f7e4ec; /* slightly deeper rose */--bg-button: #e11d48; /* keep button visible */--bg-button-hover: #be185d; /* keep button visible */+ --bg-input: #ffffff; /* white input background */--text-accent: #be185d; /* keep accent text visible */--border-primary: #fce7f3; /* light rose border */--border-secondary: #f9d2e4; /* soft rose border */--border-accent: #f3a8c7; /* medium rose border */--border-focus: #ec4899; /* keep focus visible */--ring-focus: #f7e4ec; /* soft rose ring */- --bg-audio-player: linear-gradient(to right, #fcf2f6, #fdf8fb); /* soft rose gradient */+ --bg-audio-player: var(--bg-tertiary);}.theme-light-amber {@@ -107,13 +119,14 @@--bg-accent-hover: #f7e9db; /* slightly deeper amber */--bg-button: #d97706; /* keep button visible */--bg-button-hover: #b45309; /* keep button visible */+ --bg-input: #ffffff; /* white input background */--text-accent: #b45309; /* keep accent text visible */--border-primary: #fef3c7; /* light amber border */--border-secondary: #fde68a; /* soft amber border */--border-accent: #fcd34d; /* medium amber border */--border-focus: #f59e0b; /* keep focus visible */--ring-focus: #f7e9db; /* soft amber ring */- --bg-audio-player: linear-gradient(to right, #fcf6f1, #fdfaf6); /* soft amber gradient */+ --bg-audio-player: var(--bg-tertiary);}.theme-light-teal {@@ -124,13 +137,14 @@--bg-accent-hover: #e6f9f5; /* slightly deeper teal */--bg-button: #0d9488; /* keep button visible */--bg-button-hover: #0f766e; /* keep button visible */+ --bg-input: #ffffff; /* white input background */--text-accent: #0f766e; /* keep accent text visible */--border-primary: #ccfbf1; /* light teal border */--border-secondary: #99f6e4; /* soft teal border */--border-accent: #5eead4; /* medium teal border */--border-focus: #14b8a6; /* keep focus visible */--ring-focus: #e6f9f5; /* soft teal ring */- --bg-audio-player: linear-gradient(to right, #f1fcfa, #f6fdfc); /* soft teal gradient */+ --bg-audio-player: var(--bg-tertiary);}/* Dark Theme Base */@@ -150,7 +164,7 @@--bg-success-light: #064e3b; /* green-900 */--bg-pending-light: #292524; /* stone-800 */--bg-input: #374151; /* gray-700 */- --bg-audio-player: linear-gradient(to right, #374151, #4b5563); /* gray-700, gray-600 */+ --bg-audio-player: var(--bg-secondary);--text-primary: #f3f4f6; /* gray-100 */--text-secondary: #d1d5db; /* gray-300 */@@ -186,13 +200,14 @@--bg-accent-hover: #425440; /* lighter emerald accent */--bg-button: #059669; /* keep button visible */--bg-button-hover: #10b981; /* keep button visible */+ --bg-input: #2e3c30; /* darker emerald input background */--text-accent: #7dd3ae; /* muted pastel emerald text */--border-primary: #3a4540; /* visible emerald border */--border-secondary: #485548; /* lighter emerald border */--border-accent: #556550; /* medium emerald border */--border-focus: #10b981; /* keep focus visible */--ring-focus: #384838; /* visible ring */- --bg-audio-player: linear-gradient(to right, #2e3c30, #384838); /* visible emerald gradient */+ --bg-audio-player: var(--bg-tertiary);}.dark.theme-dark-purple {@@ -203,13 +218,14 @@--bg-accent-hover: #4e4854; /* lighter purple accent */--bg-button: #7c3aed; /* keep button visible */--bg-button-hover: #8b5cf6; /* keep button visible */+ --bg-input: #36303c; /* darker purple input background */--text-accent: #b8a5d4; /* muted pastel purple text */--border-primary: #484050; /* visible purple border */--border-secondary: #555058; /* lighter purple border */--border-accent: #626060; /* medium purple border */--border-focus: #8b5cf6; /* keep focus visible */--ring-focus: #423c48; /* visible ring */- --bg-audio-player: linear-gradient(to right, #36303c, #423c48); /* visible purple gradient */+ --bg-audio-player: var(--bg-tertiary);}.dark.theme-dark-rose {@@ -220,13 +236,14 @@--bg-accent-hover: #54484c; /* lighter rose accent */--bg-button: #e11d48; /* keep button visible */--bg-button-hover: #f43f5e; /* keep button visible */+ --bg-input: #3c3030; /* darker rose input background */--text-accent: #d4a5b4; /* muted pastel rose text */--border-primary: #504048; /* visible rose border */--border-secondary: #585050; /* lighter rose border */--border-accent: #606058; /* medium rose border */--border-focus: #f43f5e; /* keep focus visible */--ring-focus: #483c40; /* visible ring */- --bg-audio-player: linear-gradient(to right, #3c3030, #483c40); /* visible rose gradient */+ --bg-audio-player: var(--bg-tertiary);}.dark.theme-dark-amber {@@ -237,13 +254,14 @@--bg-accent-hover: #544c42; /* lighter amber accent */--bg-button: #d97706; /* keep button visible */--bg-button-hover: #f59e0b; /* keep button visible */+ --bg-input: #3c342e; /* darker amber input background */--text-accent: #d4c5a5; /* muted pastel amber text */--border-primary: #504840; /* visible amber border */--border-secondary: #585548; /* lighter amber border */--border-accent: #606250; /* medium amber border */--border-focus: #f59e0b; /* keep focus visible */--ring-focus: #484038; /* visible ring */- --bg-audio-player: linear-gradient(to right, #3c342e, #484038); /* visible amber gradient */+ --bg-audio-player: var(--bg-tertiary);}.dark.theme-dark-teal {@@ -254,22 +272,34 @@--bg-accent-hover: #425454; /* lighter teal accent */--bg-button: #0d9488; /* keep button visible */--bg-button-hover: #14b8a6; /* keep button visible */+ --bg-input: #2e3c3c; /* darker teal input background */--text-accent: #a5d4d0; /* muted pastel teal text */--border-primary: #404848; /* visible teal border */--border-secondary: #485555; /* lighter teal border */--border-accent: #506262; /* medium teal border */--border-focus: #14b8a6; /* keep focus visible */--ring-focus: #384848; /* visible ring */- --bg-audio-player: linear-gradient(to right, #2e3c3c, #384848); /* visible teal gradient */+ --bg-audio-player: var(--bg-tertiary);}/* Modern UI styles */.height-100 { height: 100%; }.drag-area { transition: background-color 0.3s ease, border-color 0.3s ease; }-.custom-scrollbar::-webkit-scrollbar { width: 6px; }-.custom-scrollbar::-webkit-scrollbar-track { background: var(--scrollbar-track); border-radius: 12px; }-.custom-scrollbar::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 12px; }-.custom-scrollbar::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover); }+/* Global Scrollbar Styles */+::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}+::-webkit-scrollbar-track {+ background: var(--scrollbar-track);+}+::-webkit-scrollbar-thumb {+ background: var(--scrollbar-thumb);+ border-radius: 10px;+}+::-webkit-scrollbar-thumb:hover {+ background: var(--scrollbar-thumb-hover);+}html { /* Apply base colors to html for smoother transitions */background-color: var(--bg-primary);color: var(--text-primary);@@ -542,6 +572,20 @@ div[v-if="!editingNotes"] {.status-completed { color: #065f46; background-color: #d1fae5; } /* text-green-800 bg-green-100 */.status-failed { color: #991b1b; background-color: #fee2e2; } /* text-red-800 bg-red-100 */.status-pending { color: #57534e; background-color: #f5f5f4; } /* text-stone-700 bg-stone-100 */+ .status-highlighted { color: #d97706; background-color: #fef3c7; border: 1px solid #f59e0b; } /* text-amber-700 bg-amber-100 border-amber-500 */+ .status-inbox { color: #1d4ed8; background-color: #dbeafe; border: 1px solid #3b82f6; } /* text-blue-700 bg-blue-100 border-blue-500 */++ /* Clickable badge styles */+ .clickable-badge {+ cursor: pointer;+ transition: all 0.2s ease;+ }++ .clickable-badge:hover {+ transform: translateY(-1px);+ box-shadow: 0 2px 4px rgba(0,0,0,0.15);+ opacity: 0.8;+ }/* Transcription box with flex layout */.transcription-box {@@ -553,27 +597,35 @@ div[v-if="!editingNotes"] {/* Modern copy button styles */.copy-btn {- position: sticky;- top: 10px;- right: 10px;- float: right;- background-color: rgba(255, 255, 255, 0.9);- border: 1px solid #e5e7eb;- border-radius: 0.5rem;- padding: 0.35rem 0.75rem;- font-size: 0.75rem;- cursor: pointer;- z-index: 10;- transition: all 0.2s cubic-bezier(0.25, 0.1, 0.25, 1);- margin-bottom: 10px;- box-shadow: 0 1px 2px rgba(0,0,0,0.05);+ background-color: var(--bg-tertiary);+ border: 1px solid var(--border-primary);+ color: var(--text-secondary);+ border-radius: 0.5rem;+ padding: 0.35rem 0.75rem;+ font-size: 0.75rem;+ cursor: pointer;+ transition: all 0.2s cubic-bezier(0.25, 0.1, 0.25, 1);+ box-shadow: 0 1px 2px rgba(0,0,0,0.05);+ display: inline-flex;+ align-items: center;+ justify-content: center;}.copy-btn:hover {- background-color: #f3f4f6;+ background-color: var(--bg-accent-hover);transform: translateY(-1px);box-shadow: 0 2px 4px rgba(0,0,0,0.1);}++ .dark .copy-btn {+ background-color: var(--bg-secondary);+ border-color: var(--border-secondary);+ color: var(--text-primary);+}++.dark .copy-btn:hover {+ background-color: var(--bg-tertiary);+}/* Hover edit button styles */.content-box {@@ -664,6 +716,16 @@ div[v-if="!editingNotes"] {border-radius: 1.25rem 1.25rem 1.25rem 0.25rem;padding: 0.875rem 1rem;}++ .dark .ai-message {+ background-color: #374151;+ color: #f3f4f6;+ }++ .dark .user-message {+ background-color: #1e40af;+ color: #ffffff;+ }.copyable {position: relative;@@ -793,6 +855,7 @@ div[v-if="!editingNotes"] {min-height: 0;overflow: hidden;flex-shrink: 0; /* Prevent shrinking */+ border-right: 1px solid var(--border-primary);/* Width is controlled by inline style */}@@ -1394,6 +1457,11 @@ body {margin-right: 0.25rem;}+.dark .view-mode-toggle {+ background-color: var(--bg-secondary);+ border-color: var(--border-secondary);+}+/* Speaker colors - enhanced palette with better variation and contrast */.speaker-color-1 { background-color: #E3F2FD; color: #0D47A1; } /* Deep Blue */.speaker-color-2 { background-color: #F3E5F5; color: #6A1B9A; } /* Deep Purple */@@ -1892,24 +1960,22 @@ body {width: 12px !important;background-color: transparent !important;cursor: ew-resize !important;- margin: 0 2px !important;- display: flex !important;- align-items: center !important;- justify-content: center !important;- padding: 0 !important;- flex-shrink: 0 !important; /* Prevent resizer from shrinking */-}--#mainColumnResizer .w-1 {- width: 4px !important;- height: 60px !important;- background-color: var(--text-light) !important;- border-radius: 2px !important;- transition: background-color 0.15s ease !important;+ margin: 0 -6px !important;+ position: relative;+ z-index: 10;}-#mainColumnResizer:hover .w-1 {- background-color: var(--border-accent) !important;+#mainColumnResizer:hover::before {+ content: '';+ position: absolute;+ left: 50%;+ top: 50%;+ transform: translate(-50%, -50%);+ width: 4px;+ height: 60px;+ background-color: var(--border-accent);+ border-radius: 2px;+ transition: background-color 0.15s ease;}/* Ensure consistent layout behavior when sidebar is collapsed */@@ -2305,7 +2371,6 @@ body {.dark .audio-player-container audio {background-color: var(--bg-secondary);border: 1px solid var(--border-secondary);- filter: brightness(1.2) contrast(1.1);}/* Audio player controls for WebKit browsers */@@ -2316,7 +2381,11 @@ body {.dark .audio-player-container audio::-webkit-media-controls-panel {background-color: var(--bg-secondary);- filter: brightness(1.3);+}++.audio-player-container audio::-webkit-media-controls-enclosure {+ border: none;+ background: none;}.audio-player-container audio::-webkit-media-controls-play-button,@@ -2328,7 +2397,6 @@ body {.dark .audio-player-container audio::-webkit-media-controls-play-button,.dark .audio-player-container audio::-webkit-media-controls-pause-button {- filter: brightness(1.4) contrast(1.2);}.audio-player-container audio::-webkit-media-controls-timeline {@@ -2339,7 +2407,6 @@ body {.dark .audio-player-container audio::-webkit-media-controls-timeline {background-color: var(--border-secondary);- filter: brightness(1.5);}.audio-player-container audio::-webkit-media-controls-current-time-display,@@ -2351,7 +2418,6 @@ body {.dark .audio-player-container audio::-webkit-media-controls-current-time-display,.dark .audio-player-container audio::-webkit-media-controls-time-remaining-display {color: var(--text-primary);- filter: brightness(1.3);}/* Audio player volume controls */@@ -2362,7 +2428,6 @@ body {.dark .audio-player-container audio::-webkit-media-controls-volume-slider {background-color: var(--border-secondary);- filter: brightness(1.4);}.audio-player-container audio::-webkit-media-controls-mute-button {@@ -2370,7 +2435,6 @@ body {}.dark .audio-player-container audio::-webkit-media-controls-mute-button {- filter: brightness(1.5) contrast(1.2);}/* Custom audio player wrapper for better control */@@ -2420,3 +2484,523 @@ body {.dark .audio-player-time {color: var(--text-secondary);}++/* ASR Editor Table Styles */+.asr-editor-table {+ width: 100%;+ border-collapse: collapse; /* Changed to collapse */+}++.asr-editor-table th {+ padding: 0.75rem 1rem;+ text-align: left;+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--text-muted);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ border-bottom: 2px solid var(--border-primary);+}++.asr-editor-table td {+ padding: 0.25rem; /* Reduced padding */+ vertical-align: middle;+ border: 1px solid var(--border-primary);+}++/* Custom Number Input with Subtle Spinners */+.custom-number-input {+ position: relative;+}++.custom-number-input input[type="number"] {+ -moz-appearance: textfield;+ padding-right: 1.75rem; /* Space for spinners */+}++.custom-number-input input[type="number"]::-webkit-inner-spin-button,+.custom-number-input input[type="number"]::-webkit-outer-spin-button {+ -webkit-appearance: none;+ margin: 0;+}++.number-spinners {+ position: absolute;+ right: 0;+ top: 0;+ bottom: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ opacity: 0;+ transition: opacity 0.2s ease;+}++.custom-number-input:hover .number-spinners {+ opacity: 1;+}++.number-spinners button {+ height: 50%;+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-muted);+ background-color: transparent;+ border: none;+ cursor: pointer;+ padding: 0;+}++.number-spinners button:hover {+ color: var(--text-primary);+}++.number-spinners button svg {+ width: 0.75rem;+ height: 0.75rem;+}++/* Speaker Combobox Styles */+.speaker-combobox {+ position: relative;+}++.speaker-combobox-input {+ width: 100%;+ padding-right: 2rem; /* Space for dropdown arrow */+}++.speaker-combobox-arrow {+ position: absolute;+ right: 0;+ top: 0;+ bottom: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ color: var(--text-muted);+ pointer-events: none;+}++.speaker-combobox-suggestions {+ position: absolute;+ z-index: 10;+ width: 100%;+ margin-top: 0.25rem;+ background-color: var(--bg-secondary);+ border: 1px solid var(--border-primary);+ border-radius: 0.5rem;+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);+ max-height: 12rem;+ overflow-y: auto;+}++.speaker-suggestion-item {+ padding: 0.5rem 0.75rem;+ cursor: pointer;+ font-size: 0.875rem;+}++.speaker-suggestion-item:hover {+ background-color: var(--bg-accent);+}++/* Markdown Editor Styles */+.markdown-editor-container {+ position: relative;+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+}++.markdown-editor-container .EasyMDEContainer {+ background: var(--bg-input);+ border: none;+ border-radius: 0.75rem;+ display: flex;+ flex-direction: column;+ height: 100%;+}++.markdown-editor-container .EasyMDEContainer .CodeMirror {+ background: var(--bg-input);+ color: var(--text-primary);+ border: none;+ border-radius: 0 0 0.75rem 0.75rem;+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace;+ font-size: 0.875rem;+ line-height: 1.5;+ flex: 1;+ min-height: 0;+ overflow: hidden !important;+}++/* Fix double scrolling by ensuring only the wrapper scrolls */+.markdown-editor-container .EasyMDEContainer .CodeMirror-scroll {+ overflow: auto !important;+ height: 100% !important;+}++.markdown-editor-container .EasyMDEContainer .CodeMirror-sizer {+ min-height: 100% !important;+}++.markdown-editor-container .EasyMDEContainer .CodeMirror-focused {+ outline: none;+ box-shadow: 0 0 0 2px var(--ring-focus);+}++.markdown-editor-container .EasyMDEContainer .editor-toolbar {+ background: var(--bg-tertiary);+ border-bottom: 1px solid var(--border-secondary);+ border-radius: 0.75rem 0.75rem 0 0;+ padding: 0.5rem;+ flex-shrink: 0;+}++.markdown-editor-container .EasyMDEContainer .editor-toolbar button {+ background: transparent;+ border: 1px solid transparent;+ color: var(--text-secondary);+ border-radius: 0.25rem;+ padding: 0.25rem;+ margin: 0 0.125rem;+ transition: all 0.2s ease;+}++.markdown-editor-container .EasyMDEContainer .editor-toolbar button:hover {+ background: var(--bg-accent);+ color: var(--text-accent);+ border-color: var(--border-accent);+}++.markdown-editor-container .EasyMDEContainer .editor-toolbar button.active {+ background: var(--bg-accent);+ color: var(--text-accent);+ border-color: var(--border-accent);+}++/* EasyMDE Fullscreen Mode Fixes */+.EasyMDEContainer .editor-fullscreen {+ z-index: 9999 !important;+}++/* Force hide speaker legend during any fullscreen mode - comprehensive approach */+.editor-fullscreen .speaker-legend,+.CodeMirror-fullscreen .speaker-legend,+body:has(.editor-fullscreen) .speaker-legend,+body:has(.CodeMirror-fullscreen) .speaker-legend {+ display: none !important;+}++/* Alternative: Lower z-index approach for speaker legend during fullscreen */+.editor-fullscreen ~ .speaker-legend,+.CodeMirror-fullscreen ~ .speaker-legend,+.editor-fullscreen + .speaker-legend,+.CodeMirror-fullscreen + .speaker-legend {+ z-index: -1 !important;+}++/* Target the specific fullscreen container that EasyMDE creates */+.CodeMirror-fullscreen-wrapper {+ z-index: 9999 !important;+}++/* Ensure fullscreen editor is above everything */+.CodeMirror-fullscreen {+ z-index: 9999 !important;+}++/* Hide speaker legend when any fullscreen editor is active */+body.CodeMirror-fullscreen .speaker-legend,+.CodeMirror-fullscreen .speaker-legend {+ display: none !important;+}++.markdown-editor-container .EasyMDEContainer .editor-preview {+ background: var(--bg-input);+ color: var(--text-primary);+ padding: 1rem;+ border-radius: 0 0 0.5rem 0.5rem;+}++.markdown-editor-container .EasyMDEContainer .editor-preview-side {+ background: var(--bg-input);+ color: var(--text-primary);+ border-left: 1px solid var(--border-secondary);+}++/* Dark mode adjustments for markdown editor */+.dark .markdown-editor-container .EasyMDEContainer .CodeMirror {+ background: var(--bg-input);+ color: var(--text-primary);+}++.dark .markdown-editor-container .EasyMDEContainer .editor-toolbar {+ background: var(--bg-tertiary);+ border-bottom-color: var(--border-secondary);+}++.dark .markdown-editor-container .EasyMDEContainer .editor-toolbar button {+ color: var(--text-secondary);+}++.dark .markdown-editor-container .EasyMDEContainer .editor-toolbar button:hover,+.dark .markdown-editor-container .EasyMDEContainer .editor-toolbar button.active {+ background: var(--bg-accent);+ color: var(--text-accent);+ border-color: var(--border-accent);+}++/* Markdown preview styling in notes */+.notes-preview h1, .notes-preview h2, .notes-preview h3,+.notes-preview h4, .notes-preview h5, .notes-preview h6 {+ font-weight: 600;+ margin-top: 1rem;+ margin-bottom: 0.5rem;+ color: var(--text-primary);+}++.notes-preview h1 { font-size: 1.5rem; }+.notes-preview h2 { font-size: 1.25rem; }+.notes-preview h3 { font-size: 1.125rem; }++.notes-preview p {+ margin-bottom: 0.75rem;+ line-height: 1.6;+}++.notes-preview ul, .notes-preview ol {+ margin-left: 1.5rem;+ margin-bottom: 0.75rem;+}++.notes-preview li {+ margin-bottom: 0.25rem;+}++.notes-preview code {+ background-color: var(--bg-tertiary);+ padding: 0.125rem 0.25rem;+ border-radius: 0.25rem;+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace;+ font-size: 0.875rem;+}++.notes-preview pre {+ background-color: var(--bg-tertiary);+ padding: 0.75rem;+ border-radius: 0.5rem;+ overflow-x: auto;+ margin-bottom: 0.75rem;+}++.notes-preview pre code {+ background-color: transparent;+ padding: 0;+}++.notes-preview blockquote {+ border-left: 4px solid var(--border-accent);+ padding-left: 1rem;+ margin-left: 0;+ margin-bottom: 0.75rem;+ color: var(--text-muted);+ font-style: italic;+}++.notes-preview table {+ border-collapse: collapse;+ width: 100%;+ margin-bottom: 0.75rem;+}++.notes-preview th, .notes-preview td {+ border: 1px solid var(--border-secondary);+ padding: 0.5rem;+ text-align: left;+}++.notes-preview th {+ background-color: var(--bg-tertiary);+ font-weight: 600;+}++/* Recording notes editor styles */+.recording-notes-editor .EasyMDEContainer {+ height: 100%;+ display: flex;+ flex-direction: column;+ border: 1px solid var(--border-secondary);+ border-radius: 0.5rem;+ overflow: hidden;+}++.summary-editor-container {+ position: relative;+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+}++.recording-notes-editor .CodeMirror,+.recording-notes-editor .editor-preview,+.recording-notes-editor .editor-preview-side {+ flex-grow: 1;+ background: var(--bg-input);+ color: var(--text-primary);+}++.recording-notes-editor .editor-toolbar {+ background: var(--bg-tertiary);+ border-bottom: 1px solid var(--border-secondary);+}++.recording-notes-editor .editor-toolbar button {+ color: var(--text-secondary);+ border: none;+}++.recording-notes-editor .editor-toolbar button:hover,+.recording-notes-editor .editor-toolbar button.active {+ background: var(--bg-accent);+ color: var(--text-accent);+ border: none;+}++.recording-notes-editor .CodeMirror-cursor {+ border-left: 1px solid var(--text-primary);+}++/* Recording notes textarea theme-aware styling */+.recording-notes-editor textarea {+ background-color: var(--bg-input) !important;+ color: var(--text-primary) !important;+ border-color: var(--border-secondary) !important;+}++.recording-notes-editor textarea:focus {+ background-color: var(--bg-input) !important;+ border-color: var(--border-focus) !important;+ box-shadow: 0 0 0 2px var(--ring-focus) !important;+}++/* Ensure all textareas in recording view use theme colors */+.recording-notes-editor textarea,+textarea[ref="recordingNotesEditor"] {+ background-color: var(--bg-input) !important;+ color: var(--text-primary) !important;+ border: 1px solid var(--border-secondary) !important;+}++/* Dark mode specific adjustments for recording notes */+.dark .recording-notes-editor textarea,+.dark textarea[ref="recordingNotesEditor"] {+ background-color: var(--bg-input) !important;+ color: var(--text-primary) !important;+ border-color: var(--border-secondary) !important;+}++/* Focus states for recording notes textarea */+.recording-notes-editor textarea:focus,+textarea[ref="recordingNotesEditor"]:focus {+ outline: none !important;+ border-color: var(--border-focus) !important;+ box-shadow: 0 0 0 2px var(--ring-focus) !important;+}++.mobile-view {+ display: flex;+ flex-direction: column;+ height: 100%;+ overflow: hidden;+}++.mobile-header {+ flex-shrink: 0;+}++.mobile-audio-player {+ flex-shrink: 0;+}++.mobile-tabs {+ flex-shrink: 0;+ overflow-x: auto;+}++.mobile-content {+ flex-grow: 1;+ overflow-y: auto;+}++/* --- New Sidebar & Main Content Layout --- */++/* Sidebar Container */+.sidebar {+ position: fixed; /* Changed to fixed to overlay correctly */+ top: 69px; /* Height of the header */+ left: 0;+ bottom: 0;+ width: 320px; /* w-80 */+ background-color: var(--bg-secondary);+ border-right: 1px solid var(--border-primary);+ z-index: 50; /* Higher z-index to be above backdrop */+ transform: translateX(0);+ transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);+ display: flex;+ flex-direction: column;+}++.sidebar.collapsed {+ transform: translateX(-100%);+}++/* Wrapper to prevent sidebar's own content from squishing */+.sidebar-content-wrapper {+ width: 320px; /* Fixed width */+ height: 100%;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+}++/* Main Content Area */+.main-content {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ transition: padding-left 0.3s cubic-bezier(0.4, 0, 0.2, 1);+ padding-left: 320px; /* Default space for the sidebar */+}++.main-content.sidebar-open {+ padding-left: 320px;+}++/* When sidebar is collapsed, main content takes full width */+.main-content:not(.sidebar-open) {+ padding-left: 0;+}++/* --- Responsive Styles --- */+@media (max-width: 1023px) {+ /* On mobile, main content always takes full width */+ .main-content {+ padding-left: 0 !important;+ }++ /* Sidebar is an overlay on mobile */+ .sidebar {+ top: 0; /* Cover full height on mobile */+ z-index: 60; /* Higher z-index for mobile overlay */+ }+}diff --git a/static/img/dark-mode.png b/static/img/dark-mode.pngindex 459af1df..423c600a 100644Binary files a/static/img/dark-mode.png and b/static/img/dark-mode.png differdiff --git a/static/img/edit_transcription.png b/static/img/edit_transcription.pngnew file mode 100644index 00000000..0c289362Binary files /dev/null and b/static/img/edit_transcription.png differdiff --git a/static/img/favicon.ico b/static/img/favicon.iconew file mode 100644index 00000000..2be72d57Binary files /dev/null and b/static/img/favicon.ico differdiff --git a/static/img/favicon.svg b/static/img/favicon.svgdeleted file mode 100644index a6601115..00000000--- a/static/img/favicon.svg+++ /dev/null@@ -1,27 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!-- Speakr – meeting transcription & analysis app logo -->-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 90 90" width="90" height="90" fill="none">- <defs>- <!-- Modern blue gradient for the icon -->- <linearGradient id="speakrGrad" x1="0" y1="0" x2="1" y2="1">- <stop offset="0%" stop-color="#4e7fc2" />- <stop offset="100%" stop-color="#2c5a94" />- </linearGradient>- </defs>-- <!-- Icon block -->- <g transform="translate(12 12)">- <!-- Rounded square background -->- <rect x="0" y="0" width="66" height="66" rx="14" fill="url(#speakrGrad)" />-- <!-- Stylised microphone (white) -->- <path d="M33 18 a11 11 0 0 1 11 11 v12 a11 11 0 0 1 -22 0 v-12 a11 11 0 0 1 11 -11 z"- fill="#ffffff"/>-- <!-- Microphone stem -->- <rect x="31" y="51" width="4" height="9" fill="#ffffff"/>-- <!-- Base stand -->- <path d="M22 60 h22" stroke="#ffffff" stroke-width="4" stroke-linecap="round"/>- </g>-</svg>diff --git a/static/img/hero-shot.png b/static/img/hero-shot.pngdeleted file mode 100644index cbdb277b..00000000Binary files a/static/img/hero-shot.png and /dev/null differdiff --git a/static/img/icon-16x16.png b/static/img/icon-16x16.pngnew file mode 100644index 00000000..97e121bdBinary files /dev/null and b/static/img/icon-16x16.png differdiff --git a/static/img/icon-180x180.png b/static/img/icon-180x180.pngnew file mode 100644index 00000000..41c70df5Binary files /dev/null and b/static/img/icon-180x180.png differdiff --git a/static/img/icon-192x192.png b/static/img/icon-192x192.pngnew file mode 100644index 00000000..e8bf6d40Binary files /dev/null and b/static/img/icon-192x192.png differdiff --git a/static/img/icon-32x32.png b/static/img/icon-32x32.pngnew file mode 100644index 00000000..d4e311f4Binary files /dev/null and b/static/img/icon-32x32.png differdiff --git a/static/img/icon-512x512.png b/static/img/icon-512x512.pngnew file mode 100644index 00000000..a5008e81Binary files /dev/null and b/static/img/icon-512x512.png differdiff --git a/static/img/icon-maskable-512x512.png b/static/img/icon-maskable-512x512.pngnew file mode 100644index 00000000..bcb4586fBinary files /dev/null and b/static/img/icon-maskable-512x512.png differdiff --git a/static/img/intuitive-speaker-identification.png b/static/img/intuitive-speaker-identification.pngindex af32cbe5..b73df086 100644Binary files a/static/img/intuitive-speaker-identification.png and b/static/img/intuitive-speaker-identification.png differdiff --git a/static/img/light-mode.png b/static/img/light-mode.pngindex 33291dd1..2e4eea99 100644Binary files a/static/img/light-mode.png and b/static/img/light-mode.png differdiff --git a/static/img/main.png b/static/img/main.pngnew file mode 100644index 00000000..5b863a2aBinary files /dev/null and b/static/img/main.png differdiff --git a/static/img/manual-auto-speaker-identification.png b/static/img/manual-auto-speaker-identification.pngindex c45b5d88..82fff9d5 100644Binary files a/static/img/manual-auto-speaker-identification.png and b/static/img/manual-auto-speaker-identification.png differdiff --git a/static/img/multilingual-support.png b/static/img/multilingual-support.pngindex 482a6106..c89443d1 100644Binary files a/static/img/multilingual-support.png and b/static/img/multilingual-support.png differdiff --git a/static/img/rec1.png b/static/img/rec1.pngnew file mode 100644index 00000000..5631e63dBinary files /dev/null and b/static/img/rec1.png differdiff --git a/static/img/rec2.png b/static/img/rec2.pngnew file mode 100644index 00000000..ec77bc33Binary files /dev/null and b/static/img/rec2.png differdiff --git a/static/img/rec3.png b/static/img/rec3.pngnew file mode 100644index 00000000..621ad55aBinary files /dev/null and b/static/img/rec3.png differdiff --git a/static/img/reprocessing-transcript.png b/static/img/reprocessing-transcript.pngdeleted file mode 100644index beafb5a1..00000000Binary files a/static/img/reprocessing-transcript.png and /dev/null differdiff --git a/static/img/simple-transcription-view-2.png b/static/img/simple-transcription-view-2.pngdeleted file mode 100644index 21386fd2..00000000Binary files a/static/img/simple-transcription-view-2.png and /dev/null differdiff --git a/static/img/simple-transcription-view.png b/static/img/simple-transcription-view.pngindex 8f019be1..7e9acde7 100644Binary files a/static/img/simple-transcription-view.png and b/static/img/simple-transcription-view.png differdiff --git a/static/img/speaker-suggestions.png b/static/img/speaker-suggestions.pngindex ef46b180..7f50c3a1 100644Binary files a/static/img/speaker-suggestions.png and b/static/img/speaker-suggestions.png differdiff --git a/static/img/speakr1.png b/static/img/speakr1.pngdeleted file mode 100644index 79024894..00000000Binary files a/static/img/speakr1.png and /dev/null differdiff --git a/static/img/speakr2.png b/static/img/speakr2.pngdeleted file mode 100644index fce91794..00000000Binary files a/static/img/speakr2.png and /dev/null differdiff --git a/static/img/speakr3.png b/static/img/speakr3.pngdeleted file mode 100644index ec2dcbfc..00000000Binary files a/static/img/speakr3.png and /dev/null differdiff --git a/static/img/speakr4.png b/static/img/speakr4.pngdeleted file mode 100644index dae0d2b7..00000000Binary files a/static/img/speakr4.png and /dev/null differdiff --git a/static/img/transcription-bubble-view.png b/static/img/transcription-bubble-view.pngindex e33c7033..7d5efad3 100644Binary files a/static/img/transcription-bubble-view.png and b/static/img/transcription-bubble-view.png differdiff --git a/static/img/transcription-chat-bubble-view.png b/static/img/transcription-chat-bubble-view.pngindex 0b3c178a..16dbb6cf 100644Binary files a/static/img/transcription-chat-bubble-view.png and b/static/img/transcription-chat-bubble-view.png differdiff --git a/static/img/transcription-with-asr.png b/static/img/transcription-with-asr.pngdeleted file mode 100644index 612478de..00000000Binary files a/static/img/transcription-with-asr.png and /dev/null differdiff --git a/static/img/transcription-without-asr.png b/static/img/transcription-without-asr.pngdeleted file mode 100644index c7962b98..00000000Binary files a/static/img/transcription-without-asr.png and /dev/null differdiff --git a/static/js/app.js b/static/js/app.jsindex 816e42fa..ad0f2bf3 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -2,6 +2,18 @@ const { createApp, ref, reactive, computed, onMounted, watch, nextTick } = Vue// Wait for the DOM to be fully loaded before mounting the Vue appdocument.addEventListener('DOMContentLoaded', () => {+ // CSRF Protection for Fetch API+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');+ const originalFetch = window.fetch;+ window.fetch = function(url, options) {+ const newOptions = { ...options };+ newOptions.headers = {+ 'X-CSRFToken': csrfToken,+ ...newOptions.headers+ };+ return originalFetch(url, newOptions);+ };+// Register Service Workerif ('serviceWorker' in navigator) {window.addEventListener('load', () => {@@ -16,2645 +28,3390 @@ document.addEventListener('DOMContentLoaded', () => {}createApp({- setup() {- const currentView = ref('gallery');- const dragover = ref(false);- const recordings = ref([]);- const selectedRecording = ref(null);- const selectedTab = ref('summary'); // For Summary/Notes tabs- const selectedMobileTab = ref('transcript'); // For mobile 5-tab layout- const searchQuery = ref(''); // Search input for filtering recordings-- // --- Multi-Upload State ---- // Status: 'queued'|'uploading'|'processing'|'summarizing'|'completed'|'failed'- const uploadQueue = ref([]);- const currentlyProcessingFile = ref(null);- const processingProgress = ref(0);- const processingMessage = ref('');- const isProcessingActive = ref(false);- const pollInterval = ref(null);- const progressPopupMinimized = ref(false);- const progressPopupClosed = ref(false);-- const showEditModal = ref(false);- const showDeleteModal = ref(false);- const showReprocessModal = ref(false);- const showResetModal = ref(false);- const showSpeakerModal = ref(false);- const editingRecording = ref(null); // Holds a *copy* for the modal- const recordingToDelete = ref(null);- const recordingToReset = ref(null);- const reprocessType = ref(null); // 'transcription' or 'summary'- const reprocessRecording = ref(null);- const isAutoIdentifying = ref(false);- const asrReprocessOptions = reactive({- language: '',- min_speakers: null,- max_speakers: null- });- const speakerMap = ref({});- const regenerateSummaryAfterSpeakerUpdate = ref(true);- const highlightedSpeaker = ref(null);- const transcriptionViewMode = ref('simple'); // 'simple' or 'bubble'- const legendExpanded = ref(false); // Speaker legend expansion state- // const autoSaveTimeout = ref(null); // Autosave not implemented for modal- const isLoadingRecordings = ref(true);- const globalError = ref(null);- const maxFileSizeMB = ref(250); // Default, could fetch from config if needed- const isDarkMode = ref(false); // Dark mode state- const currentColorScheme = ref('blue'); // Current color scheme- const showColorSchemeModal = ref(false); // Color scheme modal state- const isSidebarCollapsed = ref(false); // Sidebar state- const isUserMenuOpen = ref(false); // User dropdown menu state- const isMobileMenuOpen = ref(false); // Mobile fly-in menu state- const isMobileUserMenuOpen = ref(false); // Mobile user icon dropdown menu state- const windowWidth = ref(window.innerWidth); // For reactive screen size- const useAsrEndpoint = ref(false);- const currentUserName = ref('');- const playerVolume = ref(1.0); // Default to full volume-- // --- Audio Recording State ---- const isRecording = ref(false);- const mediaRecorder = ref(null);- const audioChunks = ref([]);- const audioBlobURL = ref(null);- const recordingTime = ref(0);- const recordingInterval = ref(null);- const canRecordAudio = ref(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);-- // Inline editing state- const editingParticipants = ref(false);- const editingMeetingDate = ref(false); // For desktop- const editingMobileMeetingDate = ref(false); // For mobile metadata tab- const editingSummary = ref(false);- const editingNotes = ref(false);-- // --- Main Column Resize State ---- const leftMainColumn = ref(null);- const rightMainColumn = ref(null);- const mainColumnResizer = ref(null);- const mainContentColumns = ref(null);- const isResizingMainColumns = ref(false);- let initialMainColumnResizeX = 0;- let initialLeftMainColumnWidthPx = 0;- const MIN_MAIN_COLUMN_WIDTH_PERCENT = 30; // Min width for left column- const MAX_MAIN_COLUMN_WIDTH_PERCENT = 70; // Max width for left column (ensures right column gets at least 20%)- const ABSOLUTE_MIN_COLUMN_PX = 50; // Absolute minimum pixel width for either column-- // --- Vertical Resize State ---- const transcriptionSection = ref(null);- const tabSection = ref(null);- const verticalResizeHandle = ref(null);- const isResizingVertical = ref(false);- let initialVerticalResizeY = 0;- let initialTranscriptionHeightPx = 0;- let initialTabHeightPx = 0;-- // Resizable panels state- const transcriptionFlex = ref(2);- const tabsFlex = ref(1);-- // Track initialization status- const isDesktopLayoutInitialized = ref(false);-- // --- Computed Properties ---- // Filter recordings based on search query- const filteredRecordings = computed(() => {- if (!searchQuery.value.trim()) {- return recordings.value; // Return all recordings if no search query- }+ setup() {+ // --- Core State ---+ const currentView = ref('upload'); // 'upload' or 'recording'+ const dragover = ref(false);+ const recordings = ref([]);+ const selectedRecording = ref(null);+ const selectedTab = ref('summary'); // 'summary' or 'notes'+ const searchQuery = ref('');+ const isLoadingRecordings = ref(true);+ const globalError = ref(null);++ // --- Enhanced Search & Organization State ---+ const sortBy = ref('created_at'); // 'created_at' or 'meeting_date'++ // --- UI State ---+ const browser = ref('unknown');+ const isSidebarCollapsed = ref(false);+ const searchTipsExpanded = ref(false);+ const isUserMenuOpen = ref(false);+ const isDarkMode = ref(false);+ const currentColorScheme = ref('blue');+ const showColorSchemeModal = ref(false);+ const windowWidth = ref(window.innerWidth);+ const mobileTab = ref('transcript');+ const isMetadataExpanded = ref(false);++ // --- Upload State ---+ const uploadQueue = ref([]);+ const currentlyProcessingFile = ref(null);+ const processingProgress = ref(0);+ const processingMessage = ref('');+ const isProcessingActive = ref(false);+ const pollInterval = ref(null);+ const progressPopupMinimized = ref(false);+ const progressPopupClosed = ref(false);+ const maxFileSizeMB = ref(250); // Default value, will be updated from API++ // --- Audio Recording State ---+ const isRecording = ref(false);+ const mediaRecorder = ref(null);+ const audioChunks = ref([]);+ const audioBlobURL = ref(null);+ const recordingTime = ref(0);+ const recordingInterval = ref(null);+ const canRecordAudio = ref(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);+ const canRecordSystemAudio = ref(false);+ const systemAudioSupported = ref(false);+ const systemAudioError = ref('');+ const recordingNotes = ref('');+ const showSystemAudioHelp = ref(false);+ const audioContext = ref(null);+ const analyser = ref(null);+ const micAnalyser = ref(null);+ const systemAnalyser = ref(null);+ const visualizer = ref(null);+ const micVisualizer = ref(null);+ const systemVisualizer = ref(null);+ const animationFrameId = ref(null);+ const recordingMode = ref('microphone'); // 'microphone', 'system', or 'both'+ const activeStreams = ref([]); // Track active streams for cleanup++ // --- Modal State ---+ const showEditModal = ref(false);+ const showDeleteModal = ref(false);+ const showReprocessModal = ref(false);+ const showResetModal = ref(false);+ const showSpeakerModal = ref(false);+ const showShareModal = ref(false);+ const showSharesListModal = ref(false);+ const showTextEditorModal = ref(false);+ const showAsrEditorModal = ref(false);+ const editingRecording = ref(null);+ const editingTranscriptionContent = ref('');+ const editingSegments = ref([]);+ const availableSpeakers = ref([]);+ const recordingToShare = ref(null);+ const shareOptions = reactive({+ share_summary: true,+ share_notes: true,+ });+ const generatedShareLink = ref('');+ const userShares = ref([]);+ const isLoadingShares = ref(false);+ const recordingToDelete = ref(null);+ const recordingToReset = ref(null);+ const reprocessType = ref(null); // 'transcription' or 'summary'+ const reprocessRecording = ref(null);+ const isAutoIdentifying = ref(false);+ const asrReprocessOptions = reactive({+ language: '',+ min_speakers: null,+ max_speakers: null+ });+ const speakerMap = ref({});+ const regenerateSummaryAfterSpeakerUpdate = ref(true);+ const speakerSuggestions = ref({});+ const loadingSuggestions = ref({});++ // --- Inline Editing State ---+ const editingParticipants = ref(false);+ const editingMeetingDate = ref(false);+ const editingSummary = ref(false);+ const editingNotes = ref(false);- const query = searchQuery.value.toLowerCase().trim();- return recordings.value.filter(recording => {- // Search in title, participants, and transcription- return (- (recording.title && recording.title.toLowerCase().includes(query)) ||- (recording.participants && recording.participants.toLowerCase().includes(query)) ||- (recording.transcription && recording.transcription.toLowerCase().includes(query))- );+ // --- Markdown Editor State ---+ const notesMarkdownEditor = ref(null);+ const markdownEditorInstance = ref(null);+ const summaryMarkdownEditor = ref(null);+ const summaryMarkdownEditorInstance = ref(null);+ const recordingNotesEditor = ref(null);+ const recordingMarkdownEditorInstance = ref(null);++ // --- Transcription State ---+ const transcriptionViewMode = ref('simple'); // 'simple' or 'bubble'+ const legendExpanded = ref(false);+ const highlightedSpeaker = ref(null);++ // --- Chat State ---+ const showChat = ref(false);+ const chatMessages = ref([]);+ const chatInput = ref('');+ const isChatLoading = ref(false);+ const chatMessagesRef = ref(null);++ // --- Audio Player State ---+ const playerVolume = ref(1.0);++ // --- Column Resizing State ---+ const leftColumnWidth = ref(60); // 60% for left column (transcript)+ const rightColumnWidth = ref(40); // 40% for right column (summary/chat)+ const isResizing = ref(false);++ // --- App Configuration ---+ const useAsrEndpoint = ref(false);+ const currentUserName = ref('');++ // --- Computed Properties ---+ const isMobileScreen = computed(() => {+ return windowWidth.value < 1024;});- });-- // Group recordings by date- const groupedRecordings = computed(() => {- const sortedRecordings = [...filteredRecordings.value].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));- // Grouping logic- 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 currentDayOfWeek = now.getDay();- const daysToSubtract = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;- const weekStart = new Date(todayStart);- weekStart.setDate(todayStart.getDate() - daysToSubtract);-- sortedRecordings.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);++ const filteredRecordings = computed(() => {+ if (!searchQuery.value.trim()) {+ return recordings.value;+ }++ const query = searchQuery.value.toLowerCase().trim();++ // Check for date search syntax (date:YYYY-MM-DD or date:today, date:yesterday, etc.)+ const dateMatch = query.match(/date:(\S+)/);+ if (dateMatch) {+ const dateQuery = dateMatch[1];+ return recordings.value.filter(recording => {+ const recordingDate = getDateForSorting(recording);+ if (!recordingDate) return false;++ if (dateQuery === 'today') {+ return isToday(recordingDate);+ } else if (dateQuery === 'yesterday') {+ return isYesterday(recordingDate);+ } else if (dateQuery === 'thisweek') {+ return isThisWeek(recordingDate);+ } else if (dateQuery === 'lastweek') {+ return isLastWeek(recordingDate);+ } else if (dateQuery === 'thismonth') {+ return isThisMonth(recordingDate);+ } else if (dateQuery === 'lastmonth') {+ return isLastMonth(recordingDate);+ } else if (/^\d{4}-\d{2}-\d{2}$/.test(dateQuery)) {+ // Exact date match+ const searchDate = new Date(dateQuery + 'T00:00:00');+ return isSameDay(recordingDate, searchDate);+ } else if (/^\d{4}-\d{2}$/.test(dateQuery)) {+ // Month match (YYYY-MM)+ const [year, month] = dateQuery.split('-');+ return recordingDate.getFullYear() === parseInt(year) &&+ recordingDate.getMonth() === parseInt(month) - 1;+ } else if (/^\d{4}$/.test(dateQuery)) {+ // Year match+ return recordingDate.getFullYear() === parseInt(dateQuery);+ }+ return false;+ });+ }++ // Regular text search+ return recordings.value.filter(recording => {+ return (+ (recording.title && recording.title.toLowerCase().includes(query)) ||+ (recording.participants && recording.participants.toLowerCase().includes(query)) ||+ (recording.transcription && recording.transcription.toLowerCase().includes(query)) ||+ (recording.notes && recording.notes.toLowerCase().includes(query))+ );+ });+ });++ const highlightedTranscript = computed(() => {+ if (!selectedRecording.value?.transcription) return '';+ let html = selectedRecording.value.transcription;+ // Escape HTML to prevent injection, but keep it minimal+ html = html.replace(/</g, '<').replace(/>/g, '>');++ // 1. Replace newlines with <br> tags for proper line breaks in HTML+ html = html.replace(/\n/g, '<br>');++ // 2. Get speaker colors from the speakerMap if available+ const speakerColors = {};+ if (speakerMap.value) {+ Object.keys(speakerMap.value).forEach((speaker, index) => {+ speakerColors[speaker] = speakerMap.value[speaker].color || `speaker-color-${(index % 8) + 1}`;+ });+ }++ // 3. Wrap each speaker tag in a span for styling and interaction with colors+ html = html.replace(/\[([^\]]+)\]/g, (match, speakerId) => {+ const isHighlighted = speakerId === highlightedSpeaker.value;+ const colorClass = speakerColors[speakerId] || '';+ // Use a more specific and stylish class structure with color+ return `<span class="speaker-tag ${colorClass} ${isHighlighted ? 'speaker-highlight' : ''}" data-speaker-id="${speakerId}">${match}</span>`;+ });++ return html;});- 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);- });- const totalInQueue = computed(() => uploadQueue.value.length);- const completedInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'completed' || item.status === 'failed').length);- const queuedFiles = computed(() => uploadQueue.value.filter(item => item.status === 'queued'));- // Filter finished: includes completed and failed- const finishedFilesInQueue = computed(() => uploadQueue.value.filter(item => ['completed', 'failed'].includes(item.status)));+ const activeRecordingMetadata = computed(() => {+ if (!selectedRecording.value) return [];++ const recording = selectedRecording.value;+ const metadata = [];- const isMobileScreen = computed(() => {- // Align with Tailwind's 'lg' breakpoint for sidebar visibility and mobile menu toggling- return windowWidth.value < 1024;- });+ if (recording.created_at) {+ metadata.push({+ icon: 'fas fa-history',+ text: formatDisplayDate(recording.created_at)+ });+ }- const identifiedSpeakers = computed(() => {- // Ensure we have a valid recording and transcription- if (!selectedRecording.value?.transcription) {- return [];- }-- const transcription = selectedRecording.value.transcription;- let transcriptionData;+ if (recording.file_size) {+ metadata.push({+ icon: 'fas fa-file-audio',+ text: formatFileSize(recording.file_size)+ });+ }- try {- transcriptionData = JSON.parse(transcription);- } catch (e) {- transcriptionData = null;- }+ if (recording.duration) {+ metadata.push({+ icon: 'fas fa-clock',+ text: formatDuration(recording.duration)+ });+ }- // Updated to handle new simplified JSON format (array of segments)- if (transcriptionData && Array.isArray(transcriptionData)) {- // JSON format - extract speakers from segments- const speakers = new Set();- transcriptionData.forEach(segment => {- if (segment.speaker && String(segment.speaker).trim()) {- speakers.add(segment.speaker);- }- });- return Array.from(speakers).sort(); // Sort for consistent color mapping- } else if (typeof transcription === 'string') {- // Plain text format - use regex to find speaker patterns- const speakerRegex = /\[([^\]]+)\]:/g;- const speakers = new Set();- let match;- while ((match = speakerRegex.exec(transcription)) !== null) {- const speaker = match[1].trim();- if (speaker) {- speakers.add(speaker);- }+ if (recording.original_filename) {+ const maxLength = 30;+ const truncated = recording.original_filename.length > maxLength+ ? recording.original_filename.substring(0, maxLength) + '...'+ : recording.original_filename;+ metadata.push({+ icon: 'fas fa-file',+ text: truncated,+ fullText: recording.original_filename+ });}- return Array.from(speakers).sort();- }- return [];- });++ return metadata;+ });- const hasSpeakerNames = computed(() => {- // Check if any speaker has a non-empty name- return Object.values(speakerMap.value).some(speakerData =>- speakerData.name && speakerData.name.trim() !== ''- );- });+ const groupedRecordings = computed(() => {+ // Sort recordings based on the selected sort criteria+ const sortedRecordings = [...filteredRecordings.value].sort((a, b) => {+ const dateA = getDateForSorting(a);+ const dateB = getDateForSorting(b);++ // Handle null dates (put them at the end)+ if (!dateA && !dateB) return 0;+ if (!dateA) return 1;+ if (!dateB) return -1;++ return dateB - dateA; // Most recent first+ });- const processedTranscription = computed(() => {- if (!selectedRecording.value?.transcription) {- return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };- }+ const groups = {+ today: [],+ yesterday: [],+ thisWeek: [],+ lastWeek: [],+ thisMonth: [],+ lastMonth: [],+ older: []+ };- const transcription = selectedRecording.value.transcription;- let transcriptionData;+ sortedRecordings.forEach(recording => {+ const date = getDateForSorting(recording);+ if (!date) {+ groups.older.push(recording);+ return;+ }- try {- transcriptionData = JSON.parse(transcription);- } catch (e) {- transcriptionData = null;- }+ if (isToday(date)) {+ groups.today.push(recording);+ } else if (isYesterday(date)) {+ groups.yesterday.push(recording);+ } else if (isThisWeek(date)) {+ groups.thisWeek.push(recording);+ } else if (isLastWeek(date)) {+ groups.lastWeek.push(recording);+ } else if (isThisMonth(date)) {+ groups.thisMonth.push(recording);+ } else if (isLastMonth(date)) {+ groups.lastMonth.push(recording);+ } else {+ groups.older.push(recording);+ }+ });- // Updated to handle new simplified JSON format (array of segments)- if (transcriptionData && Array.isArray(transcriptionData)) {- // If no segments have a speaker, it wasn't diarized. Treat as plain text.- const wasDiarized = transcriptionData.some(segment => segment.speaker);+ return [+ { title: 'Today', items: groups.today },+ { title: 'Yesterday', items: groups.yesterday },+ { title: 'This Week', items: groups.thisWeek },+ { title: 'Last Week', items: groups.lastWeek },+ { title: 'This Month', items: groups.thisMonth },+ { title: 'Last Month', items: groups.lastMonth },+ { title: 'Older', items: groups.older }+ ].filter(g => g.items.length > 0);+ });- if (!wasDiarized) {- const segments = transcriptionData.map(segment => ({- sentence: segment.sentence,- startTime: segment.start_time,- }));- return {- hasDialogue: false,- isJson: true,- content: segments.map(s => s.sentence).join('\n'),- simpleSegments: segments,- speakers: [],- bubbleRows: []- };+ const totalInQueue = computed(() => uploadQueue.value.length);+ const completedInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'completed' || item.status === 'failed').length);+ const finishedFilesInQueue = computed(() => uploadQueue.value.filter(item => ['completed', 'failed'].includes(item.status)));++ const identifiedSpeakers = computed(() => {+ // Ensure we have a valid recording and transcription+ if (!selectedRecording.value?.transcription) {+ return [];}- const speakerColors = {};- const speakerList = identifiedSpeakers.value; // Use computed property which is already sorted- speakerList.forEach((speaker, index) => {- speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;- });-- // Only use speakerMap if it contains speakers that actually exist in this recording- const currentRecordingSpeakers = new Set(speakerList);- const relevantSpeakerMap = {};- for (const [speakerId, speakerData] of Object.entries(speakerMap.value)) {- if (currentRecordingSpeakers.has(speakerId)) {- relevantSpeakerMap[speakerId] = speakerData;+ const transcription = selectedRecording.value.transcription;+ let transcriptionData;++ try {+ transcriptionData = JSON.parse(transcription);+ } catch (e) {+ transcriptionData = null;+ }++ // Updated to handle new simplified JSON format (array of segments)+ if (transcriptionData && Array.isArray(transcriptionData)) {+ // JSON format - extract speakers from segments+ const speakers = new Set();+ transcriptionData.forEach(segment => {+ if (segment.speaker && String(segment.speaker).trim()) {+ speakers.add(segment.speaker);+ }+ });+ return Array.from(speakers).sort(); // Sort for consistent color mapping+ } else if (typeof transcription === 'string') {+ // Plain text format - use regex to find speaker patterns+ const speakerRegex = /\[([^\]]+)\]:/g;+ const speakers = new Set();+ let match;+ while ((match = speakerRegex.exec(transcription)) !== null) {+ const speaker = match[1].trim();+ if (speaker) {+ speakers.add(speaker);+ }}+ return Array.from(speakers).sort();}+ return [];+ });++ const hasSpeakerNames = computed(() => {+ // Check if any speaker has a non-empty name+ return Object.values(speakerMap.value).some(speakerData =>+ speakerData.name && speakerData.name.trim() !== ''+ );+ });- const simpleSegments = transcriptionData.map(segment => ({- speakerId: segment.speaker,- speaker: (relevantSpeakerMap[segment.speaker]?.name || segment.speaker),- sentence: segment.sentence,- startTime: segment.start_time,- endTime: segment.end_time,- color: speakerColors[segment.speaker] || 'speaker-color-1'- }));-- // Create a unique list of speakers *after* names have been mapped.- const uniqueSpeakers = [...new Map(simpleSegments.map(item => [item.speaker, item])).values()];-- const processedSimpleSegments = [];- let lastSpeaker = null;- simpleSegments.forEach(segment => {- processedSimpleSegments.push({- ...segment,- showSpeaker: segment.speaker !== lastSpeaker- });- lastSpeaker = segment.speaker;- });+ const processedTranscription = computed(() => {+ if (!selectedRecording.value?.transcription) {+ return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };+ }- const bubbleRows = [];- let lastBubbleSpeaker = null;- simpleSegments.forEach(segment => {- if (bubbleRows.length === 0 || segment.speaker !== lastBubbleSpeaker) {- bubbleRows.push({- speaker: segment.speaker,- color: segment.color,- isMe: segment.speaker && (typeof segment.speaker === 'string') && segment.speaker.toLowerCase().includes('me'),- bubbles: []- });- lastBubbleSpeaker = segment.speaker;+ const transcription = selectedRecording.value.transcription;+ let transcriptionData;++ try {+ transcriptionData = JSON.parse(transcription);+ } catch (e) {+ transcriptionData = null;+ }++ // Handle new simplified JSON format (array of segments)+ if (transcriptionData && Array.isArray(transcriptionData)) {+ const wasDiarized = transcriptionData.some(segment => segment.speaker);++ if (!wasDiarized) {+ const segments = transcriptionData.map(segment => ({+ sentence: segment.sentence,+ startTime: segment.start_time,+ }));+ return {+ hasDialogue: false,+ isJson: true,+ content: segments.map(s => s.sentence).join('\n'),+ simpleSegments: segments,+ speakers: [],+ bubbleRows: []+ };}- bubbleRows[bubbleRows.length - 1].bubbles.push({- sentence: segment.sentence,- startTime: segment.startTime,- color: segment.color++ // Extract unique speakers+ const speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];+ const speakerColors = {};+ speakers.forEach((speaker, index) => {+ speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;});- });- return {- hasDialogue: true,- isJson: true,- segments: simpleSegments,- simpleSegments: processedSimpleSegments,- bubbleRows: bubbleRows,- speakers: uniqueSpeakers.map(speaker => ({- name: speaker.speaker,- color: speaker.color- }))- };+ const simpleSegments = transcriptionData.map(segment => ({+ speakerId: segment.speaker,+ speaker: segment.speaker,+ sentence: segment.sentence,+ startTime: segment.start_time || segment.startTime,+ endTime: segment.end_time || segment.endTime,+ color: speakerColors[segment.speaker] || 'speaker-color-1'+ }));++ const processedSimpleSegments = [];+ let lastSpeaker = null;+ simpleSegments.forEach(segment => {+ processedSimpleSegments.push({+ ...segment,+ showSpeaker: segment.speaker !== lastSpeaker+ });+ lastSpeaker = segment.speaker;+ });- } else {- // Fallback for plain text transcription- const speakerRegex = /\[([^\]]+)\]:\s*/g;- const hasDialogue = speakerRegex.test(transcription);+ const bubbleRows = [];+ let lastBubbleSpeaker = null;+ simpleSegments.forEach(segment => {+ if (bubbleRows.length === 0 || segment.speaker !== lastBubbleSpeaker) {+ bubbleRows.push({+ speaker: segment.speaker,+ color: segment.color,+ isMe: segment.speaker && (typeof segment.speaker === 'string') && segment.speaker.toLowerCase().includes('me'),+ bubbles: []+ });+ lastBubbleSpeaker = segment.speaker;+ }+ bubbleRows[bubbleRows.length - 1].bubbles.push({+ sentence: segment.sentence,+ startTime: segment.startTime || segment.start_time,+ color: segment.color+ });+ });- if (!hasDialogue) {return {- hasDialogue: false,- isJson: false,- content: transcription,- speakers: [],- simpleSegments: [],- bubbleRows: []+ hasDialogue: true,+ isJson: true,+ segments: simpleSegments,+ simpleSegments: processedSimpleSegments,+ bubbleRows: bubbleRows,+ speakers: speakers.map(speaker => ({+ name: speaker,+ color: speakerColors[speaker]+ }))};- }- speakerRegex.lastIndex = 0;- const speakers = new Set();- let match;- while ((match = speakerRegex.exec(transcription)) !== null) {- speakers.add(match[1]);- }+ } else {+ // Fallback for plain text transcription+ const speakerRegex = /\[([^\]]+)\]:\s*/g;+ const hasDialogue = speakerRegex.test(transcription);++ if (!hasDialogue) {+ return {+ hasDialogue: false,+ isJson: false,+ content: transcription,+ speakers: [],+ simpleSegments: [],+ bubbleRows: []+ };+ }- const speakerList = Array.from(speakers);- const speakerColors = {};- speakerList.forEach((speaker, index) => {- speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;- });+ speakerRegex.lastIndex = 0;+ const speakers = new Set();+ let match;+ while ((match = speakerRegex.exec(transcription)) !== null) {+ speakers.add(match[1]);+ }- const segments = [];- const lines = transcription.split('\n');- let currentSpeaker = null;- let currentText = '';+ const speakerList = Array.from(speakers);+ const speakerColors = {};+ speakerList.forEach((speaker, index) => {+ speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;+ });- for (const line of lines) {- const speakerMatch = line.match(/^\[([^\]]+)\]:\s*(.*)$/);- if (speakerMatch) {- if (currentSpeaker && currentText.trim()) {+ const segments = [];+ const lines = transcription.split('\n');+ let currentSpeaker = null;+ let currentText = '';++ for (const line of lines) {+ const speakerMatch = line.match(/^\[([^\]]+)\]:\s*(.*)$/);+ if (speakerMatch) {+ if (currentSpeaker && currentText.trim()) {+ segments.push({+ speaker: currentSpeaker,+ sentence: currentText.trim(),+ color: speakerColors[currentSpeaker] || 'speaker-color-1'+ });+ }+ currentSpeaker = speakerMatch[1];+ currentText = speakerMatch[2];+ } else if (currentSpeaker && line.trim()) {+ currentText += ' ' + line.trim();+ } else if (!currentSpeaker && line.trim()) {segments.push({- speaker: currentSpeaker,- sentence: currentText.trim(),- color: speakerColors[currentSpeaker] || 'speaker-color-1'+ speaker: null,+ sentence: line.trim(),+ color: 'speaker-color-1'});}- currentSpeaker = speakerMatch[1];- currentText = speakerMatch[2];- } else if (currentSpeaker && line.trim()) {- currentText += ' ' + line.trim();- } else if (!currentSpeaker && line.trim()) {+ }++ if (currentSpeaker && currentText.trim()) {segments.push({- speaker: null,- sentence: line.trim(),- color: 'speaker-color-1'+ speaker: currentSpeaker,+ sentence: currentText.trim(),+ color: speakerColors[currentSpeaker] || 'speaker-color-1'});}- }-- if (currentSpeaker && currentText.trim()) {- segments.push({- speaker: currentSpeaker,- sentence: currentText.trim(),- color: speakerColors[currentSpeaker] || 'speaker-color-1'- });- }- const simpleSegments = [];- let lastSpeaker = null;- segments.forEach(segment => {- simpleSegments.push({- ...segment,- showSpeaker: segment.speaker !== lastSpeaker,- // Ensure sentence property exists for plain text- sentence: segment.sentence || segment.text+ const simpleSegments = [];+ let lastSpeaker = null;+ segments.forEach(segment => {+ simpleSegments.push({+ ...segment,+ showSpeaker: segment.speaker !== lastSpeaker,+ sentence: segment.sentence || segment.text+ });+ lastSpeaker = segment.speaker;});- lastSpeaker = segment.speaker;- });- const bubbleRows = [];- let currentRow = null;- segments.forEach(segment => {- if (!currentRow || currentRow.speaker !== segment.speaker) {- if (currentRow) bubbleRows.push(currentRow);- currentRow = {- speaker: segment.speaker,- color: segment.color,- bubbles: [],- isMe: segment.speaker && segment.speaker.toLowerCase().includes('me')- };- }- currentRow.bubbles.push({- sentence: segment.sentence,- color: segment.color+ const bubbleRows = [];+ let currentRow = null;+ segments.forEach(segment => {+ if (!currentRow || currentRow.speaker !== segment.speaker) {+ if (currentRow) bubbleRows.push(currentRow);+ currentRow = {+ speaker: segment.speaker,+ color: segment.color,+ bubbles: [],+ isMe: segment.speaker && segment.speaker.toLowerCase().includes('me')+ };+ }+ currentRow.bubbles.push({+ sentence: segment.sentence,+ color: segment.color+ });});- });- if (currentRow) bubbleRows.push(currentRow);-- return {- hasDialogue: true,- isJson: false,- segments: segments,- simpleSegments: simpleSegments,- bubbleRows: bubbleRows,- speakers: speakerList.map(speaker => ({- name: speaker,- color: speakerColors[speaker] || 'speaker-color-1'- }))- };- }- });+ if (currentRow) bubbleRows.push(currentRow);- const highlightedTranscript = computed(() => {- if (!selectedRecording.value?.transcription) return '';- let html = selectedRecording.value.transcription;- // Escape HTML to prevent injection, but keep it minimal- html = html.replace(/</g, '<').replace(/>/g, '>');-- // 1. Replace newlines with <br> tags for proper line breaks in HTML- html = html.replace(/\n/g, '<br>');-- // 2. Get speaker colors from the speakerMap if available- const speakerColors = {};- if (speakerMap.value) {- Object.keys(speakerMap.value).forEach((speaker, index) => {- speakerColors[speaker] = speakerMap.value[speaker].color || `speaker-color-${(index % 8) + 1}`;- });- }-- // 3. Wrap each speaker tag in a span for styling and interaction with colors- html = html.replace(/\[([^\]]+)\]/g, (match, speakerId) => {- const isHighlighted = speakerId === highlightedSpeaker.value;- const colorClass = speakerColors[speakerId] || '';- // Use a more specific and stylish class structure with color- return `<span class="speaker-tag ${colorClass} ${isHighlighted ? 'speaker-highlight' : ''}" data-speaker-id="${speakerId}">${match}</span>`;+ return {+ hasDialogue: true,+ isJson: false,+ segments: segments,+ simpleSegments: simpleSegments,+ bubbleRows: bubbleRows,+ speakers: speakerList.map(speaker => ({+ name: speaker,+ color: speakerColors[speaker] || 'speaker-color-1'+ }))+ };+ }});-- return html;- });+ // --- Color Scheme Management ---+ const colorSchemes = {+ light: [+ { id: 'blue', name: 'Ocean Blue', description: 'Classic blue theme with professional appeal', class: '' },+ { id: 'emerald', name: 'Forest Emerald', description: 'Fresh green theme for a natural feel', class: 'theme-light-emerald' },+ { id: 'purple', name: 'Royal Purple', description: 'Elegant purple theme with sophistication', class: 'theme-light-purple' },+ { id: 'rose', name: 'Sunset Rose', description: 'Warm pink theme with gentle energy', class: 'theme-light-rose' },+ { id: 'amber', name: 'Golden Amber', description: 'Warm yellow theme for brightness', class: 'theme-light-amber' },+ { id: 'teal', name: 'Ocean Teal', description: 'Cool teal theme for tranquility', class: 'theme-light-teal' }+ ],+ dark: [+ { id: 'blue', name: 'Midnight Blue', description: 'Deep blue theme for focused work', class: '' },+ { id: 'emerald', name: 'Dark Forest', description: 'Rich green theme for comfortable viewing', class: 'theme-dark-emerald' },+ { id: 'purple', name: 'Deep Purple', description: 'Mysterious purple theme for creativity', class: 'theme-dark-purple' },+ { id: 'rose', name: 'Dark Rose', description: 'Muted pink theme with subtle warmth', class: 'theme-dark-rose' },+ { id: 'amber', name: 'Dark Amber', description: 'Warm brown theme for cozy sessions', class: 'theme-dark-amber' },+ { id: 'teal', name: 'Deep Teal', description: 'Dark teal theme for calm focus', class: 'theme-dark-teal' }+ ]+ };- // --- Methods ---- const setGlobalError = (message, duration = 7000) => {- globalError.value = message;- if (duration > 0) {- setTimeout(() => { if (globalError.value === message) globalError.value = null; }, duration);- }- };+ // --- Utility Methods ---+ const setGlobalError = (message, duration = 7000) => {+ globalError.value = message;+ if (duration > 0) {+ setTimeout(() => { if (globalError.value === message) globalError.value = null; }, duration);+ }+ };- const formatFileSize = (bytes) => {- if (bytes == null || bytes === 0) return '0 Bytes';- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];- if (bytes < 0) bytes = 0;- const i = bytes === 0 ? 0 : Math.max(0, Math.floor(Math.log(bytes) / Math.log(k)));- const size = i === 0 ? bytes : parseFloat((bytes / Math.pow(k, i)).toFixed(2));- return size + ' ' + sizes[i];- };+ const formatFileSize = (bytes) => {+ if (bytes == null || bytes === 0) return '0 Bytes';+ const k = 1024;+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];+ if (bytes < 0) bytes = 0;+ const i = bytes === 0 ? 0 : Math.max(0, Math.floor(Math.log(bytes) / Math.log(k)));+ const size = i === 0 ? bytes : parseFloat((bytes / Math.pow(k, i)).toFixed(2));+ return size + ' ' + sizes[i];+ };- const formatDuration = (totalSeconds) => {- if (totalSeconds == null || totalSeconds < 0) return 'N/A';+ const formatDisplayDate = (dateString) => {+ if (!dateString) return '';+ try {+ // Try to parse the date string directly first (it might already be formatted)+ let date = new Date(dateString);++ // If that fails or results in invalid date, try different approaches+ if (isNaN(date.getTime())) {+ // Try appending time if it looks like a date-only string (YYYY-MM-DD format)+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {+ date = new Date(dateString + 'T00:00:00');+ } else {+ // If it's already a formatted string, just return it+ return dateString;+ }+ }++ // If we still have an invalid date, return the original string+ if (isNaN(date.getTime())) {+ return dateString;+ }++ return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });+ } catch (e) {+ console.error("Error formatting date:", e);+ return dateString;+ }+ };- if (totalSeconds < 1) {- return `${totalSeconds.toFixed(2)} seconds`;- }-- totalSeconds = Math.round(totalSeconds);+ const formatStatus = (status) => {+ if (!status || status === 'COMPLETED') return '';+ return status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();+ };- if (totalSeconds < 60) {- return `${totalSeconds} sec`;- }+ const getStatusClass = (status) => {+ switch(status) {+ case 'PENDING': return 'status-pending';+ case 'PROCESSING': return 'status-processing';+ case 'SUMMARIZING': return 'status-summarizing';+ case 'COMPLETED': return '';+ case 'FAILED': return 'status-failed';+ default: return 'status-pending';+ }+ };- const hours = Math.floor(totalSeconds / 3600);- const minutes = Math.floor((totalSeconds % 3600) / 60);- const seconds = totalSeconds % 60;+ const formatTime = (seconds) => {+ const minutes = Math.floor(seconds / 60);+ const secs = seconds % 60;+ return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;+ };- let parts = [];- if (hours > 0) {- parts.push(`${hours} hr`);- }- if (minutes > 0) {- parts.push(`${minutes} min`);- }- // Only show seconds if duration is less than an hour- if (hours === 0 && seconds > 0) {- parts.push(`${seconds} sec`);- }+ const formatDuration = (totalSeconds) => {+ if (totalSeconds == null || totalSeconds < 0) return 'N/A';++ if (totalSeconds < 1) {+ return `${totalSeconds.toFixed(2)} seconds`;+ }++ totalSeconds = Math.round(totalSeconds);++ if (totalSeconds < 60) {+ return `${totalSeconds} sec`;+ }++ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ let parts = [];+ if (hours > 0) {+ parts.push(`${hours} hr`);+ }+ if (minutes > 0) {+ parts.push(`${minutes} min`);+ }+ // Only show seconds if duration is less than an hour+ if (hours === 0 && seconds > 0) {+ parts.push(`${seconds} sec`);+ }++ return parts.join(' ');+ };- return parts.join(' ');- };+ // --- Enhanced Date Utility Functions ---+ const getDateForSorting = (recording) => {+ const dateStr = sortBy.value === 'meeting_date' ? recording.meeting_date : recording.created_at;+ if (!dateStr) return null;+ return new Date(dateStr);+ };- // --- Dark Mode ---- const toggleDarkMode = () => {- isDarkMode.value = !isDarkMode.value;- if (isDarkMode.value) {- document.documentElement.classList.add('dark');- localStorage.setItem('darkMode', 'true');- } else {- document.documentElement.classList.remove('dark');- localStorage.setItem('darkMode', 'false');- }- };+ const isToday = (date) => {+ const today = new Date();+ return isSameDay(date, today);+ };- const initializeDarkMode = () => {- const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;- const savedMode = localStorage.getItem('darkMode');- if (savedMode === 'true' || (savedMode === null && prefersDark)) {- isDarkMode.value = true;- document.documentElement.classList.add('dark');- } else {- isDarkMode.value = false;- document.documentElement.classList.remove('dark');- }- };+ const isYesterday = (date) => {+ const yesterday = new Date();+ yesterday.setDate(yesterday.getDate() - 1);+ return isSameDay(date, yesterday);+ };- // --- Color Scheme Management ---- const colorSchemes = {- light: [- { id: 'blue', name: 'Ocean Blue', description: 'Classic blue theme with professional appeal', class: '' },- { id: 'emerald', name: 'Forest Emerald', description: 'Fresh green theme for a natural feel', class: 'theme-light-emerald' },- { id: 'purple', name: 'Royal Purple', description: 'Elegant purple theme with sophistication', class: 'theme-light-purple' },- { id: 'rose', name: 'Sunset Rose', description: 'Warm pink theme with gentle energy', class: 'theme-light-rose' },- { id: 'amber', name: 'Golden Amber', description: 'Warm yellow theme for brightness', class: 'theme-light-amber' },- { id: 'teal', name: 'Ocean Teal', description: 'Cool teal theme for tranquility', class: 'theme-light-teal' }- ],- dark: [- { id: 'blue', name: 'Midnight Blue', description: 'Deep blue theme for focused work', class: '' },- { id: 'emerald', name: 'Dark Forest', description: 'Rich green theme for comfortable viewing', class: 'theme-dark-emerald' },- { id: 'purple', name: 'Deep Purple', description: 'Mysterious purple theme for creativity', class: 'theme-dark-purple' },- { id: 'rose', name: 'Dark Rose', description: 'Muted pink theme with subtle warmth', class: 'theme-dark-rose' },- { id: 'amber', name: 'Dark Amber', description: 'Warm brown theme for cozy sessions', class: 'theme-dark-amber' },- { id: 'teal', name: 'Deep Teal', description: 'Dark teal theme for calm focus', class: 'theme-dark-teal' }- ]- };+ const isThisWeek = (date) => {+ const now = new Date();+ const startOfWeek = new Date(now);+ const day = now.getDay();+ const diff = now.getDate() - day + (day === 0 ? -6 : 1); // Monday as start of week+ startOfWeek.setDate(diff);+ startOfWeek.setHours(0, 0, 0, 0);++ const endOfWeek = new Date(startOfWeek);+ endOfWeek.setDate(startOfWeek.getDate() + 6);+ endOfWeek.setHours(23, 59, 59, 999);++ return date >= startOfWeek && date <= endOfWeek;+ };- const applyColorScheme = (schemeId, mode = null) => {- const targetMode = mode || (isDarkMode.value ? 'dark' : 'light');- const scheme = colorSchemes[targetMode].find(s => s.id === schemeId);-- if (!scheme) {- console.warn(`Color scheme '${schemeId}' not found for mode '${targetMode}'`);- return;- }+ const isLastWeek = (date) => {+ const now = new Date();+ const startOfLastWeek = new Date(now);+ const day = now.getDay();+ const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7; // Previous Monday+ startOfLastWeek.setDate(diff);+ startOfLastWeek.setHours(0, 0, 0, 0);++ const endOfLastWeek = new Date(startOfLastWeek);+ endOfLastWeek.setDate(startOfLastWeek.getDate() + 6);+ endOfLastWeek.setHours(23, 59, 59, 999);++ return date >= startOfLastWeek && date <= endOfLastWeek;+ };- // Remove all existing theme classes- const allThemeClasses = [- ...colorSchemes.light.map(s => s.class),- ...colorSchemes.dark.map(s => s.class)- ].filter(c => c !== '');+ const isThisMonth = (date) => {+ const now = new Date();+ return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth();+ };- document.documentElement.classList.remove(...allThemeClasses);+ const isLastMonth = (date) => {+ const now = new Date();+ const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);+ return date.getFullYear() === lastMonth.getFullYear() && date.getMonth() === lastMonth.getMonth();+ };- // Apply new theme class if it's not the default- if (scheme.class) {- document.documentElement.classList.add(scheme.class);- }+ const isSameDay = (date1, date2) => {+ return date1.getFullYear() === date2.getFullYear() &&+ date1.getMonth() === date2.getMonth() &&+ date1.getDate() === date2.getDate();+ };- // Update current scheme- currentColorScheme.value = schemeId;-- // Save to localStorage- localStorage.setItem('colorScheme', schemeId);+ const reprocessTranscription = (recordingId) => {+ const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;+ confirmReprocess('transcription', recording);+ };- console.log(`Applied color scheme: ${scheme.name} (${targetMode} mode)`);- };+ const reprocessSummary = (recordingId) => {+ const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;+ confirmReprocess('summary', recording);+ };- const initializeColorScheme = () => {- const savedScheme = localStorage.getItem('colorScheme') || 'blue';- currentColorScheme.value = savedScheme;- applyColorScheme(savedScheme);- };+ const resetRecordingStatus = async (recordingId) => {+ const recording = recordings.value.find(r => r.id === recordingId);+ if (!recording) return;- const openColorSchemeModal = () => {- showColorSchemeModal.value = true;- };+ try {+ const response = await fetch(`/recording/${recording.id}/reset_status`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ });+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Failed to reset status');+ }+ const index = recordings.value.findIndex(r => r.id === recording.id);+ if (index !== -1) {+ recordings.value[index] = data.recording;+ }+ if (selectedRecording.value?.id === recording.id) {+ selectedRecording.value = data.recording;+ }+ showToast('Recording status has been reset.', 'fa-check-circle');+ } catch (error) {+ setGlobalError(`Failed to reset status: ${error.message}`);+ }+ };- const closeColorSchemeModal = () => {- showColorSchemeModal.value = false;- };+ const confirmReprocess = (type, recording) => {+ reprocessType.value = type;+ reprocessRecording.value = recording;+ showReprocessModal.value = true;+ };- const selectColorScheme = (schemeId) => {- applyColorScheme(schemeId);- showToast(`Applied ${colorSchemes[isDarkMode.value ? 'dark' : 'light'].find(s => s.id === schemeId)?.name} theme`, 'fa-palette');- };+ const openTranscriptionEditor = () => {+ if (processedTranscription.value.isJson) {+ openAsrEditorModal();+ } else {+ openTextEditorModal();+ }+ };- const resetColorScheme = () => {- applyColorScheme('blue');- showToast('Reset to default Ocean Blue theme', 'fa-undo');- };+ const openTextEditorModal = () => {+ if (!selectedRecording.value) return;+ editingTranscriptionContent.value = selectedRecording.value.transcription;+ showTextEditorModal.value = true;+ };- // Watch for dark mode changes to reapply color scheme- watch(isDarkMode, () => {- applyColorScheme(currentColorScheme.value);- });- // --- End Color Scheme Management ---+ const closeTextEditorModal = () => {+ showTextEditorModal.value = false;+ editingTranscriptionContent.value = '';+ };- // --- Sidebar Toggle ---- const toggleSidebar = () => { // This is for DESKTOP sidebar- if (!isMobileScreen.value) {- isSidebarCollapsed.value = !isSidebarCollapsed.value;- // localStorage.setItem('sidebarCollapsed', isSidebarCollapsed.value);-- // Ensure main content layout is preserved after sidebar toggle- nextTick(() => {- // Re-initialize layout if needed to maintain column widths- if (leftMainColumn.value && mainContentColumns.value) {- // Preserve the current column width percentage- const currentWidth = leftMainColumn.value.style.width;- if (currentWidth) {- // Force a layout recalculation to ensure the resizer still works- leftMainColumn.value.style.width = currentWidth;- }- }- });- }- };+ const saveTranscription = async () => {+ if (!selectedRecording.value) return;+ await saveTranscriptionContent(editingTranscriptionContent.value);+ closeTextEditorModal();+ };- const toggleMobileMenu = () => {- isMobileMenuOpen.value = !isMobileMenuOpen.value;- if (isMobileMenuOpen.value) {- document.body.classList.add('mobile-menu-open');- } else {- document.body.classList.remove('mobile-menu-open');- }- };+ const openAsrEditorModal = async () => {+ if (!selectedRecording.value) return;+ try {+ const segments = JSON.parse(selectedRecording.value.transcription);+ editingSegments.value = segments.map((s, i) => ({+ ...s,+ id: i,+ showSuggestions: false,+ filteredSpeakers: []+ }));- const closeMobileMenu = () => {- if (isMobileMenuOpen.value) {- isMobileMenuOpen.value = false;- document.body.classList.remove('mobile-menu-open');- }- };- // --- End Sidebar Toggle ----- // Helper to format date for display (e.g., "May 4, 2025")- const formatDisplayDate = (dateString) => {- if (!dateString) return '';- try {- // Input is expected as 'YYYY-MM-DD'- const date = new Date(dateString + 'T00:00:00'); // Add time to avoid timezone issues- return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });- } catch (e) {- console.error("Error formatting date:", e);- return dateString; // Return original string if formatting fails- }- };+ // Populate available speakers+ const speakersInTranscript = [...new Set(segments.map(s => s.speaker))];+ const response = await fetch('/speakers');+ const speakersFromDb = await response.json();+ const speakerNamesFromDb = speakersFromDb.map(s => s.name);+ availableSpeakers.value = [...new Set([...speakersInTranscript, ...speakerNamesFromDb])].sort();++ showAsrEditorModal.value = true;+ } catch (e) {+ console.error("Could not parse transcription as JSON for ASR editor:", e);+ setGlobalError("This transcription is not in the correct format for the ASR editor.");+ }+ };- // Helper for status display- const formatStatus = (status) => {- if (!status) return 'Unknown';- // Capitalize first letter, handle 'SUMMARIZING' specifically- return status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();- };+ const closeAsrEditorModal = () => {+ showAsrEditorModal.value = false;+ editingSegments.value = [];+ availableSpeakers.value = [];+ };- // Helper for status badge class- const getStatusClass = (status) => {- switch(status) {- case 'PENDING': return 'status-pending';- case 'PROCESSING': return 'status-processing';- case 'SUMMARIZING': return 'status-summarizing';- case 'COMPLETED': return 'status-completed';- case 'FAILED': return 'status-failed';- default: return 'status-pending'; // Default or unknown- }- };+ const saveAsrTranscription = async () => {+ const contentToSave = JSON.stringify(editingSegments.value.map(({ id, showSuggestions, filteredSpeakers, ...rest }) => rest));+ await saveTranscriptionContent(contentToSave);+ closeAsrEditorModal();+ };+ const adjustTime = (index, field, amount) => {+ if (editingSegments.value[index]) {+ editingSegments.value[index][field] = parseFloat((editingSegments.value[index][field] + amount).toFixed(3));+ }+ };- const resetCurrentFileProcessingState = () => {- if (pollInterval.value) clearInterval(pollInterval.value);- pollInterval.value = null;- currentlyProcessingFile.value = null;- processingProgress.value = 0;- processingMessage.value = '';- };+ const filterSpeakers = (index) => {+ const segment = editingSegments.value[index];+ if (segment) {+ const query = segment.speaker.toLowerCase();+ segment.filteredSpeakers = availableSpeakers.value.filter(s => s.toLowerCase().includes(query));+ }+ };- const switchToUploadView = () => {- currentView.value = 'upload';- selectedRecording.value = null;- };+ const openSpeakerSuggestions = (index) => {+ if (editingSegments.value[index]) {+ editingSegments.value[index].showSuggestions = true;+ filterSpeakers(index);+ }+ };- const switchToGalleryView = async () => {- currentView.value = 'gallery';- await loadRecordings(); // Refresh recordings when switching back- };+ const closeSpeakerSuggestions = (index) => {+ if (editingSegments.value[index]) {+ window.setTimeout(() => {+ if (editingSegments.value[index]) {+ editingSegments.value[index].showSuggestions = false;+ }+ }, 200); // Delay to allow click event to register+ }+ };- const handleDragLeave = (e) => {- if (e.relatedTarget && e.currentTarget.contains(e.relatedTarget)) {- return;- }- dragover.value = false;- }+ const selectSpeaker = (index, speaker) => {+ if (editingSegments.value[index]) {+ editingSegments.value[index].speaker = speaker;+ editingSegments.value[index].showSuggestions = false;+ }+ };- const handleDrop = (e) => {- dragover.value = false;- addFilesToQueue(e.dataTransfer.files);- };+ const addSegment = () => {+ const lastSegment = editingSegments.value[editingSegments.value.length - 1];+ editingSegments.value.push({+ id: Date.now(),+ speaker: lastSegment ? lastSegment.speaker : 'SPEAKER_00',+ start_time: lastSegment ? lastSegment.end_time : 0,+ end_time: lastSegment ? lastSegment.end_time + 1 : 1,+ sentence: ''+ });+ };- const handleFileSelect = (e) => {- addFilesToQueue(e.target.files);- e.target.value = null; // Reset input- };+ const removeSegment = (index) => {+ editingSegments.value.splice(index, 1);+ };- // --- Queue Management ---- const addFilesToQueue = (files) => {- let filesAdded = 0;- for (const file of files) {- if (file && file.type.startsWith('audio/')) {- if (file.size > maxFileSizeMB.value * 1024 * 1024) {- setGlobalError(`File "${file.name}" exceeds the maximum size of ${maxFileSizeMB.value} MB and was skipped.`);- continue;- }- const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;- uploadQueue.value.push({- file: file, status: 'queued', recordingId: null, clientId: clientId, error: null+ const saveTranscriptionContent = async (content) => {+ if (!selectedRecording.value) return;+ try {+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcription`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ transcription: content })});- filesAdded++;- } else if (file) {- setGlobalError(`Invalid file type "${file.name}". Only audio files are accepted. File skipped.`);+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to update transcription');+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);+ if (index !== -1) {+ recordings.value[index] = data.recording;+ }+ selectedRecording.value = data.recording;+ showToast('Transcription updated successfully!', 'fa-check-circle');+ } catch (error) {+ console.error('Save Transcription Error:', error);+ setGlobalError(`Failed to save transcription: ${error.message}`);}- }- if(filesAdded > 0) {- console.log(`Added ${filesAdded} file(s) to the queue.`);- progressPopupMinimized.value = false; // Show popup- progressPopupClosed.value = false; // Reset closed state to make popup reappear- if (!isProcessingActive.value) {- startProcessingQueue();+ };++ const cancelReprocess = () => {+ showReprocessModal.value = false;+ reprocessType.value = null;+ reprocessRecording.value = null;+ };++ const executeReprocess = async () => {+ if (!reprocessRecording.value || !reprocessType.value) return;++ const recordingId = reprocessRecording.value.id;+ const type = reprocessType.value;++ // Close the modal first+ cancelReprocess();++ if (type === 'transcription') {+ await performReprocessTranscription(+ recordingId,+ asrReprocessOptions.language,+ asrReprocessOptions.min_speakers,+ asrReprocessOptions.max_speakers+ );+ } else if (type === 'summary') {+ await performReprocessSummary(recordingId);}- }- };-- const startProcessingQueue = async () => {- console.log("Attempting to start processing queue...");- if (isProcessingActive.value) {- console.log("Queue processor already active.");- return;- }-- isProcessingActive.value = true;- resetCurrentFileProcessingState();-- const nextFileItem = uploadQueue.value.find(item => item.status === 'queued');-- if (nextFileItem) {- console.log(`Processing next file: ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId})`);- currentlyProcessingFile.value = nextFileItem;- nextFileItem.status = 'uploading';- processingMessage.value = 'Preparing upload...';- processingProgress.value = 5;+ };+ const performReprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {+ if (!recordingId) {+ setGlobalError('No recording ID provided for reprocessing.');+ return;+ }+try {- const formData = new FormData();- formData.append('file', nextFileItem.file);-- processingMessage.value = 'Uploading file...';- processingProgress.value = 10;-- const response = await fetch('/upload', { method: 'POST', body: formData });+ const payload = {+ language: language,+ min_speakers: minSpeakers,+ max_speakers: maxSpeakers+ };++ const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ });+const data = await response.json();-- if (!response.ok) {- let errorMsg = data.error || `Upload failed with status ${response.status}`;- if (response.status === 413) errorMsg = data.error || `File too large. Max: ${data.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;- throw new Error(errorMsg);+ if (!response.ok) throw new Error(data.error || 'Failed to start transcription reprocessing');++ // Update the recording in the UI+ const index = recordings.value.findIndex(r => r.id === recordingId);+ if (index !== -1) {+ recordings.value[index] = data.recording;}-- if (response.status === 202 && data.id) {- console.log(`File ${nextFileItem.file.name} uploaded. Recording ID: ${data.id}. Starting status poll.`);- // Status is now 'PENDING' on backend, will be updated by poll- nextFileItem.status = 'pending'; // Reflect initial backend status- nextFileItem.recordingId = data.id;- processingMessage.value = 'Upload complete. Waiting for processing...';- processingProgress.value = 30;-- // Add preliminary record to gallery immediately- recordings.value.unshift(data);- // Optionally select the new item- // selectRecording(data);-- pollProcessingStatus(nextFileItem); // Start polling-- } else {- throw new Error('Unexpected success response from server after upload.');++ // Update selected recording if it's the one being reprocessed+ if (selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data.recording;}-++ showToast('Transcription reprocessing started', 'fa-sync-alt');++ // Show progress modal for reprocessing+ showProgressModalForReprocessing(recordingId, 'transcription');++ // Start polling for status updates+ startReprocessingPoll(recordingId);+} catch (error) {- console.error(`Upload/Processing Error for ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId}):`, error);- nextFileItem.status = 'failed';- nextFileItem.error = error.message;- // Find the potentially added preliminary record and mark it failed- const failedRecordIndex = recordings.value.findIndex(r => r.id === nextFileItem.recordingId);- if(failedRecordIndex !== -1) {- recordings.value[failedRecordIndex].status = 'FAILED';- recordings.value[failedRecordIndex].transcription = `Upload/Processing failed: ${error.message}`;- } else {- // If record wasn't even created, add a note- setGlobalError(`Failed to process "${nextFileItem.file.name}": ${error.message}`);- }-- // Reset state and try next file- resetCurrentFileProcessingState();- isProcessingActive.value = false;- await nextTick();- startProcessingQueue();- }- } else {- console.log("Upload queue is empty or no files are queued.");- isProcessingActive.value = false;- // Optional: Auto-minimize popup after a delay- // setTimeout(() => {- // if (!isProcessingActive.value && uploadQueue.value.every(f => ['completed', 'failed'].includes(f.status))) {- // progressPopupMinimized.value = true;- // }- // }, 5000);- }- };-- const pollProcessingStatus = (fileItem) => {- if (pollInterval.value) clearInterval(pollInterval.value);-- const recordingId = fileItem.recordingId;- if (!recordingId) {- console.error("Cannot poll status without recording ID for", fileItem.file.name);- fileItem.status = 'failed';- fileItem.error = 'Internal error: Missing recording ID for polling.';- resetCurrentFileProcessingState();- isProcessingActive.value = false;- nextTick(startProcessingQueue); // Try next file- return;- }-- // Initial message based on fileItem status (should be 'pending' initially)- processingMessage.value = 'Waiting for transcription...';- processingProgress.value = 40;-- pollInterval.value = setInterval(async () => {- // Check if the item is still the one being processed and hasn't finished/failed- if (!currentlyProcessingFile.value || currentlyProcessingFile.value.clientId !== fileItem.clientId || ['completed', 'failed'].includes(fileItem.status)) {- console.log(`Polling stopped for ${fileItem.clientId} as it's no longer active or finished.`);- clearInterval(pollInterval.value);- pollInterval.value = null;- // If this was the active file, allow queue to restart- if (currentlyProcessingFile.value && currentlyProcessingFile.value.clientId === fileItem.clientId) {- resetCurrentFileProcessingState();- isProcessingActive.value = false;- await nextTick();- startProcessingQueue();- }+ console.error('Reprocess Transcription Error:', error);+ setGlobalError(`Failed to start transcription reprocessing: ${error.message}`);+ }+ };++ const performReprocessSummary = async (recordingId) => {+ if (!recordingId) {+ setGlobalError('No recording ID provided for reprocessing.');return;}-+try {- console.log(`Polling status for recording ID: ${recordingId} (${fileItem.file.name})`);- const response = await fetch(`/status/${recordingId}`);- if (!response.ok) throw new Error(`Status check failed with status ${response.status}`);-+ const response = await fetch(`/recording/${recordingId}/reprocess_summary`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ });+const data = await response.json();- const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);-- // Update item in the main recordings list- if (galleryIndex !== -1) {- recordings.value[galleryIndex] = data;- if(selectedRecording.value?.id === recordingId) {- selectedRecording.value = data; // Update selection if viewing details- }+ if (!response.ok) throw new Error(data.error || 'Failed to start summary reprocessing');++ // Update the recording in the UI+ const index = recordings.value.findIndex(r => r.id === recordingId);+ if (index !== -1) {+ recordings.value[index] = data.recording;}-- // Update the status in the uploadQueue item as well- fileItem.status = data.status;-- // Update progress display based on backend status- if (data.status === 'COMPLETED') {- console.log(`Processing COMPLETED for ${fileItem.file.name} (ID: ${recordingId})`);- processingMessage.value = 'Processing complete!';- processingProgress.value = 100;- fileItem.status = 'completed'; // Final status for queue item- // Stop polling, reset state, and trigger next item- clearInterval(pollInterval.value);- pollInterval.value = null;- resetCurrentFileProcessingState();- isProcessingActive.value = false;- await nextTick();- startProcessingQueue();-- } else if (data.status === 'FAILED') {- console.log(`Processing FAILED for ${fileItem.file.name} (ID: ${recordingId})`);- processingMessage.value = 'Processing failed.';- processingProgress.value = 100; // Show 100% but failed state- fileItem.status = 'failed'; // Final status for queue item- fileItem.error = data.transcription || data.summary || 'Processing failed on server.';- setGlobalError(`Processing failed for "${data.title || fileItem.file.name}".`);- // Stop polling, reset state, and trigger next item- clearInterval(pollInterval.value);- pollInterval.value = null;- resetCurrentFileProcessingState();- isProcessingActive.value = false;- await nextTick();- startProcessingQueue();-- } else if (data.status === 'PROCESSING') {- processingMessage.value = 'Transcription in progress...';- processingProgress.value = Math.min(65, processingProgress.value + Math.random() * 5); // Mid-range progress- } else if (data.status === 'SUMMARIZING') {- processingMessage.value = 'Generating title & summary...';- processingProgress.value = Math.min(95, processingProgress.value + Math.random() * 5); // Higher progress- } else { // PENDING- processingMessage.value = 'Waiting in queue...';- processingProgress.value = 45; // Keep progress indication while pending++ // Update selected recording if it's the one being reprocessed+ if (selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data.recording;}++ showToast('Summary reprocessing started', 'fa-sync-alt');++ // Show progress modal for reprocessing+ showProgressModalForReprocessing(recordingId, 'summary');++ // Start polling for status updates+ startReprocessingPoll(recordingId);+} catch (error) {- console.error(`Polling Error for ${fileItem.file.name} (ID: ${recordingId}):`, error);- // Assume failed if polling error occurs- fileItem.status = 'failed';- fileItem.error = `Error checking status: ${error.message}`;- setGlobalError(`Error checking status for "${fileItem.file.name}": ${error.message}.`);- // Update record in gallery if found- const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);- if (galleryIndex !== -1) recordings.value[galleryIndex].status = 'FAILED';-- clearInterval(pollInterval.value);- pollInterval.value = null;- resetCurrentFileProcessingState();- isProcessingActive.value = false;- await nextTick();- startProcessingQueue(); // Process the next file+ console.error('Reprocess Summary Error:', error);+ setGlobalError(`Failed to start summary reprocessing: ${error.message}`);}- }, 5000); // Poll every 5 seconds (adjust as needed)- };-- // --- Gallery and Detail Methods ---- // AutoSave removed in favor of explicit save in modal- // const autoSave = () => { ... };-- // Toggle inbox status- const toggleInbox = async (recording) => {- if (!recording || !recording.id) return;+ };- try {- const response = await fetch(`/recording/${recording.id}/toggle_inbox`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' }- });+ // Show progress modal for reprocessing operations+ const showProgressModalForReprocessing = (recordingId, type) => {+ const recording = recordings.value.find(r => r.id === recordingId);+ if (!recording) return;- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to toggle inbox status');+ // Create a mock file item for the progress modal+ const reprocessItem = {+ file: {+ name: recording.title || `Recording ${recordingId}`,+ size: recording.file_size || 0+ },+ status: 'pending',+ recordingId: recordingId,+ clientId: `reprocess-${type}-${recordingId}-${Date.now()}`,+ error: null,+ isReprocessing: true,+ reprocessType: type+ };- // Update the recording in the UI- recording.is_inbox = data.is_inbox;+ // Add to upload queue for progress tracking+ uploadQueue.value.unshift(reprocessItem);- // Update in the recordings list- const index = recordings.value.findIndex(r => r.id === recording.id);- if (index !== -1) {- recordings.value[index].is_inbox = data.is_inbox;- }+ // Show progress modal+ progressPopupMinimized.value = false;+ progressPopupClosed.value = false;- showToast(`Recording ${data.is_inbox ? 'moved to inbox' : 'marked as read'}`);- } catch (error) {- console.error('Toggle Inbox Error:', error);- setGlobalError(`Failed to toggle inbox status: ${error.message}`);- }- };-- // Toggle highlighted status- const toggleHighlight = async (recording) => {- if (!recording || !recording.id) return;+ // Set as currently processing file+ currentlyProcessingFile.value = reprocessItem;+ processingProgress.value = 10;+ processingMessage.value = type === 'transcription' ? 'Starting transcription reprocessing...' : 'Starting summary reprocessing...';+ };++ // Polling for reprocessing status updates+ const reprocessingPolls = ref(new Map()); // Track active polls by recording ID- try {- const response = await fetch(`/recording/${recording.id}/toggle_highlight`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' }- });-- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to toggle highlighted status');-- // Update the recording in the UI- recording.is_highlighted = data.is_highlighted;-- // Update in the recordings list- const index = recordings.value.findIndex(r => r.id === recording.id);- if (index !== -1) {- recordings.value[index].is_highlighted = data.is_highlighted;+ const startReprocessingPoll = (recordingId) => {+ // Clear any existing poll for this recording+ if (reprocessingPolls.value.has(recordingId)) {+ clearInterval(reprocessingPolls.value.get(recordingId));}- showToast(`Recording ${data.is_highlighted ? 'highlighted' : 'unhighlighted'}`);- } catch (error) {- console.error('Toggle Highlight Error:', error);- setGlobalError(`Failed to toggle highlighted status: ${error.message}`);- }- };-- const saveMetadata = async (recordingDataToSave) => {- globalError.value = null;- if (!recordingDataToSave || !recordingDataToSave.id) return null;- console.log('Saving metadata for:', recordingDataToSave.id);- try {- const payload = {- id: recordingDataToSave.id,- title: recordingDataToSave.title,- participants: recordingDataToSave.participants,- notes: recordingDataToSave.notes,- summary: recordingDataToSave.summary, // <-- ADDED: Include summary- meeting_date: recordingDataToSave.meeting_date // <-- ADDED: Include meeting_date (should be YYYY-MM-DD)- };- const response = await fetch('/save', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- });- 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 master recordings list- const index = recordings.value.findIndex(r => r.id === data.recording.id);- if (index !== -1) {- // Update only the editable fields, preserve others like status/transcription from backend- recordings.value[index].title = payload.title;- recordings.value[index].participants = payload.participants;- recordings.value[index].notes = payload.notes;- recordings.value[index].notes_html = data.recording.notes_html;- recordings.value[index].summary = payload.summary;- recordings.value[index].summary_html = data.recording.summary_html;- recordings.value[index].meeting_date = payload.meeting_date; // <-- ADDED: Update meeting_date- }- // Update selected if it's the one being saved- if (selectedRecording.value?.id === data.recording.id) {- selectedRecording.value.title = payload.title;- selectedRecording.value.participants = payload.participants;- selectedRecording.value.notes = payload.notes;- selectedRecording.value.notes_html = data.recording.notes_html;- selectedRecording.value.summary = payload.summary;- selectedRecording.value.summary_html = data.recording.summary_html;- selectedRecording.value.meeting_date = payload.meeting_date; // <-- ADDED: Update meeting_date- }- return data.recording; // Return the full updated object from backend- } catch (error) {- console.error('Save Metadata Error:', error);- setGlobalError(`Save failed: ${error.message}`);- return null;- }- };-- const loadRecordings = async () => {- globalError.value = null;- isLoadingRecordings.value = true;- 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;-- // After loading recordings, check for a saved recording ID- const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');- if (lastRecordingId) {- const recordingToSelect = recordings.value.find(r => r.id == lastRecordingId);- if (recordingToSelect) {- selectRecording(recordingToSelect);- }- }+ console.log(`Starting reprocessing poll for recording ${recordingId}`);++ const pollInterval = setInterval(async () => {+ try {+ const response = await fetch(`/status/${recordingId}`);+ if (!response.ok) {+ console.error(`Status check failed for recording ${recordingId}`);+ stopReprocessingPoll(recordingId);+ return;+ }++ const data = await response.json();++ // Update the recording in the UI+ const index = recordings.value.findIndex(r => r.id === recordingId);+ if (index !== -1) {+ recordings.value[index] = data;+ }++ // Update selected recording if it's the one being reprocessed+ if (selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data;+ }++ const queueItem = uploadQueue.value.find(item => item.recordingId === recordingId);- // On load, check for any recordings stuck in PENDING, PROCESSING, or SUMMARIZING- // and ensure polling is active if the queue processor isn't running.- const incompleteRecordings = recordings.value.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));-- if (incompleteRecordings.length > 0 && !isProcessingActive.value) {- console.warn(`Found ${incompleteRecordings.length} incomplete recording(s) on load. Attempting to resume polling if not already queued.`);- for (const recording of incompleteRecordings) {- // Is this item already being tracked in the queue?- let queueItem = uploadQueue.value.find(item => item.recordingId === recording.id);- if (!queueItem) {- // If not in queue (likely page reload), create a placeholder to track polling- console.log(`Re-attaching poll for recording ${recording.id}.`);- queueItem = {- // Mock file object, size might be useful for display- file: { name: recording.title || `Recording ${recording.id}`, size: recording.file_size },- status: recording.status, // Use current status from DB- recordingId: recording.id,- clientId: `reload-${recording.id}`, // Unique ID for tracking- error: null- };- // Add to the *beginning* of the visual queue *if* we want to show it there- // Or just manage polling without adding to queue visually?- // Let's add it to the queue for consistency in management.- uploadQueue.value.unshift(queueItem);- // Start processing queue if it wasn't active- if (!isProcessingActive.value) {- startProcessingQueue();- } else if (currentlyProcessingFile.value?.recordingId !== recording.id) {- // If processor is active but on a different file, just ensure polling starts- // Note: startProcessingQueue handles finding the next 'queued'. This item- // might not be 'queued'. We need direct polling.- // Let's rethink: The queue processor should handle finding PENDING/PROCESSING items.- // For simplicity, let's just trigger the queue processor. It will find this item if it's next.- // If something else is truly processing, this won't interrupt.- console.log("Triggering queue processor check due to reloaded incomplete item.")- // Ensure it's marked conceptually 'queued' for the processor to pick up- queueItem.status = 'queued';- startProcessingQueue(); // Let the queue logic handle it+ // Update the item's status and name for intermediate states+ if (queueItem) {+ queueItem.status = data.status; // e.g., 'PROCESSING', 'SUMMARIZING'+ queueItem.file.name = data.title || data.original_filename;+ }++ // Update progress modal if this is the currently processing item+ if (queueItem && currentlyProcessingFile.value?.clientId === queueItem.clientId) {+ updateReprocessingProgress(data.status, queueItem);+ }++ // Stop polling if processing is complete+ if (data.status === 'COMPLETED' || data.status === 'FAILED') {+ console.log(`Reprocessing ${data.status.toLowerCase()} for recording ${recordingId}`);+ stopReprocessingPoll(recordingId);++ // Update queue item status to final lowercase state+ if (queueItem) {+ queueItem.status = data.status === 'COMPLETED' ? 'completed' : 'failed';+ if (data.status === 'FAILED') {+ queueItem.error = data.error_message || 'Reprocessing failed';+ }+ }++ // Clear current processing if this was the active item+ if (currentlyProcessingFile.value?.recordingId === recordingId) {+ resetCurrentFileProcessingState();+ }++ if (data.status === 'COMPLETED') {+ showToast('Reprocessing completed successfully', 'fa-check-circle');+ } else {+ showToast('Reprocessing failed', 'fa-exclamation-circle');}-- } else if (queueItem.status !== recording.status && !['completed', 'failed'].includes(queueItem.status)) {- // If queue status differs from DB, update queue status- console.log(`Correcting queue status for ${queueItem.clientId} from ${queueItem.status} to ${recording.status}`);- queueItem.status = recording.status;- // Restart queue processing if needed- if (!isProcessingActive.value) startProcessingQueue();}++ } catch (error) {+ console.error(`Error polling status for recording ${recordingId}:`, error);+ stopReprocessingPoll(recordingId);}+ }, 3000); // Poll every 3 seconds++ reprocessingPolls.value.set(recordingId, pollInterval);+ };++ const updateReprocessingProgress = (status, queueItem) => {+ switch (status) {+ case 'PENDING':+ processingProgress.value = 20;+ processingMessage.value = `Waiting to start ${queueItem.reprocessType} reprocessing...`;+ break;+ case 'PROCESSING':+ processingProgress.value = Math.round(Math.min(70, processingProgress.value + Math.random() * 10));+ processingMessage.value = queueItem.reprocessType === 'transcription'+ ? 'Reprocessing transcription...'+ : 'Processing audio...';+ break;+ case 'SUMMARIZING':+ processingProgress.value = Math.round(Math.min(90, processingProgress.value + Math.random() * 10));+ processingMessage.value = queueItem.reprocessType === 'summary'+ ? 'Regenerating summary...'+ : 'Generating title and summary...';+ break;+ case 'COMPLETED':+ processingProgress.value = 100;+ processingMessage.value = 'Reprocessing completed!';+ break;+ case 'FAILED':+ processingProgress.value = 100;+ processingMessage.value = 'Reprocessing failed.';+ break;+ default:+ processingProgress.value = 15;+ processingMessage.value = 'Starting reprocessing...';}+ };- } catch (error) {- console.error('Load Recordings Error:', error);- setGlobalError(`Failed to load recordings: ${error.message}`);- recordings.value = [];- } finally {- isLoadingRecordings.value = false;- }- };-- const selectRecording = (recording) => {- // CRITICAL FIX: Reset the speakerMap state synchronously *before*- // updating the selected recording. This prevents a race condition where- // computed properties could re-evaluate using the new recording data- // but the old, stale speakerMap from a previous interaction.- speakerMap.value = {};-- selectedRecording.value = recording;- if (recording && recording.id) {- localStorage.setItem('lastSelectedRecordingId', recording.id);- } else {- localStorage.removeItem('lastSelectedRecordingId');- }- };-- const editRecording = (recording) => {- // Create a deep copy for the modal to prevent modifying original object directly- editingRecording.value = JSON.parse(JSON.stringify(recording));- showEditModal.value = true;- };-- const cancelEdit = () => {- showEditModal.value = false;- editingRecording.value = null;- };-- const saveEdit = async () => {- // Save using the saveMetadata function which updates the main list & selected item- const success = await saveMetadata(editingRecording.value);- if (success) {- cancelEdit(); // Close modal on success- }- // Keep modal open on failure, error shown via globalError- };-- 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;- const titleToDelete = recordingToDelete.value.title; // For logging/messaging- 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 gallery list- recordings.value = recordings.value.filter(r => r.id !== idToDelete);-- // Find and remove from upload queue- const queueIndex = uploadQueue.value.findIndex(item => item.recordingId === idToDelete);- if (queueIndex !== -1) {- const deletedItem = uploadQueue.value.splice(queueIndex, 1)[0];- console.log(`Removed item ${deletedItem.clientId} from queue.`);- // If deleting the file currently being processed, stop polling and move to next- if (currentlyProcessingFile.value?.clientId === deletedItem.clientId) {- console.log(`Deleting currently processing file: ${titleToDelete}. Stopping poll and moving to next.`);- clearInterval(pollInterval.value); // Stop polling explicitly- pollInterval.value = null;- resetCurrentFileProcessingState();- isProcessingActive.value = false; // Allow queue to restart- await nextTick();- startProcessingQueue();- }+ const stopReprocessingPoll = (recordingId) => {+ if (reprocessingPolls.value.has(recordingId)) {+ clearInterval(reprocessingPolls.value.get(recordingId));+ reprocessingPolls.value.delete(recordingId);+ console.log(`Stopped reprocessing poll for recording ${recordingId}`);}-- if (selectedRecording.value?.id === idToDelete) selectedRecording.value = null;- cancelDelete();- console.log(`Successfully deleted recording ${idToDelete} (${titleToDelete})`);-- } catch (error) {- console.error('Delete Error:', error);- setGlobalError(`Failed to delete recording "${titleToDelete}": ${error.message}`);- cancelDelete(); // Still close modal on error- }- };-- // Inline editing methods- const toggleEditParticipants = () => {- editingParticipants.value = !editingParticipants.value;- if (!editingParticipants.value) {- saveInlineEdit('participants');- }- };-- const toggleEditMeetingDate = () => {- editingMeetingDate.value = !editingMeetingDate.value;- if (!editingMeetingDate.value) {- saveInlineEdit('meeting_date');- }- };-- const toggleEditSummary = () => {- editingSummary.value = !editingSummary.value;- if (!editingSummary.value) {- saveInlineEdit('summary');- }- };-- const toggleEditNotes = () => {- editingNotes.value = !editingNotes.value;- if (!editingNotes.value) {- saveInlineEdit('notes');- }- };-- const saveInlineEdit = async (field) => {- if (!selectedRecording.value) return;-- // Create a payload with just the field being edited- const payload = {- id: selectedRecording.value.id,- [field]: selectedRecording.value[field]};-- // For completeness, include all editable fields in the payload- // This ensures the backend has all the data it needs- const fullPayload = {- id: selectedRecording.value.id,- title: selectedRecording.value.title,- participants: selectedRecording.value.participants,- notes: selectedRecording.value.notes,- summary: selectedRecording.value.summary,- meeting_date: selectedRecording.value.meeting_date++ const confirmReset = (recording) => {+ recordingToReset.value = recording;+ showResetModal.value = true;};-- try {- const updatedRecording = await saveMetadata(fullPayload);- if (updatedRecording) {- // Update the HTML versions from the response- if (field === 'notes') {- selectedRecording.value.notes_html = updatedRecording.notes_html;- } else if (field === 'summary') {- selectedRecording.value.summary_html = updatedRecording.summary_html;++ const cancelReset = () => {+ showResetModal.value = false;+ recordingToReset.value = null;+ };++ const executeReset = async () => {+ if (!recordingToReset.value) return;+ const recordingId = recordingToReset.value.id;++ // Close the modal first+ cancelReset();++ try {+ const response = await fetch(`/recording/${recordingId}/reset_status`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to reset status');++ // Update the recording in the UI+ const index = recordings.value.findIndex(r => r.id === recordingId);+ if (index !== -1) {+ recordings.value[index] = data.recording;}- // Reset the editing state for the field- switch(field) {- case 'participants':- editingParticipants.value = false;- break;- case 'meeting_date':- editingMeetingDate.value = false;- break;- case 'summary':- editingSummary.value = false;- break;- case 'notes':- editingNotes.value = false;- break;+ // Update selected recording if it's the one being reset+ if (selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data.recording;}- showToast(`${field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ')} updated successfully`);++ showToast('Recording status has been reset.', 'fa-check-circle');++ } catch (error) {+ console.error('Reset Status Error:', error);+ setGlobalError(`Failed to reset status: ${error.message}`);}- } catch (error) {- console.error(`Save ${field} Error:`, error);- setGlobalError(`Failed to save ${field}: ${error.message}`);- }- };-- // --- Audio Recording Methods ---- const formatTime = (seconds) => {- const minutes = Math.floor(seconds / 60);- const secs = seconds % 60;- return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;- };-- const startRecording = async () => {- if (!canRecordAudio.value) {- setGlobalError('Audio recording is not supported by your browser or permission was denied.');- return;- }- try {- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });- mediaRecorder.value = new MediaRecorder(stream);- audioChunks.value = [];- audioBlobURL.value = null; // Clear previous recording-- mediaRecorder.value.ondataavailable = event => {- audioChunks.value.push(event.data);- };-- mediaRecorder.value.onstop = () => {- const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' }); // or audio/ogg, audio/wav- audioBlobURL.value = URL.createObjectURL(audioBlob);- stream.getTracks().forEach(track => track.stop()); // Stop microphone access- clearInterval(recordingInterval.value);- };-- mediaRecorder.value.start();- isRecording.value = true;- recordingTime.value = 0;- recordingInterval.value = setInterval(() => {- recordingTime.value++;- }, 1000);- setGlobalError(null); // Clear any previous errors- } catch (err) {- console.error("Error starting recording:", err);- setGlobalError(`Could not start recording: ${err.message}. Please ensure microphone access is allowed.`);- isRecording.value = false;- canRecordAudio.value = false; // Assume permission denied or no device- }- };-- const stopRecording = () => {- if (mediaRecorder.value && isRecording.value) {- mediaRecorder.value.stop();- isRecording.value = false;- // URL and blob are set in onstop handler- }- };-- const uploadRecordedAudio = () => {- if (!audioBlobURL.value) {- setGlobalError("No recorded audio to upload.");- return;- }- // Create a File object from the Blob- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');- const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });-- addFilesToQueue([recordedFile]); // Use the existing queue mechanism- discardRecording(); // Clear the recording UI- };-- const discardRecording = () => {- if (audioBlobURL.value) {- URL.revokeObjectURL(audioBlobURL.value);- }- audioBlobURL.value = null;- audioChunks.value = [];- isRecording.value = false;- recordingTime.value = 0;- if (recordingInterval.value) clearInterval(recordingInterval.value);- };+ };- // --- Lifecycle Hooks ---- onMounted(async () => {- // Check for the ASR endpoint flag from the template- const appDiv = document.getElementById('app');- if (appDiv) {- const asrFlag = appDiv.dataset.useAsrEndpoint;- useAsrEndpoint.value = asrFlag === 'True' || asrFlag === 'true';- currentUserName.value = appDiv.dataset.currentUserName || '';- }- loadRecordings();- initializeDarkMode(); // Initialize dark mode on load- initializeColorScheme(); // Initialize color scheme on load-- // Load saved settings- const savedVolume = localStorage.getItem('playerVolume');- if (savedVolume !== null) {- playerVolume.value = parseFloat(savedVolume);- }- const savedTranscriptionViewMode = localStorage.getItem('transcriptionViewMode');- if (savedTranscriptionViewMode) {- transcriptionViewMode.value = savedTranscriptionViewMode;- }-- // Check initial screen size and handle window resize- const updateMobileStatus = () => {- windowWidth.value = window.innerWidth;- // If transitioning from mobile to desktop and mobile menu was open, close it.- if (!isMobileScreen.value && isMobileMenuOpen.value) {- closeMobileMenu();+ const searchSpeakers = async (query, speakerId) => {+ if (!query || query.length < 2) {+ speakerSuggestions.value[speakerId] = [];+ return;+ }++ loadingSuggestions.value[speakerId] = true;++ try {+ const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);+ if (!response.ok) throw new Error('Failed to search speakers');++ const speakers = await response.json();+ speakerSuggestions.value[speakerId] = speakers;+ } catch (error) {+ console.error('Error searching speakers:', error);+ speakerSuggestions.value[speakerId] = [];+ } finally {+ loadingSuggestions.value[speakerId] = false;}};- window.addEventListener('resize', updateMobileStatus);- updateMobileStatus(); // Set initial window width-- // Close mobile menu on escape key- const handleEsc = (e) => {- if (e.key === 'Escape' && isMobileMenuOpen.value) {- closeMobileMenu();+ const selectSpeakerSuggestion = (speakerId, suggestion) => {+ if (speakerMap.value[speakerId]) {+ speakerMap.value[speakerId].name = suggestion.name;+ speakerSuggestions.value[speakerId] = [];}};- document.addEventListener('keydown', handleEsc);- });-- // --- Main Column Resizer Methods ---- const loadMainColumnWidths = () => {- if (isMobileScreen.value || !leftMainColumn.value) return;-- const savedLeftWidthPercent = localStorage.getItem('mainColumnLeftWidthPercent');- if (savedLeftWidthPercent) {- const percent = parseFloat(savedLeftWidthPercent);- // Validate against the new percentage-based constraints- if (percent >= MIN_MAIN_COLUMN_WIDTH_PERCENT && percent <= MAX_MAIN_COLUMN_WIDTH_PERCENT) {- leftMainColumn.value.style.width = `${percent}%`;- } else {- // If stored value is out of bounds, apply default within valid range- const defaultPercent = Math.max(MIN_MAIN_COLUMN_WIDTH_PERCENT, Math.min(40, MAX_MAIN_COLUMN_WIDTH_PERCENT));- leftMainColumn.value.style.width = `${defaultPercent}%`;- localStorage.removeItem('mainColumnLeftWidthPercent'); // Clear invalid stored value- }- } else if (leftMainColumn.value.style.width === '') {- // If no saved width and no inline style, set default within valid range- const defaultPercent = Math.max(MIN_MAIN_COLUMN_WIDTH_PERCENT, Math.min(40, MAX_MAIN_COLUMN_WIDTH_PERCENT));- leftMainColumn.value.style.width = `${defaultPercent}%`;- }- };-- const saveMainColumnWidths = (leftWidthPercentString) => {- if (isMobileScreen.value) return;- localStorage.setItem('mainColumnLeftWidthPercent', leftWidthPercentString);- };-- const initMainColumnResizer = () => {- if (mainColumnResizer.value && !isMobileScreen.value) {- mainColumnResizer.value.addEventListener('mousedown', startMainColumnResize);- }- };-- const startMainColumnResize = (event) => {- if (isMobileScreen.value || !leftMainColumn.value || !mainContentColumns.value) return;- event.preventDefault();-- isResizingMainColumns.value = true;- initialMainColumnResizeX = event.clientX;- initialLeftMainColumnWidthPx = leftMainColumn.value.offsetWidth;-- document.addEventListener('mousemove', handleMainColumnResize);- document.addEventListener('mouseup', stopMainColumnResize);- document.body.style.cursor = 'ew-resize';- document.body.style.userSelect = 'none';- };-- const handleMainColumnResize = (event) => {- if (!isResizingMainColumns.value || !leftMainColumn.value || !mainContentColumns.value || !mainColumnResizer.value) return;-- const dx = event.clientX - initialMainColumnResizeX;- // Get CURRENT parent width (not cached) to handle sidebar state changes- const currentParentWidthPx = mainContentColumns.value.offsetWidth;- const resizerActualWidth = mainColumnResizer.value.offsetWidth;- const resizerMarginLeft = parseFloat(getComputedStyle(mainColumnResizer.value).marginLeft) || 0;- const resizerMarginRight = parseFloat(getComputedStyle(mainColumnResizer.value).marginRight) || 0;- const resizerTotalSpacePx = resizerActualWidth + resizerMarginLeft + resizerMarginRight;+ const openSpeakerModal = () => {+ // Clear any existing speaker map data first+ speakerMap.value = {};++ // Initialize speaker map only for speakers in the current recording+ speakerMap.value = identifiedSpeakers.value.reduce((acc, speaker, index) => {+ acc[speaker] = {+ name: '',+ isMe: false,+ color: `speaker-color-${(index % 8) + 1}` // Assign same colors as transcription view+ };+ return acc;+ }, {});++ highlightedSpeaker.value = null;+ speakerSuggestions.value = {};+ loadingSuggestions.value = {};+ isAutoIdentifying.value = false;+ showSpeakerModal.value = true;+ };++ const closeSpeakerModal = () => {+ showSpeakerModal.value = false;+ highlightedSpeaker.value = null;+ // Clear the speaker map to prevent stale data from persisting+ speakerMap.value = {};+ speakerSuggestions.value = {};+ loadingSuggestions.value = {};+ };++ const saveSpeakerNames = async () => {+ if (!selectedRecording.value) return;++ // Create a filtered speaker map that excludes entries with blank names+ const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {+ if (speakerData.name && speakerData.name.trim() !== '') {+ acc[speakerId] = speakerData;+ }+ return acc;+ }, {});++ try {+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ speaker_map: filteredSpeakerMap, // Send the filtered map+ regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value+ })+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to update speakers');++ // On success, close the modal and clear the speakerMap state *before*+ // updating the recording data. This prevents a race condition where the+ // view could re-render using the new data but the old, lingering speakerMap.+ closeSpeakerModal();++ // The backend returns the fully updated recording object.+ // We can directly update our local state with this fresh data.+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);+ if (index !== -1) {+ recordings.value[index] = data.recording;+ }+ selectedRecording.value = data.recording;++ showToast('Speaker names updated successfully!', 'fa-check-circle');++ // If a summary regeneration was requested, start polling for its status.+ if (regenerateSummaryAfterSpeakerUpdate.value) {+ startReprocessingPoll(selectedRecording.value.id);+ }++ } catch (error) {+ console.error('Save Speaker Names Error:', error);+ setGlobalError(`Failed to save speaker names: ${error.message}`);+ }+ };++ const highlightSpeakerInTranscript = (speakerId) => {+ highlightedSpeaker.value = speakerId;+ // Scroll to the first instance in the transcript when a speaker is focused+ if (speakerId) {+ nextTick(() => {+ // Try both the modal transcript and the main transcript+ const modalTranscript = document.querySelector('div.speaker-modal-transcript');+ const mainTranscript = document.querySelector('.transcription-simple-view, .transcription-with-speakers, .transcription-content');+ const transcriptContainer = modalTranscript || mainTranscript;+ if (transcriptContainer) {+ const firstInstance = transcriptContainer.querySelector(`[data-speaker-id="${speakerId}"]`);+ if (firstInstance) {+ firstInstance.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }+ }+ });+ }+ };- const currentEffectiveParentWidthPx = currentParentWidthPx - resizerTotalSpacePx;+ // Enhanced speaker highlighting with focus/blur events for text inputs+ const focusSpeaker = (speakerId) => {+ highlightSpeakerInTranscript(speakerId);+ };- if (currentEffectiveParentWidthPx <= 0) return; // Guard against division by zero or invalid state+ const blurSpeaker = () => {+ clearSpeakerHighlight();+ };++ const clearSpeakerHighlight = () => {+ highlightedSpeaker.value = null;+ };++ const autoIdentifySpeakers = async () => {+ if (!selectedRecording.value) {+ showToast('No recording selected.', 'fa-exclamation-circle');+ return;+ }- // Calculate new width based on mouse movement- let newLeftWidthPx = initialLeftMainColumnWidthPx + dx;+ isAutoIdentifying.value = true;+ showToast('Starting automatic speaker identification...', 'fa-magic');- // Apply constraints smoothly - use pixel-based constraints for better control- const minLeftPx = Math.max(ABSOLUTE_MIN_COLUMN_PX, (MIN_MAIN_COLUMN_WIDTH_PERCENT / 100) * currentEffectiveParentWidthPx);- const maxLeftPx = Math.min(currentEffectiveParentWidthPx - ABSOLUTE_MIN_COLUMN_PX, (MAX_MAIN_COLUMN_WIDTH_PERCENT / 100) * currentEffectiveParentWidthPx);-- // Smooth constraint application - don't snap to limits immediately- if (newLeftWidthPx < minLeftPx) {- newLeftWidthPx = minLeftPx;- } else if (newLeftWidthPx > maxLeftPx) {- newLeftWidthPx = maxLeftPx;- }+ try {+ const response = await fetch(`/recording/${selectedRecording.value.id}/auto_identify_speakers`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ current_speaker_map: speakerMap.value+ })+ });++ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Unknown error occurred during auto-identification.');+ }++ // Check if there's a message (e.g., all speakers already identified)+ if (data.message) {+ showToast(data.message, 'fa-info-circle');+ return;+ }++ // Update speakerMap with the identified names (only for unidentified speakers)+ let identifiedCount = 0;+ for (const speakerId in data.speaker_map) {+ const identifiedName = data.speaker_map[speakerId];+ if (speakerMap.value[speakerId] && identifiedName && identifiedName.trim() !== '') {+ speakerMap.value[speakerId].name = identifiedName;+ identifiedCount++;+ }+ }++ if (identifiedCount > 0) {+ showToast(`${identifiedCount} speaker(s) identified successfully!`, 'fa-check-circle');+ } else {+ showToast('No speakers could be identified from the context.', 'fa-info-circle');+ }- // Calculate percentage based on CURRENT effective width- const newLeftWidthPercent = (newLeftWidthPx / currentEffectiveParentWidthPx) * 100;+ } catch (error) {+ console.error('Auto Identify Speakers Error:', error);+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 5000);+ } finally {+ isAutoIdentifying.value = false;+ }+ };- leftMainColumn.value.style.width = `${newLeftWidthPercent.toFixed(2)}%`;- };+ const toggleInbox = async (recording) => {+ if (!recording || !recording.id) return;++ try {+ const response = await fetch(`/recording/${recording.id}/toggle_inbox`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to toggle inbox status');++ // Update the recording in the UI+ recording.is_inbox = data.is_inbox;++ // Update in the recordings list+ const index = recordings.value.findIndex(r => r.id === recording.id);+ if (index !== -1) {+ recordings.value[index].is_inbox = data.is_inbox;+ }++ showToast(`Recording ${data.is_inbox ? 'moved to inbox' : 'marked as read'}`);+ } catch (error) {+ console.error('Toggle Inbox Error:', error);+ setGlobalError(`Failed to toggle inbox status: ${error.message}`);+ }+ };++ // Toggle highlighted status+ const toggleHighlight = async (recording) => {+ if (!recording || !recording.id) return;++ try {+ const response = await fetch(`/recording/${recording.id}/toggle_highlight`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to toggle highlighted status');++ // Update the recording in the UI+ recording.is_highlighted = data.is_highlighted;++ // Update in the recordings list+ const index = recordings.value.findIndex(r => r.id === recording.id);+ if (index !== -1) {+ recordings.value[index].is_highlighted = data.is_highlighted;+ }++ showToast(`Recording ${data.is_highlighted ? 'highlighted' : 'unhighlighted'}`);+ } catch (error) {+ console.error('Toggle Highlight Error:', error);+ setGlobalError(`Failed to toggle highlighted status: ${error.message}`);+ }+ };- const stopMainColumnResize = () => {- if (!isResizingMainColumns.value) return;- isResizingMainColumns.value = false;+ // --- Dark Mode ---+ const toggleDarkMode = () => {+ isDarkMode.value = !isDarkMode.value;+ if (isDarkMode.value) {+ document.documentElement.classList.add('dark');+ localStorage.setItem('darkMode', 'true');+ } else {+ document.documentElement.classList.remove('dark');+ localStorage.setItem('darkMode', 'false');+ }+ };- document.removeEventListener('mousemove', handleMainColumnResize);- document.removeEventListener('mouseup', stopMainColumnResize);- document.body.style.cursor = '';- document.body.style.userSelect = '';+ const initializeDarkMode = () => {+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ const savedMode = localStorage.getItem('darkMode');+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ isDarkMode.value = true;+ document.documentElement.classList.add('dark');+ } else {+ isDarkMode.value = false;+ document.documentElement.classList.remove('dark');+ }+ };- if (leftMainColumn.value && leftMainColumn.value.style.width) {- saveMainColumnWidths(parseFloat(leftMainColumn.value.style.width).toFixed(2));- }- };-- // Watch for screen size changes to re-init or clear resizer- watch(isMobileScreen, (isMobile) => {- if (isMobile) {- if (mainColumnResizer.value) {- mainColumnResizer.value.removeEventListener('mousedown', startMainColumnResize);- }- // Optionally reset widths to default for mobile if needed, though CSS should handle layout- } else {- // Desktop: ensure elements are available and initialize- nextTick(() => { // Ensure DOM is updated- initializeDesktopLayout();- });- }- });+ const applyColorScheme = (schemeId, mode = null) => {+ const targetMode = mode || (isDarkMode.value ? 'dark' : 'light');+ const scheme = colorSchemes[targetMode].find(s => s.id === schemeId);++ if (!scheme) {+ console.warn(`Color scheme '${schemeId}' not found for mode '${targetMode}'`);+ return;+ }- // --- Vertical Resizer Methods ---- const initVerticalResizer = () => {- transcriptionSection.value = document.querySelector('.transcription-section');- tabSection.value = document.querySelector('.tab-section');- verticalResizeHandle.value = document.querySelector('.resize-handle');-- if (verticalResizeHandle.value && !isMobileScreen.value) {- verticalResizeHandle.value.addEventListener('mousedown', startVerticalResize);- console.log('Vertical resizer initialized with addEventListener');- return true; // Successfully initialized- } else {- console.log('Vertical resizer elements not found:', {- transcriptionSection: !!transcriptionSection.value,- tabSection: !!tabSection.value,- verticalResizeHandle: !!verticalResizeHandle.value,- isMobileScreen: isMobileScreen.value- });- return false; // Failed to initialize- }- };+ const allThemeClasses = [+ ...colorSchemes.light.map(s => s.class),+ ...colorSchemes.dark.map(s => s.class)+ ].filter(c => c !== '');- const startVerticalResize = (event) => {- if (isMobileScreen.value || !transcriptionSection.value || !tabSection.value) return;- event.preventDefault();+ document.documentElement.classList.remove(...allThemeClasses);- isResizingVertical.value = true;- initialVerticalResizeY = event.clientY;- initialTranscriptionHeightPx = transcriptionSection.value.offsetHeight;- initialTabHeightPx = tabSection.value.offsetHeight;+ if (scheme.class) {+ document.documentElement.classList.add(scheme.class);+ }- document.addEventListener('mousemove', handleVerticalResize);- document.addEventListener('mouseup', stopVerticalResize);- document.body.style.cursor = 'ns-resize';- document.body.style.userSelect = 'none';-- console.log('Started vertical resize');- };+ currentColorScheme.value = schemeId;+ localStorage.setItem('colorScheme', schemeId);+ };- const handleVerticalResize = (event) => {- if (!isResizingVertical.value) return;+ const initializeColorScheme = () => {+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ currentColorScheme.value = savedScheme;+ applyColorScheme(savedScheme);+ };- requestAnimationFrame(() => {- if (!transcriptionSection.value || !tabSection.value) return;+ const openColorSchemeModal = () => {+ showColorSchemeModal.value = true;+ };- const dy = event.clientY - initialVerticalResizeY;- const totalHeight = initialTranscriptionHeightPx + initialTabHeightPx;-- let newTranscriptionHeight = initialTranscriptionHeightPx + dy;-- // Enforce minimum heights (e.g., 100px)- const minHeight = 100;- if (newTranscriptionHeight < minHeight) {- newTranscriptionHeight = minHeight;- } else if (totalHeight - newTranscriptionHeight < minHeight) {- newTranscriptionHeight = totalHeight - minHeight;- }-- const newTabHeight = totalHeight - newTranscriptionHeight;+ const closeColorSchemeModal = () => {+ showColorSchemeModal.value = false;+ };++ const selectColorScheme = (schemeId) => {+ applyColorScheme(schemeId);+ showToast(`Applied ${colorSchemes[isDarkMode.value ? 'dark' : 'light'].find(s => s.id === schemeId)?.name} theme`, 'fa-palette');+ };- // Convert heights to flex-grow values- // The sum of flex-grow values will be used for proportioning- const newTranscriptionFlex = newTranscriptionHeight / totalHeight;- const newTabFlex = newTabHeight / totalHeight;+ const resetColorScheme = () => {+ applyColorScheme('blue');+ showToast('Reset to default Ocean Blue theme', 'fa-undo');+ };- transcriptionFlex.value = newTranscriptionFlex;- tabsFlex.value = newTabFlex;+ // Watch for dark mode changes to reapply color scheme+ watch(isDarkMode, () => {+ applyColorScheme(currentColorScheme.value);});- };- const stopVerticalResize = () => {- if (!isResizingVertical.value) return;- isResizingVertical.value = false;+ // --- Sidebar Toggle ---+ const toggleSidebar = () => {+ isSidebarCollapsed.value = !isSidebarCollapsed.value;+ };- document.removeEventListener('mousemove', handleVerticalResize);- document.removeEventListener('mouseup', stopVerticalResize);- document.body.style.cursor = '';- document.body.style.userSelect = '';-- console.log('Stopped vertical resize');- };+ // --- View Management ---+ const switchToUploadView = () => {+ currentView.value = 'upload';+ selectedRecording.value = null;+ if (isMobileScreen.value) {+ isSidebarCollapsed.value = true;+ }+ };- // Helper function to initialize desktop layout- const initializeDesktopLayout = () => {- console.log('Attempting to initialize desktop layout...');-- // First check if we're actually in desktop mode- if (isMobileScreen.value) {- console.log('Skipping desktop layout initialization - mobile screen detected');- return false;- }-- // Check if desktop layout elements are visible and rendered- const desktopLayout = document.querySelector('.desktop-layout');- if (!desktopLayout) {- console.log('Desktop layout container not found');- return false;- }-- // Check if desktop layout is actually visible (not hidden by CSS)- const desktopLayoutStyle = window.getComputedStyle(desktopLayout);- if (desktopLayoutStyle.display === 'none') {- console.log('Desktop layout is hidden by CSS');- return false;- }-- leftMainColumn.value = document.getElementById('leftMainColumn');- rightMainColumn.value = document.getElementById('rightMainColumn');- mainColumnResizer.value = document.getElementById('mainColumnResizer');- mainContentColumns.value = document.getElementById('mainContentColumns');-- let mainColumnsInitialized = false;- if (leftMainColumn.value && rightMainColumn.value && mainColumnResizer.value && mainContentColumns.value) {- // Additional check to ensure elements are actually visible- const leftStyle = window.getComputedStyle(leftMainColumn.value);- const rightStyle = window.getComputedStyle(rightMainColumn.value);-- if (leftStyle.display !== 'none' && rightStyle.display !== 'none') {- loadMainColumnWidths();- initMainColumnResizer();- mainColumnsInitialized = true;- console.log('Main columns initialized successfully');+ const selectRecording = (recording) => {+ if (currentView.value === 'recording' && isRecording.value) {+ // If we are in the middle of a recording, don't switch views+ setGlobalError("Please stop the current recording before selecting another one.");+ return;+ }+ selectedRecording.value = recording;+ currentView.value = 'detail';+ if (recording && recording.id) {+ localStorage.setItem('lastSelectedRecordingId', recording.id);} else {- console.log('Main column elements are hidden by CSS');- }- } else {- console.log('Main column elements not found:', {- leftMainColumn: !!leftMainColumn.value,- rightMainColumn: !!rightMainColumn.value,- mainColumnResizer: !!mainColumnResizer.value,- mainContentColumns: !!mainContentColumns.value- });- }-- // Initialize vertical resizer- const verticalInitialized = initVerticalResizer();-- // Initialize vertical resizing flex values- const defaultTranscriptionFlex = 2; // Default initial value- const defaultTabsFlex = 1; // Default initial value+ localStorage.removeItem('lastSelectedRecordingId');+ }+ if (isMobileScreen.value) {+ isSidebarCollapsed.value = true;+ }+ };- transcriptionFlex.value = defaultTranscriptionFlex;- tabsFlex.value = defaultTabsFlex;-- console.log('Initialized vertical flex values:', { transcriptionFlex: transcriptionFlex.value, tabsFlex: tabsFlex.value });-- // Return true if at least one resizer was initialized successfully- const success = mainColumnsInitialized || verticalInitialized;- console.log('Desktop layout initialization result:', { mainColumnsInitialized, verticalInitialized, success });- return success;- };+ // --- File Upload ---+ const handleDragOver = (e) => {+ e.preventDefault();+ dragover.value = true;+ };++ const handleDragLeave = (e) => {+ if (e.relatedTarget && e.currentTarget.contains(e.relatedTarget)) {+ return;+ }+ dragover.value = false;+ };+ const handleDrop = (e) => {+ e.preventDefault();+ dragover.value = false;+ addFilesToQueue(e.dataTransfer.files);+ };- // --- Watchers ---- watch(uploadQueue, (newQueue, oldQueue) => {- if (newQueue.length === 0 && oldQueue.length > 0 && !isProcessingActive.value) {- console.log("Upload queue processing finished.");- // Auto-minimize after delay- setTimeout(() => progressPopupMinimized.value = true, 1000);- // Auto-hide popup after all uploads are complete- setTimeout(() => {- if (completedInQueue.value === totalInQueue.value && !isProcessingActive.value) {- progressPopupClosed.value = true;+ const handleFileSelect = (e) => {+ addFilesToQueue(e.target.files);+ e.target.value = null;+ };++ const addFilesToQueue = (files) => {+ let filesAdded = 0;+ for (const file of files) {+ const fileObject = file.file ? file.file : file;+ const notes = file.notes || null;++ // Check if it's an audio file or has AMR extension+ const isAudioFile = fileObject && (+ fileObject.type.startsWith('audio/') ||+ fileObject.name.toLowerCase().endsWith('.amr') ||+ fileObject.name.toLowerCase().endsWith('.3gp') ||+ fileObject.name.toLowerCase().endsWith('.3gpp')+ );++ if (isAudioFile) {+ if (fileObject.size > maxFileSizeMB.value * 1024 * 1024) {+ setGlobalError(`File "${fileObject.name}" exceeds the maximum size of ${maxFileSizeMB.value} MB and was skipped.`);+ continue;+ }+ const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;+ uploadQueue.value.push({+ file: fileObject,+ notes: notes,+ status: 'queued',+ recordingId: null,+ clientId: clientId,+ error: null+ });+ filesAdded++;+ } else if (fileObject) {+ setGlobalError(`Invalid file type "${fileObject.name}". Only audio files (including AMR) are accepted. File skipped.`);}- }, 5000);- }- }, { deep: true });+ }+ if(filesAdded > 0) {+ console.log(`Added ${filesAdded} file(s) to the queue.`);+ progressPopupMinimized.value = false;+ progressPopupClosed.value = false;+ if (!isProcessingActive.value) {+ startProcessingQueue();+ }+ }+ };++ const resetCurrentFileProcessingState = () => {+ if (pollInterval.value) clearInterval(pollInterval.value);+ pollInterval.value = null;+ currentlyProcessingFile.value = null;+ processingProgress.value = 0;+ processingMessage.value = '';+ };- watch(speakerMap, (newMap) => {- for (const speakerId in newMap) {- if (newMap[speakerId].isMe) {- newMap[speakerId].name = currentUserName.value || 'Me';+ const startProcessingQueue = async () => {+ console.log("Attempting to start processing queue...");+ if (isProcessingActive.value) {+ console.log("Queue processor already active.");+ return;}- }- }, { deep: true });+ isProcessingActive.value = true;+ resetCurrentFileProcessingState();- // --- Reprocessing functionality ---- const confirmReprocess = (type, recording) => {- reprocessType.value = type;- reprocessRecording.value = recording;- showReprocessModal.value = true;- };-- const cancelReprocess = () => {- showReprocessModal.value = false;- reprocessType.value = null;- reprocessRecording.value = null;- };-- const executeReprocess = async () => {- if (!reprocessRecording.value || !reprocessType.value) return;-- const recordingId = reprocessRecording.value.id;- const type = reprocessType.value;-- // Close the modal first- cancelReprocess();-- if (type === 'transcription') {- await performReprocessTranscription(- recordingId,- asrReprocessOptions.language,- asrReprocessOptions.min_speakers,- asrReprocessOptions.max_speakers- );- } else if (type === 'summary') {- await performReprocessSummary(recordingId);- }- };-- const reprocessTranscription = (recordingId) => {- const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;- confirmReprocess('transcription', recording);- };-- const reprocessSummary = (recordingId) => {- const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;- confirmReprocess('summary', recording);- };+ const nextFileItem = uploadQueue.value.find(item => item.status === 'queued');- const confirmAsrReprocess = (recording) => {- reprocessRecording.value = recording;- // Reset/pre-fill options when opening the modal- asrReprocessOptions.language = recording.owner?.transcription_language || '';- asrReprocessOptions.min_speakers = null;- asrReprocessOptions.max_speakers = null;- showAsrReprocessModal.value = true;- };+ if (nextFileItem) {+ console.log(`Processing next file: ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId})`);+ currentlyProcessingFile.value = nextFileItem;+ nextFileItem.status = 'uploading';+ processingMessage.value = 'Preparing upload...';+ processingProgress.value = 5;- const cancelAsrReprocess = () => {- showAsrReprocessModal.value = false;- reprocessRecording.value = null; // Clear the recording being reprocessed- };+ try {+ const formData = new FormData();+ formData.append('file', nextFileItem.file);+ if (nextFileItem.notes) {+ formData.append('notes', nextFileItem.notes);+ }- const executeAsrReprocess = async () => {- if (!reprocessRecording.value) return;-- const recordingId = reprocessRecording.value.id;-- // Hide modal before starting- showAsrReprocessModal.value = false;-- await performAsrReprocess(- recordingId,- asrReprocessOptions.language,- asrReprocessOptions.min_speakers,- asrReprocessOptions.max_speakers- );-- // Clear the recording after execution- reprocessRecording.value = null;- };+ processingMessage.value = 'Uploading file...';+ processingProgress.value = 10;- // Speaker database functionality- const speakerSuggestions = ref({});- const loadingSuggestions = ref({});-- const searchSpeakers = async (query, speakerId) => {- if (!query || query.length < 2) {- speakerSuggestions.value[speakerId] = [];- return;- }-- loadingSuggestions.value[speakerId] = true;-- try {- const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);- if (!response.ok) throw new Error('Failed to search speakers');-- const speakers = await response.json();- speakerSuggestions.value[speakerId] = speakers;- } catch (error) {- console.error('Error searching speakers:', error);- speakerSuggestions.value[speakerId] = [];- } finally {- loadingSuggestions.value[speakerId] = false;- }- };-- const selectSpeakerSuggestion = (speakerId, suggestion) => {- if (speakerMap.value[speakerId]) {- speakerMap.value[speakerId].name = suggestion.name;- speakerSuggestions.value[speakerId] = [];- }- };-- const openSpeakerModal = () => {- // Clear any existing speaker map data first- speakerMap.value = {};-- // Initialize speaker map only for speakers in the current recording- speakerMap.value = identifiedSpeakers.value.reduce((acc, speaker, index) => {- acc[speaker] = {- name: '',- isMe: false,- color: `speaker-color-${(index % 8) + 1}` // Assign same colors as transcription view- };- return acc;- }, {});-- highlightedSpeaker.value = null;- speakerSuggestions.value = {};- loadingSuggestions.value = {};- isAutoIdentifying.value = false;- showSpeakerModal.value = true;- };+ const response = await fetch('/upload', { method: 'POST', body: formData });+ const data = await response.json();- const closeSpeakerModal = () => {- showSpeakerModal.value = false;- highlightedSpeaker.value = null;- // Clear the speaker map to prevent stale data from persisting- speakerMap.value = {};- speakerSuggestions.value = {};- loadingSuggestions.value = {};- };+ if (!response.ok) {+ let errorMsg = data.error || `Upload failed with status ${response.status}`;+ if (response.status === 413) errorMsg = data.error || `File too large. Max: ${data.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;+ throw new Error(errorMsg);+ }- const saveSpeakerNames = async () => {- if (!selectedRecording.value) return;-- // Create a filtered speaker map that excludes entries with blank names- const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {- if (speakerData.name && speakerData.name.trim() !== '') {- acc[speakerId] = speakerData;- }- return acc;- }, {});-- try {- const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- speaker_map: filteredSpeakerMap, // Send the filtered map- regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value- })- });+ if (response.status === 202 && data.id) {+ console.log(`File ${nextFileItem.file.name} uploaded. Recording ID: ${data.id}. Starting status poll.`);+ nextFileItem.status = 'pending';+ nextFileItem.recordingId = data.id;+ processingMessage.value = 'Upload complete. Waiting for processing...';+ processingProgress.value = 30;- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to update speakers');+ recordings.value.unshift(data);+ pollProcessingStatus(nextFileItem);++ } else {+ throw new Error('Unexpected success response from server after upload.');+ }- // On success, close the modal and clear the speakerMap state *before*- // updating the recording data. This prevents a race condition where the- // view could re-render using the new data but the old, lingering speakerMap.- closeSpeakerModal();+ } catch (error) {+ console.error(`Upload/Processing Error for ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId}):`, error);+ nextFileItem.status = 'failed';+ nextFileItem.error = error.message;+ const failedRecordIndex = recordings.value.findIndex(r => r.id === nextFileItem.recordingId);+ if(failedRecordIndex !== -1) {+ recordings.value[failedRecordIndex].status = 'FAILED';+ recordings.value[failedRecordIndex].transcription = `Upload/Processing failed: ${error.message}`;+ } else {+ setGlobalError(`Failed to process "${nextFileItem.file.name}": ${error.message}`);+ }- // The backend returns the fully updated recording object.- // We can directly update our local state with this fresh data.- const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);- if (index !== -1) {- recordings.value[index] = data.recording;+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();+ }+ } else {+ console.log("Upload queue is empty or no files are queued.");+ isProcessingActive.value = false;}- selectedRecording.value = data.recording;+ };- showToast('Speaker names updated successfully!', 'fa-check-circle');+ const pollProcessingStatus = (fileItem) => {+ if (pollInterval.value) clearInterval(pollInterval.value);- // If a summary regeneration was requested, start polling for its status.- if (regenerateSummaryAfterSpeakerUpdate.value) {- startReprocessingPoll(selectedRecording.value.id);+ const recordingId = fileItem.recordingId;+ if (!recordingId) {+ console.error("Cannot poll status without recording ID for", fileItem.file.name);+ fileItem.status = 'failed';+ fileItem.error = 'Internal error: Missing recording ID for polling.';+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ nextTick(startProcessingQueue);+ return;}- } catch (error) {- console.error('Save Speaker Names Error:', error);- setGlobalError(`Failed to save speaker names: ${error.message}`);- }- };+ processingMessage.value = 'Waiting for transcription...';+ processingProgress.value = 40;- const highlightSpeakerInTranscript = (speakerId) => {- highlightedSpeaker.value = speakerId;- // Scroll to the first instance in the transcript when a speaker is focused- if (speakerId) {- nextTick(() => {- const modalTranscript = document.querySelector('div.speaker-modal-transcript');- if (modalTranscript) {- const firstInstance = modalTranscript.querySelector(`[data-speaker-id="${speakerId}"]`);- if (firstInstance) {- firstInstance.scrollIntoView({ behavior: 'smooth', block: 'center' });+ pollInterval.value = setInterval(async () => {+ if (!currentlyProcessingFile.value || currentlyProcessingFile.value.clientId !== fileItem.clientId || ['completed', 'failed'].includes(fileItem.status)) {+ console.log(`Polling stopped for ${fileItem.clientId} as it's no longer active or finished.`);+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ if (currentlyProcessingFile.value && currentlyProcessingFile.value.clientId === fileItem.clientId) {+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();}+ return;}- });- }- };- const clearSpeakerHighlight = () => {- highlightedSpeaker.value = null;- };-- const autoIdentifySpeakers = async () => {- if (!selectedRecording.value) {- showToast('No recording selected.', 'fa-exclamation-circle');- return;- }-- isAutoIdentifying.value = true;- showToast('Starting automatic speaker identification...', 'fa-magic');-- try {- const response = await fetch(`/recording/${selectedRecording.value.id}/auto_identify_speakers`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- current_speaker_map: speakerMap.value- })- });-- const data = await response.json();- if (!response.ok) {- throw new Error(data.error || 'Unknown error occurred during auto-identification.');- }-- // Check if there's a message (e.g., all speakers already identified)- if (data.message) {- showToast(data.message, 'fa-info-circle');- return;- }-- // Update speakerMap with the identified names (only for unidentified speakers)- let identifiedCount = 0;- for (const speakerId in data.speaker_map) {- const identifiedName = data.speaker_map[speakerId];- if (speakerMap.value[speakerId] && identifiedName && identifiedName.trim() !== '') {- speakerMap.value[speakerId].name = identifiedName;- identifiedCount++;- }- }-- if (identifiedCount > 0) {- showToast(`${identifiedCount} speaker(s) identified successfully!`, 'fa-check-circle');- } else {- showToast('No speakers could be identified from the context.', 'fa-info-circle');- }-- } catch (error) {- console.error('Auto Identify Speakers Error:', error);- showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 5000);- } finally {- isAutoIdentifying.value = false;- }- };+ try {+ console.log(`Polling status for recording ID: ${recordingId} (${fileItem.file.name})`);+ const response = await fetch(`/status/${recordingId}`);+ if (!response.ok) throw new Error(`Status check failed with status ${response.status}`);- const performReprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {- if (!recordingId) {- setGlobalError('No recording ID provided for reprocessing.');- return;- }-- try {- const payload = {- language: language,- min_speakers: minSpeakers,- max_speakers: maxSpeakers- };+ const data = await response.json();+ const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);- const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- });-- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to start transcription reprocessing');-- // Update the recording in the UI- const index = recordings.value.findIndex(r => r.id === recordingId);- if (index !== -1) {- recordings.value[index] = data.recording;- }-- // Update selected recording if it's the one being reprocessed- if (selectedRecording.value?.id === recordingId) {- selectedRecording.value = data.recording;+ if (galleryIndex !== -1) {+ recordings.value[galleryIndex] = data;+ if(selectedRecording.value?.id === recordingId) {+ selectedRecording.value = data;+ }+ }++ fileItem.status = data.status;+ fileItem.file.name = data.title || data.original_filename;++ if (data.status === 'COMPLETED') {+ console.log(`Processing COMPLETED for ${fileItem.file.name} (ID: ${recordingId})`);+ processingMessage.value = 'Processing complete!';+ processingProgress.value = 100;+ fileItem.status = 'completed';+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();++ } else if (data.status === 'FAILED') {+ console.log(`Processing FAILED for ${fileItem.file.name} (ID: ${recordingId})`);+ processingMessage.value = 'Processing failed.';+ processingProgress.value = 100;+ fileItem.status = 'failed';+ fileItem.error = data.transcription || data.summary || 'Processing failed on server.';+ setGlobalError(`Processing failed for "${data.title || fileItem.file.name}".`);+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();++ } else if (data.status === 'PROCESSING') {+ processingMessage.value = 'Transcription in progress...';+ processingProgress.value = Math.round(Math.min(65, processingProgress.value + Math.random() * 5));+ } else if (data.status === 'SUMMARIZING') {+ processingMessage.value = 'Generating title & summary...';+ processingProgress.value = Math.round(Math.min(95, processingProgress.value + Math.random() * 5));+ } else {+ processingMessage.value = 'Waiting in queue...';+ processingProgress.value = 45;+ }+ } catch (error) {+ console.error(`Polling Error for ${fileItem.file.name} (ID: ${recordingId}):`, error);+ fileItem.status = 'failed';+ fileItem.error = `Error checking status: ${error.message}`;+ setGlobalError(`Error checking status for "${fileItem.file.name}": ${error.message}.`);+ const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);+ if (galleryIndex !== -1) recordings.value[galleryIndex].status = 'FAILED';++ clearInterval(pollInterval.value);+ pollInterval.value = null;+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();+ }+ }, 5000);+ };++ // --- Data Loading ---+ const loadRecordings = async () => {+ globalError.value = null;+ isLoadingRecordings.value = true;+ 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;++ const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');+ if (lastRecordingId) {+ const recordingToSelect = recordings.value.find(r => r.id == lastRecordingId);+ if (recordingToSelect) {+ selectRecording(recordingToSelect);+ }+ }++ const incompleteRecordings = recordings.value.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));+ if (incompleteRecordings.length > 0 && !isProcessingActive.value) {+ console.warn(`Found ${incompleteRecordings.length} incomplete recording(s) on load.`);+ for (const recording of incompleteRecordings) {+ let queueItem = uploadQueue.value.find(item => item.recordingId === recording.id);+ if (!queueItem) {+ queueItem = {+ file: { name: recording.title || `Recording ${recording.id}`, size: recording.file_size },+ status: 'queued',+ recordingId: recording.id,+ clientId: `reload-${recording.id}`,+ error: null+ };+ uploadQueue.value.unshift(queueItem);+ if (!isProcessingActive.value) {+ startProcessingQueue();+ }+ }+ }+ }++ } catch (error) {+ console.error('Load Recordings Error:', error);+ setGlobalError(`Failed to load recordings: ${error.message}`);+ recordings.value = [];+ } finally {+ isLoadingRecordings.value = false;}+ };++ // --- Audio Recording ---+ const startRecording = async (mode = 'microphone') => {+ recordingMode.value = mode;- showToast('Transcription reprocessing started', 'fa-sync-alt');+ try {+ // Reset state+ audioChunks.value = [];+ audioBlobURL.value = null;+ recordingNotes.value = '';+ activeStreams.value = [];++ let combinedStream = null;+ let micStream = null;+ let systemStream = null;++ // Get microphone stream if needed+ if (mode === 'microphone' || mode === 'both') {+ if (!canRecordAudio.value) {+ throw new Error('Microphone recording is not supported by your browser or permission was denied.');+ }+ micStream = await navigator.mediaDevices.getUserMedia({ audio: true });+ activeStreams.value.push(micStream);+ showToast('Microphone access granted', 'fa-microphone');+ }++ // Get system audio stream if needed+ if (mode === 'system' || mode === 'both') {+ if (!canRecordSystemAudio.value) {+ throw new Error('System audio recording is not supported by your browser.');+ }+ try {+ systemStream = await navigator.mediaDevices.getDisplayMedia({+ audio: true,+ video: true // Request video to enable system audio sharing prompt+ });++ // Check if the user actually granted audio permission+ if (systemStream.getAudioTracks().length === 0) {+ // Stop the video track if it exists, since we didn't get audio+ systemStream.getVideoTracks().forEach(track => track.stop());+ throw new Error('System audio permission was not granted. Please ensure you check the "Share system audio" box.');+ }++ activeStreams.value.push(systemStream);+ showToast('System audio access granted', 'fa-desktop');+ } catch (err) {+ if (mode === 'system') {+ throw err; // Re-throw the original error to be caught by the outer handler+ } else {+ // For 'both' mode, fall back to microphone only+ showToast('System audio denied, using microphone only', 'fa-exclamation-triangle');+ mode = 'microphone';+ systemStream = null; // Make sure systemStream is null so it's not used later+ }+ }+ }++ // Combine streams if we have both+ if (micStream && systemStream) {+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();++ const micSource = audioContext.value.createMediaStreamSource(micStream);+ const systemSource = audioContext.value.createMediaStreamSource(systemStream);+ const destination = audioContext.value.createMediaStreamDestination();++ micSource.connect(destination);+ systemSource.connect(destination);++ // The destination stream contains the mixed audio+ combinedStream = destination.stream;++ // We also need to add the video track from the system stream to keep the browser's "sharing this screen" UI active.+ // This video track will not be recorded.+ const videoTrack = systemStream.getVideoTracks()[0];+ if (videoTrack) {+ combinedStream.addTrack(videoTrack);+ }++ showToast('Recording both microphone and system audio', 'fa-microphone');+ } else if (systemStream) {+ combinedStream = systemStream;+ showToast('Recording system audio only', 'fa-desktop');+ } else if (micStream) {+ combinedStream = micStream;+ showToast('Recording microphone only', 'fa-microphone');+ } else {+ throw new Error('No audio streams available for recording.');+ }++ // Setup MediaRecorder+ mediaRecorder.value = new MediaRecorder(combinedStream);+ mediaRecorder.value.ondataavailable = event => audioChunks.value.push(event.data);+ mediaRecorder.value.onstop = () => {+ const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' });+ audioBlobURL.value = URL.createObjectURL(audioBlob);++ // Stop all active streams+ activeStreams.value.forEach(stream => {+ stream.getTracks().forEach(track => track.stop());+ });+ activeStreams.value = [];++ if (audioContext.value) {+ audioContext.value.close().catch(e => console.error("Error closing AudioContext:", e));+ audioContext.value = null;+ }+ cancelAnimationFrame(animationFrameId.value);+ clearInterval(recordingInterval.value);+ };++ // --- Visualizer Setup ---+ if (!audioContext.value) {+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();+ }++ if (mode === 'both' && micStream && systemStream) {+ // Dual visualizer setup+ micAnalyser.value = audioContext.value.createAnalyser();+ micAnalyser.value.fftSize = 256;+ const micSource = audioContext.value.createMediaStreamSource(micStream);+ micSource.connect(micAnalyser.value);++ systemAnalyser.value = audioContext.value.createAnalyser();+ systemAnalyser.value.fftSize = 256;+ const systemSource = audioContext.value.createMediaStreamSource(systemStream);+ systemSource.connect(systemAnalyser.value);++ } else {+ // Single visualizer setup+ const visualizerStream = micStream || systemStream;+ if (visualizerStream) {+ analyser.value = audioContext.value.createAnalyser();+ analyser.value.fftSize = 256;+ const source = audioContext.value.createMediaStreamSource(visualizerStream);+ source.connect(analyser.value);+ }+ }++ // Start recording and timer+ mediaRecorder.value.start();+ isRecording.value = true;+ recordingTime.value = 0;+ recordingInterval.value = setInterval(() => recordingTime.value++, 1000);++ // Switch to recording view+ currentView.value = 'recording';++ // Start visualizer(s)+ drawVisualizers();++ setGlobalError(null);+ } catch (err) {+ console.error("Error starting recording:", err);+ setGlobalError(`Could not start recording: ${err.message}`);+ isRecording.value = false;++ // Clean up any streams that were created+ activeStreams.value.forEach(stream => {+ stream.getTracks().forEach(track => track.stop());+ });+ activeStreams.value = [];+ }+ };++ const stopRecording = () => {+ if (mediaRecorder.value && isRecording.value) {+ mediaRecorder.value.stop();+ isRecording.value = false;+ cancelAnimationFrame(animationFrameId.value);+ animationFrameId.value = null;+ }+ };++ const uploadRecordedAudio = () => {+ if (!audioBlobURL.value) {+ setGlobalError("No recorded audio to upload.");+ return;+ }+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');+ const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });++ // Pass notes along with the file+ addFilesToQueue([{ file: recordedFile, notes: recordingNotes.value }]);+ discardRecording();- // Start polling for status updates- startReprocessingPoll(recordingId);+ // Switch back to upload view+ currentView.value = 'upload';+ };++ const discardRecording = () => {+ if (audioBlobURL.value) {+ URL.revokeObjectURL(audioBlobURL.value);+ }+ audioBlobURL.value = null;+ audioChunks.value = [];+ isRecording.value = false;+ recordingTime.value = 0;+ if (recordingInterval.value) clearInterval(recordingInterval.value);+ recordingNotes.value = '';+ };++ const drawSingleVisualizer = (analyserNode, canvasElement) => {+ if (!analyserNode || !canvasElement) return;++ const bufferLength = analyserNode.frequencyBinCount;+ const dataArray = new Uint8Array(bufferLength);+ analyserNode.getByteFrequencyData(dataArray);++ const canvasCtx = canvasElement.getContext('2d');+ const WIDTH = canvasElement.width;+ const HEIGHT = canvasElement.height;++ canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);++ const barWidth = (WIDTH / bufferLength) * 1.5;+ let barHeight;+ let x = 0;- } catch (error) {- console.error('Reprocess Transcription Error:', error);- setGlobalError(`Failed to start transcription reprocessing: ${error.message}`);- }- };-- const performReprocessSummary = async (recordingId) => {- if (!recordingId) {- setGlobalError('No recording ID provided for reprocessing.');- return;- }-- try {- const response = await fetch(`/recording/${recordingId}/reprocess_summary`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' }- });+ const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-accent').trim();+ const gradient = canvasCtx.createLinearGradient(0, 0, 0, HEIGHT);+ gradient.addColorStop(0, themeColor);+ gradient.addColorStop(1, 'rgba(255, 255, 255, 0.1)');++ for (let i = 0; i < bufferLength; i++) {+ barHeight = dataArray[i] / 2.5;+ canvasCtx.fillStyle = gradient;+ canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);+ x += barWidth + 2;+ }+ };++ const drawVisualizers = () => {+ if (!isRecording.value) {+ if (animationFrameId.value) {+ cancelAnimationFrame(animationFrameId.value);+ animationFrameId.value = null;+ }+ return;+ }++ animationFrameId.value = requestAnimationFrame(drawVisualizers);++ if (recordingMode.value === 'both') {+ drawSingleVisualizer(micAnalyser.value, micVisualizer.value);+ drawSingleVisualizer(systemAnalyser.value, systemVisualizer.value);+ } else {+ drawSingleVisualizer(analyser.value, visualizer.value);+ }+ };++ // --- Recording Management ---+ const saveMetadata = async (recordingDataToSave) => {+ globalError.value = null;+ if (!recordingDataToSave || !recordingDataToSave.id) return null;+ console.log('Saving metadata for:', recordingDataToSave.id);+ try {+ const payload = {+ id: recordingDataToSave.id,+ title: recordingDataToSave.title,+ participants: recordingDataToSave.participants,+ notes: recordingDataToSave.notes,+ summary: recordingDataToSave.summary,+ meeting_date: recordingDataToSave.meeting_date+ };+ const response = await fetch('/save', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ });+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to save metadata');++ console.log('Save successful:', data.recording.id);+ const index = recordings.value.findIndex(r => r.id === data.recording.id);+ if (index !== -1) {+ recordings.value[index].title = payload.title;+ recordings.value[index].participants = payload.participants;+ recordings.value[index].notes = payload.notes;+ recordings.value[index].notes_html = data.recording.notes_html;+ recordings.value[index].summary = payload.summary;+ recordings.value[index].summary_html = data.recording.summary_html;+ recordings.value[index].meeting_date = payload.meeting_date;+ }+ if (selectedRecording.value?.id === data.recording.id) {+ selectedRecording.value.title = payload.title;+ selectedRecording.value.participants = payload.participants;+ selectedRecording.value.notes = payload.notes;+ selectedRecording.value.notes_html = data.recording.notes_html;+ selectedRecording.value.summary = payload.summary;+ selectedRecording.value.summary_html = data.recording.summary_html;+ selectedRecording.value.meeting_date = payload.meeting_date;+ }+ return data.recording;+ } catch (error) {+ console.error('Save Metadata Error:', error);+ setGlobalError(`Save failed: ${error.message}`);+ return null;+ }+ };++ const editRecording = (recording) => {+ editingRecording.value = JSON.parse(JSON.stringify(recording));+ showEditModal.value = true;+ };++ const cancelEdit = () => {+ showEditModal.value = false;+ editingRecording.value = null;+ };++ const saveEdit = async () => {+ const success = await saveMetadata(editingRecording.value);+ if (success) {+ cancelEdit();+ }+ };++ 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;+ const titleToDelete = recordingToDelete.value.title;+ 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');++ recordings.value = recordings.value.filter(r => r.id !== idToDelete);++ const queueIndex = uploadQueue.value.findIndex(item => item.recordingId === idToDelete);+ if (queueIndex !== -1) {+ const deletedItem = uploadQueue.value.splice(queueIndex, 1)[0];+ console.log(`Removed item ${deletedItem.clientId} from queue.`);+ if (currentlyProcessingFile.value?.clientId === deletedItem.clientId) {+ console.log(`Deleting currently processing file: ${titleToDelete}. Stopping poll and moving to next.`);+ clearInterval(pollInterval.value);+ pollInterval.value = null;+ resetCurrentFileProcessingState();+ isProcessingActive.value = false;+ await nextTick();+ startProcessingQueue();+ }+ }++ if (selectedRecording.value?.id === idToDelete) selectedRecording.value = null;+ cancelDelete();+ console.log(`Successfully deleted recording ${idToDelete} (${titleToDelete})`);++ } catch (error) {+ console.error('Delete Error:', error);+ setGlobalError(`Failed to delete recording "${titleToDelete}": ${error.message}`);+ cancelDelete();+ }+ };++ // --- Inline Editing ---+ const toggleEditParticipants = () => {+ editingParticipants.value = !editingParticipants.value;+ if (!editingParticipants.value) {+ saveInlineEdit('participants');+ }+ };++ const toggleEditMeetingDate = () => {+ editingMeetingDate.value = !editingMeetingDate.value;+ if (!editingMeetingDate.value) {+ saveInlineEdit('meeting_date');+ }+ };++ const toggleEditSummary = () => {+ editingSummary.value = !editingSummary.value;+ if (editingSummary.value) {+ nextTick(() => {+ initializeSummaryMarkdownEditor();+ });+ }+ };++ const cancelEditSummary = () => {+ if (summaryMarkdownEditorInstance.value) {+ summaryMarkdownEditorInstance.value.toTextArea();+ summaryMarkdownEditorInstance.value = null;+ }+ editingSummary.value = false;+ };++ const saveEditSummary = async () => {+ if (summaryMarkdownEditorInstance.value) {+ selectedRecording.value.summary = summaryMarkdownEditorInstance.value.value();+ summaryMarkdownEditorInstance.value.toTextArea();+ summaryMarkdownEditorInstance.value = null;+ }+ editingSummary.value = false;+ await saveInlineEdit('summary');+ };++ const toggleEditNotes = () => {+ editingNotes.value = !editingNotes.value;+ if (editingNotes.value) {+ // Initialize markdown editor when entering edit mode+ nextTick(() => {+ initializeMarkdownEditor();+ });+ }+ };++ const cancelEditNotes = () => {+ if (markdownEditorInstance.value) {+ markdownEditorInstance.value.toTextArea();+ markdownEditorInstance.value = null;+ }+ editingNotes.value = false;+ // Reset notes to original value if needed+ if (selectedRecording.value) {+ // You might want to store the original value before editing+ }+ };++ const saveEditNotes = async () => {+ if (markdownEditorInstance.value) {+ // Get the markdown content from the editor+ selectedRecording.value.notes = markdownEditorInstance.value.value();+ markdownEditorInstance.value.toTextArea();+ markdownEditorInstance.value = null;+ }+ editingNotes.value = false;+ await saveInlineEdit('notes');+ };++ const initializeMarkdownEditor = () => {+ if (!notesMarkdownEditor.value) return;- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to start summary reprocessing');+ try {+ markdownEditorInstance.value = new EasyMDE({+ element: notesMarkdownEditor.value,+ spellChecker: false,+ autofocus: true,+ placeholder: "Enter notes in Markdown format...",+ status: false,+ toolbar: [+ "bold", "italic", "heading", "|",+ "quote", "unordered-list", "ordered-list", "|",+ "link", "image", "|",+ "preview", "side-by-side", "fullscreen", "|",+ "guide"+ ],+ previewClass: ["editor-preview", "notes-preview"],+ theme: isDarkMode.value ? "dark" : "light"+ });+ } catch (error) {+ console.error('Failed to initialize markdown editor:', error);+ // Fallback to regular textarea editing+ editingNotes.value = true;+ }+ };++ const initializeRecordingMarkdownEditor = () => {+ if (!recordingNotesEditor.value) {+ console.log('Recording notes editor ref not found');+ return;+ }- // Update the recording in the UI- const index = recordings.value.findIndex(r => r.id === recordingId);- if (index !== -1) {- recordings.value[index] = data.recording;+ // Check if EasyMDE is available+ if (typeof EasyMDE === 'undefined') {+ console.error('EasyMDE is not loaded');+ return;}- // Update selected recording if it's the one being reprocessed- if (selectedRecording.value?.id === recordingId) {- selectedRecording.value = data.recording;+ // Clean up existing instance if any+ if (recordingMarkdownEditorInstance.value) {+ recordingMarkdownEditorInstance.value.toTextArea();+ recordingMarkdownEditorInstance.value = null;}- showToast('Summary reprocessing started', 'fa-sync-alt');+ try {+ console.log('Initializing recording markdown editor');+ recordingMarkdownEditorInstance.value = new EasyMDE({+ element: recordingNotesEditor.value,+ spellChecker: false,+ autofocus: false,+ placeholder: "Type your notes in Markdown format...",+ status: false,+ toolbar: [+ "bold", "italic", "heading", "|",+ "quote", "unordered-list", "ordered-list", "|",+ "link", "|",+ "preview", "guide"+ ],+ previewClass: ["editor-preview", "notes-preview"],+ theme: isDarkMode.value ? "dark" : "light",+ initialValue: recordingNotes.value || ""+ });++ // Sync changes back to the reactive variable+ recordingMarkdownEditorInstance.value.codemirror.on('change', () => {+ recordingNotes.value = recordingMarkdownEditorInstance.value.value();+ });++ console.log('Recording markdown editor initialized successfully');+ } catch (error) {+ console.error('Failed to initialize recording markdown editor:', error);+ // Keep as regular textarea if EasyMDE fails+ }+ };++ const toggleTranscriptionViewMode = () => {+ transcriptionViewMode.value = transcriptionViewMode.value === 'simple' ? 'bubble' : 'simple';+ localStorage.setItem('transcriptionViewMode', transcriptionViewMode.value);+ };++ const saveInlineEdit = async (field) => {+ if (!selectedRecording.value) return;++ const fullPayload = {+ id: selectedRecording.value.id,+ title: selectedRecording.value.title,+ participants: selectedRecording.value.participants,+ notes: selectedRecording.value.notes,+ summary: selectedRecording.value.summary,+ meeting_date: selectedRecording.value.meeting_date+ };++ try {+ const updatedRecording = await saveMetadata(fullPayload);+ if (updatedRecording) {+ if (field === 'notes') {+ selectedRecording.value.notes_html = updatedRecording.notes_html;+ } else if (field === 'summary') {+ selectedRecording.value.summary_html = updatedRecording.summary_html;+ }++ switch(field) {+ case 'participants':+ editingParticipants.value = false;+ break;+ case 'meeting_date':+ editingMeetingDate.value = false;+ break;+ case 'summary':+ editingSummary.value = false;+ break;+ case 'notes':+ editingNotes.value = false;+ break;+ }+ showToast(`${field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ')} updated successfully`);+ }+ } catch (error) {+ console.error(`Save ${field} Error:`, error);+ setGlobalError(`Failed to save ${field}: ${error.message}`);+ }+ };++ // --- Chat Functionality ---+ const sendChatMessage = async () => {+ if (!chatInput.value.trim() || isChatLoading.value || !selectedRecording.value || selectedRecording.value.status !== 'COMPLETED') {+ return;+ }++ const message = chatInput.value.trim();++ if (!Array.isArray(chatMessages.value)) {+ chatMessages.value = [];+ }++ chatMessages.value.push({ role: 'user', content: message });+ chatInput.value = '';+ isChatLoading.value = true;++ await nextTick();+ if (chatMessagesRef.value) {+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;+ }++ let assistantMessage = null;++ try {+ const messageHistory = chatMessages.value+ .slice(0, -1)+ .map(msg => ({ role: msg.role, content: msg.content }));++ const response = await fetch('/chat', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ recording_id: selectedRecording.value.id,+ message: message,+ message_history: messageHistory+ })+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to get chat response');+ }++ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';++ const processStream = async () => {+ let isFirstChunk = true;+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop();++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ const jsonStr = line.substring(6);+ if (jsonStr) {+ try {+ const data = JSON.parse(jsonStr);+ if (data.delta) {+ if (isFirstChunk) {+ isChatLoading.value = false;+ assistantMessage = reactive({ role: 'assistant', content: '', html: '' });+ chatMessages.value.push(assistantMessage);+ isFirstChunk = false;+ }+ assistantMessage.content += data.delta;+ assistantMessage.html = marked.parse(assistantMessage.content);++ await nextTick();+ if (chatMessagesRef.value) {+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;+ }+ }+ if (data.end_of_stream) {+ return;+ }+ if (data.error) {+ throw new Error(data.error);+ }+ } catch (e) {+ console.error('Error parsing stream data:', e);+ }+ }+ }+ }+ }+ };++ await processStream();++ } catch (error) {+ console.error('Chat Error:', error);+ if (assistantMessage) {+ assistantMessage.content = `Error: ${error.message}`;+ assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;+ } else {+ chatMessages.value.push({ role: 'assistant', content: `Error: ${error.message}`, html: `<span class="text-red-500">Error: ${error.message}</span>` });+ }+ } finally {+ isChatLoading.value = false;+ await nextTick();+ if (chatMessagesRef.value) {+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;+ }+ }+ };++ // --- Column Resizing ---+ const startColumnResize = (event) => {+ isResizing.value = true;+ const startX = event.clientX;+ const startLeftWidth = leftColumnWidth.value;++ const handleMouseMove = (e) => {+ if (!isResizing.value) return;++ const container = document.getElementById('mainContentColumns');+ if (!container) return;++ const containerRect = container.getBoundingClientRect();+ const deltaX = e.clientX - startX;+ const containerWidth = containerRect.width;+ const deltaPercent = (deltaX / containerWidth) * 100;++ let newLeftWidth = startLeftWidth + deltaPercent;+ newLeftWidth = Math.max(20, Math.min(80, newLeftWidth)); // Constrain between 20% and 80%++ leftColumnWidth.value = newLeftWidth;+ rightColumnWidth.value = 100 - newLeftWidth;+ };- // Start polling for status updates- startReprocessingPoll(recordingId);+ const handleMouseUp = () => {+ isResizing.value = false;+ document.removeEventListener('mousemove', handleMouseMove);+ document.removeEventListener('mouseup', handleMouseUp);++ // Save to localStorage+ localStorage.setItem('transcriptColumnWidth', leftColumnWidth.value);+ localStorage.setItem('summaryColumnWidth', rightColumnWidth.value);+ };- } catch (error) {- console.error('Reprocess Summary Error:', error);- setGlobalError(`Failed to start summary reprocessing: ${error.message}`);- }- };-- // Polling for reprocessing status updates- const reprocessingPolls = ref(new Map()); // Track active polls by recording ID-- const startReprocessingPoll = (recordingId) => {- // Clear any existing poll for this recording- if (reprocessingPolls.value.has(recordingId)) {- clearInterval(reprocessingPolls.value.get(recordingId));- }-- console.log(`Starting reprocessing poll for recording ${recordingId}`);-- const pollInterval = setInterval(async () => {+ document.addEventListener('mousemove', handleMouseMove);+ document.addEventListener('mouseup', handleMouseUp);+ event.preventDefault();+ };++ // --- Chat Input Handling ---+ const handleChatKeydown = (event) => {+ if (event.key === 'Enter') {+ if (event.ctrlKey || event.shiftKey) {+ // Ctrl+Enter or Shift+Enter: add new line (default behavior)+ return;+ } else {+ // Enter: send message+ event.preventDefault();+ sendChatMessage();+ }+ }+ };++ // --- Audio Player ---+ const seekAudio = (time, context = 'main') => {+ let audioPlayer = null;+ if (context === 'modal') {+ // The audio player in the modal has the class directly on the audio element+ audioPlayer = document.querySelector('audio.speaker-modal-transcript');+ } else {+ audioPlayer = document.querySelector('.main-content-area audio');+ }++ if (audioPlayer) {+ const wasPlaying = !audioPlayer.paused;+ audioPlayer.currentTime = time;+ if (wasPlaying) {+ audioPlayer.play();+ }+ } else {+ console.warn(`Audio player not found for context: ${context}`);+ // Fallback to old method if new one fails+ const oldPlayer = document.querySelector('audio');+ if(oldPlayer) {+ const wasPlaying = !oldPlayer.paused;+ oldPlayer.currentTime = time;+ if (wasPlaying) {+ oldPlayer.play();+ }+ }+ }+ };++ const seekAudioFromEvent = (event) => {+ const segmentElement = event.target.closest('[data-start-time]');+ if (!segmentElement) return;++ const time = parseFloat(segmentElement.dataset.startTime);+ if (isNaN(time)) return;++ // Determine context by checking if we're inside the speaker modal+ const isInSpeakerModal = event.target.closest('.speaker-modal-transcript') !== null;+ const context = isInSpeakerModal ? 'modal' : 'main';++ seekAudio(time, context);+ };++ const onPlayerVolumeChange = (event) => {+ const newVolume = event.target.volume;+ playerVolume.value = newVolume;+ localStorage.setItem('playerVolume', newVolume);+ };++ // --- Toast Notifications ---+ const showToast = (message, icon = 'fa-check-circle', duration = 2000) => {+ const toastContainer = document.getElementById('toastContainer');++ const toast = document.createElement('div');+ toast.className = 'toast';+ toast.innerHTML = `<i class="fas ${icon}"></i> ${message}`;++ toastContainer.appendChild(toast);++ setTimeout(() => {+ toast.classList.add('show');+ }, 10);++ setTimeout(() => {+ toast.classList.remove('show');+ setTimeout(() => {+ toastContainer.removeChild(toast);+ }, 300);+ }, duration);+ };++ const animateCopyButton = (button) => {+ button.classList.add('copy-success');++ const originalContent = button.innerHTML;+ button.innerHTML = '<i class="fas fa-check"></i>';++ setTimeout(() => {+ button.classList.remove('copy-success');+ button.innerHTML = originalContent;+ }, 1500);+ };++ const copyMessage = (text, event) => {+ const button = event.currentTarget;++ if (navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.writeText(text)+ .then(() => {+ showToast('Copied to clipboard!');+ animateCopyButton(button);+ })+ .catch(err => {+ console.error('Copy failed:', err);+ showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');+ fallbackCopyTextToClipboard(text, button);+ });+ } else {+ fallbackCopyTextToClipboard(text, button);+ }+ };++ const fallbackCopyTextToClipboard = (text, button = null) => {try {- const response = await fetch(`/status/${recordingId}`);- if (!response.ok) {- console.error(`Status check failed for recording ${recordingId}`);- stopReprocessingPoll(recordingId);- return;- }+ const textArea = document.createElement("textarea");+ textArea.value = text;- const data = await response.json();+ textArea.style.position = "fixed";+ textArea.style.left = "-999999px";+ textArea.style.top = "-999999px";+ document.body.appendChild(textArea);- // Update the recording in the UI- const index = recordings.value.findIndex(r => r.id === recordingId);- if (index !== -1) {- recordings.value[index] = data;- }+ textArea.focus();+ textArea.select();+ const successful = document.execCommand('copy');- // Update selected recording if it's the one being reprocessed- if (selectedRecording.value?.id === recordingId) {- selectedRecording.value = data;- }+ document.body.removeChild(textArea);- // Stop polling if processing is complete- if (data.status === 'COMPLETED' || data.status === 'FAILED') {- console.log(`Reprocessing ${data.status.toLowerCase()} for recording ${recordingId}`);- stopReprocessingPoll(recordingId);-- if (data.status === 'COMPLETED') {- showToast('Reprocessing completed successfully', 'fa-check-circle');+ if (successful) {+ showToast('Copied to clipboard!');+ if (button) animateCopyButton(button);+ } else {+ showToast('Copy failed. Your browser may not support this feature.', 'fa-exclamation-circle');+ }+ } catch (err) {+ console.error('Fallback copy failed:', err);+ showToast('Unable to copy: ' + err.message, 'fa-exclamation-circle');+ }+ };++ const copyTranscription = (event) => {+ if (!selectedRecording.value || !selectedRecording.value.transcription) {+ showToast('No transcription available to copy.', 'fa-exclamation-circle');+ return;+ }++ const button = event.currentTarget;+ let textToCopy = '';++ try {+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);+ if (Array.isArray(transcriptionData)) {+ const wasDiarized = transcriptionData.some(segment => segment.speaker);+ if (wasDiarized) {+ textToCopy = transcriptionData.map(segment => {+ const speakerName = segment.speaker;+ return `[${speakerName}]: ${segment.sentence}`;+ }).join('\n');} else {- showToast('Reprocessing failed', 'fa-exclamation-circle');+ textToCopy = transcriptionData.map(segment => segment.sentence).join('\n');}+ } else {+ textToCopy = selectedRecording.value.transcription;}-- } catch (error) {- console.error(`Error polling status for recording ${recordingId}:`, error);- stopReprocessingPoll(recordingId);+ } catch (e) {+ textToCopy = selectedRecording.value.transcription;}- }, 3000); // Poll every 3 seconds-- reprocessingPolls.value.set(recordingId, pollInterval);- };-- const stopReprocessingPoll = (recordingId) => {- if (reprocessingPolls.value.has(recordingId)) {- clearInterval(reprocessingPolls.value.get(recordingId));- reprocessingPolls.value.delete(recordingId);- console.log(`Stopped reprocessing poll for recording ${recordingId}`);- }- };- const confirmReset = (recording) => {- recordingToReset.value = recording;- showResetModal.value = true;- };+ animateCopyButton(button);++ if (navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.writeText(textToCopy)+ .then(() => {+ showToast('Transcription copied to clipboard!');+ })+ .catch(err => {+ console.error('Copy failed:', err);+ showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');+ fallbackCopyTextToClipboard(textToCopy);+ });+ } else {+ fallbackCopyTextToClipboard(textToCopy);+ }+ };- const cancelReset = () => {- showResetModal.value = false;- recordingToReset.value = null;- };+ const copySummary = (event) => {+ if (!selectedRecording.value || !selectedRecording.value.summary) {+ showToast('No summary available to copy.', 'fa-exclamation-circle');+ return;+ }+ const button = event.currentTarget;+ const textToCopy = selectedRecording.value.summary;+ animateCopyButton(button);+ if (navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.writeText(textToCopy)+ .then(() => {+ showToast('Summary copied to clipboard!');+ })+ .catch(err => {+ console.error('Copy failed:', err);+ showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');+ fallbackCopyTextToClipboard(textToCopy);+ });+ } else {+ fallbackCopyTextToClipboard(textToCopy);+ }+ };- const executeReset = async () => {- if (!recordingToReset.value) return;- const recordingId = recordingToReset.value.id;-- // Close the modal first- cancelReset();+ const copyNotes = (event) => {+ if (!selectedRecording.value || !selectedRecording.value.notes) {+ showToast('No notes available to copy.', 'fa-exclamation-circle');+ return;+ }+ const button = event.currentTarget;+ const textToCopy = selectedRecording.value.notes;+ animateCopyButton(button);+ if (navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.writeText(textToCopy)+ .then(() => {+ showToast('Notes copied to clipboard!');+ })+ .catch(err => {+ console.error('Copy failed:', err);+ showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');+ fallbackCopyTextToClipboard(textToCopy);+ });+ } else {+ fallbackCopyTextToClipboard(textToCopy);+ }+ };++ const openShareModal = (recording) => {+ recordingToShare.value = recording;+ shareOptions.share_summary = true;+ shareOptions.share_notes = true;+ generatedShareLink.value = '';+ showShareModal.value = true;+ };++ const closeShareModal = () => {+ showShareModal.value = false;+ recordingToShare.value = null;+ };++ const createShare = async () => {+ if (!recordingToShare.value) return;+ try {+ const response = await fetch(`/api/recording/${recordingToShare.value.id}/share`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(shareOptions)+ });+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to create share link');+ generatedShareLink.value = data.share_url;+ showToast('Share link created successfully!', 'fa-check-circle');+ } catch (error) {+ setGlobalError(`Failed to create share link: ${error.message}`);+ }+ };- try {- const response = await fetch(`/recording/${recordingId}/reset_status`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' }+ const copyShareLink = () => {+ if (!generatedShareLink.value) return;+ navigator.clipboard.writeText(generatedShareLink.value).then(() => {+ showToast('Share link copied to clipboard!');});-- const data = await response.json();- if (!response.ok) throw new Error(data.error || 'Failed to reset status');-- // Update the recording in the UI- const index = recordings.value.findIndex(r => r.id === recordingId);- if (index !== -1) {- recordings.value[index] = data.recording;+ };++ const openSharesList = async () => {+ isLoadingShares.value = true;+ showSharesListModal.value = true;+ try {+ const response = await fetch('/api/shares');+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to load shared items');+ userShares.value = data;+ } catch (error) {+ setGlobalError(`Failed to load shared items: ${error.message}`);+ } finally {+ isLoadingShares.value = false;}-- // Update selected recording if it's the one being reset- if (selectedRecording.value?.id === recordingId) {- selectedRecording.value = data.recording;+ };++ const closeSharesList = () => {+ showSharesListModal.value = false;+ userShares.value = [];+ };++ const updateShare = async (share) => {+ try {+ const response = await fetch(`/api/share/${share.id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ share_summary: share.share_summary,+ share_notes: share.share_notes+ })+ });+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to update share');+ showToast('Share permissions updated.', 'fa-check-circle');+ } catch (error) {+ setGlobalError(`Failed to update share: ${error.message}`);}-- showToast('Recording status has been reset.', 'fa-check-circle');-- } catch (error) {- console.error('Reset Status Error:', error);- setGlobalError(`Failed to reset status: ${error.message}`);- }- };+ };- // --- Chat functionality ----- const showChat = ref(false);- const chatMessages = ref([]);- const chatInput = ref('');- const isChatLoading = ref(false);-- // Create a ref for the chat messages container- const chatMessagesRef = ref(null);-- const sendChatMessage = async () => {- if (!chatInput.value.trim() || isChatLoading.value || !selectedRecording.value || selectedRecording.value.status !== 'COMPLETED') {- return;- }-- const message = chatInput.value.trim();-- if (!Array.isArray(chatMessages.value)) {- chatMessages.value = [];- }-- chatMessages.value.push({ role: 'user', content: message });- chatInput.value = '';- isChatLoading.value = true;-- await nextTick();- if (chatMessagesRef.value) {- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;- }-- let assistantMessage = null;-- try {- const messageHistory = chatMessages.value- .slice(0, -1) // Exclude the new user message- .map(msg => ({ role: msg.role, content: msg.content }));-- const response = await fetch('/chat', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- recording_id: selectedRecording.value.id,- message: message,- message_history: messageHistory- })- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || 'Failed to get chat response');- }-- const reader = response.body.getReader();- const decoder = new TextDecoder();- let buffer = '';-- const processStream = async () => {- let isFirstChunk = true;- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const lines = buffer.split('\n');- buffer = lines.pop();-- for (const line of lines) {- if (line.startsWith('data: ')) {- const jsonStr = line.substring(6);- if (jsonStr) {- try {- const data = JSON.parse(jsonStr);- if (data.delta) {- if (isFirstChunk) {- isChatLoading.value = false;- assistantMessage = reactive({ role: 'assistant', content: '', html: '' });- chatMessages.value.push(assistantMessage);- isFirstChunk = false;- }- assistantMessage.content += data.delta;- assistantMessage.html = marked.parse(assistantMessage.content);-- await nextTick();- if (chatMessagesRef.value) {- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;- }- }- if (data.end_of_stream) {- return;- }- if (data.error) {- throw new Error(data.error);- }- } catch (e) {- console.error('Error parsing stream data:', e);- }- }- }+ const deleteShare = async (shareId) => {+ if (!confirm('Are you sure you want to delete this share? This will revoke access to the public link.')) return;+ try {+ const response = await fetch(`/api/share/${shareId}`, { method: 'DELETE' });+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to delete share');+ userShares.value = userShares.value.filter(s => s.id !== shareId);+ showToast('Share deleted successfully.', 'fa-check-circle');+ } catch (error) {+ setGlobalError(`Failed to delete share: ${error.message}`);+ }+ };++ // --- Watchers ---+ watch(uploadQueue, (newQueue, oldQueue) => {+ if (newQueue.length === 0 && oldQueue.length > 0 && !isProcessingActive.value) {+ console.log("Upload queue processing finished.");+ setTimeout(() => progressPopupMinimized.value = true, 1000);+ setTimeout(() => {+ if (completedInQueue.value === totalInQueue.value && !isProcessingActive.value) {+ progressPopupClosed.value = true;}- }- };-- await processStream();-- } catch (error) {- console.error('Chat Error:', error);- if (assistantMessage) {- assistantMessage.content = `Error: ${error.message}`;- assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;- } else {- chatMessages.value.push({ role: 'assistant', content: `Error: ${error.message}`, html: `<span class="text-red-500">Error: ${error.message}</span>` });+ }, 5000);}- } finally {- isChatLoading.value = false;- await nextTick();- if (chatMessagesRef.value) {- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;+ }, { deep: true });++ // Watch for changes to speakerMap to handle "This is Me" functionality+ watch(speakerMap, (newSpeakerMap) => {+ if (!newSpeakerMap) return;++ Object.keys(newSpeakerMap).forEach(speakerId => {+ const speakerData = newSpeakerMap[speakerId];+ if (speakerData.isMe && currentUserName.value && !speakerData.name) {+ // Automatically fill in the user's name when "This is Me" is checked+ speakerData.name = currentUserName.value;+ } else if (!speakerData.isMe && speakerData.name === currentUserName.value) {+ // Clear the name if "This is Me" is unchecked and the name matches the current user+ speakerData.name = '';+ }+ });+ }, { deep: true });++ watch(selectedRecording, (newVal, oldVal) => {+ if (newVal?.id !== oldVal?.id) {+ chatMessages.value = [];+ showChat.value = false;+ selectedTab.value = 'summary';++ editingParticipants.value = false;+ editingMeetingDate.value = false;+ editingSummary.value = false;+ editingNotes.value = false;}- }- };-- // Toast notification system- const showToast = (message, icon = 'fa-check-circle', duration = 2000) => {- const toastContainer = document.getElementById('toastContainer');-- // Create toast element- const toast = document.createElement('div');- toast.className = 'toast';- toast.innerHTML = `<i class="fas ${icon}"></i> ${message}`;-- // Add to container- toastContainer.appendChild(toast);-- // Trigger animation- setTimeout(() => {- toast.classList.add('show');- }, 10);-- // Remove after duration- setTimeout(() => {- toast.classList.remove('show');- setTimeout(() => {- toastContainer.removeChild(toast);- }, 300);- }, duration);- };-- // Add animation to copy button- const animateCopyButton = (button) => {- button.classList.add('copy-success');-- // Store original content- const originalContent = button.innerHTML;- button.innerHTML = '<i class="fas fa-check"></i>';-- setTimeout(() => {- button.classList.remove('copy-success');- button.innerHTML = originalContent;- }, 1500);- };-- const copyMessage = (text, event) => {- // Get the button that was clicked- const button = event.currentTarget;-- if (navigator.clipboard && window.isSecureContext) {- // Use clipboard API if available (secure context)- navigator.clipboard.writeText(text)- .then(() => {- showToast('Copied to clipboard!');- animateCopyButton(button);- })- .catch(err => {- console.error('Copy failed:', err);- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');- fallbackCopyTextToClipboard(text, button);+ });++ watch(currentView, (newView) => {+ if (newView === 'recording') {+ // Initialize recording markdown editor when switching to recording view+ nextTick(() => {+ initializeRecordingMarkdownEditor();});- } else {- // Fallback for non-secure contexts- fallbackCopyTextToClipboard(text, button);- }- };-- // Fallback method using document.execCommand- const fallbackCopyTextToClipboard = (text, button = null) => {- try {- const textArea = document.createElement("textarea");- textArea.value = text;-- // Make the textarea out of viewport- textArea.style.position = "fixed";- textArea.style.left = "-999999px";- textArea.style.top = "-999999px";- document.body.appendChild(textArea);-- // Select and copy- textArea.focus();- textArea.select();- const successful = document.execCommand('copy');-- // Clean up- document.body.removeChild(textArea);-- if (successful) {- showToast('Copied to clipboard!');- if (button) animateCopyButton(button);} else {- showToast('Copy failed. Your browser may not support this feature.', 'fa-exclamation-circle');+ // Clean up recording markdown editor when leaving recording view+ if (recordingMarkdownEditorInstance.value) {+ recordingMarkdownEditorInstance.value.toTextArea();+ recordingMarkdownEditorInstance.value = null;+ }}- } catch (err) {- console.error('Fallback copy failed:', err);- showToast('Unable to copy: ' + err.message, 'fa-exclamation-circle');- }- };-- const copyTranscription = (event) => {- if (!selectedRecording.value || !selectedRecording.value.transcription) {- showToast('No transcription available to copy.', 'fa-exclamation-circle');- return;- }-- const button = event.currentTarget;- let textToCopy = '';-- try {- const transcriptionData = JSON.parse(selectedRecording.value.transcription);- if (Array.isArray(transcriptionData)) {- const wasDiarized = transcriptionData.some(segment => segment.speaker);- if (wasDiarized) {- textToCopy = transcriptionData.map(segment => {- const speakerName = speakerMap.value[segment.speaker]?.name || segment.speaker;- return `[${speakerName}]: ${segment.sentence}`;- }).join('\n');+ });++ watch(playerVolume, (newVolume) => {+ const audioElements = document.querySelectorAll('audio');+ audioElements.forEach(audio => {+ if (audio.volume !== newVolume) {+ audio.volume = newVolume;+ }+ });+ });++ // --- Configuration Loading ---+ const loadConfiguration = async () => {+ try {+ const response = await fetch('/api/config');+ if (response.ok) {+ const config = await response.json();+ maxFileSizeMB.value = config.max_file_size_mb || 250;+ console.log(`Loaded max file size: ${maxFileSizeMB.value} MB`);} else {- textToCopy = transcriptionData.map(segment => segment.sentence).join('\n');+ console.warn('Failed to load configuration, using default values');}- } else {- textToCopy = selectedRecording.value.transcription;+ } catch (error) {+ console.error('Error loading configuration:', error);+ // Keep default values on error}- } catch (e) {- textToCopy = selectedRecording.value.transcription;- }+ };- animateCopyButton(button);-- if (navigator.clipboard && window.isSecureContext) {- navigator.clipboard.writeText(textToCopy)- .then(() => {- showToast('Transcription copied to clipboard!');- })- .catch(err => {- console.error('Copy failed:', err);- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');- fallbackCopyTextToClipboard(textToCopy);- });- } else {- fallbackCopyTextToClipboard(textToCopy);- }- };-+ const initializeSummaryMarkdownEditor = () => {+ if (!summaryMarkdownEditor.value) return;--- // Mobile tab switching- const switchMobileTab = (tabName) => {- selectedMobileTab.value = tabName;- };-- // Clear chat messages when recording changes- watch(selectedRecording, (newVal, oldVal) => {- // Only clear and reset if we're actually changing recordings- if (newVal?.id !== oldVal?.id) {- chatMessages.value = [];- showChat.value = false;- selectedTab.value = 'summary'; // Reset tab when recording changes- selectedMobileTab.value = 'transcript'; // Reset mobile tab when recording changes- editingMobileMeetingDate.value = false; // Reset mobile edit state-- // The critical speakerMap reset is now handled in selectRecording.- // We still reset other speaker-related UI state here.- highlightedSpeaker.value = null;- speakerSuggestions.value = {};- loadingSuggestions.value = {};-- // Reset editing states- editingParticipants.value = false;- editingMeetingDate.value = false;- editingSummary.value = false;- editingNotes.value = false;-- // Initialize desktop layout when a recording is first selected- if (newVal && !isMobileScreen.value && !isDesktopLayoutInitialized.value) {- // Use nextTick to ensure Vue has rendered the conditional elements- nextTick(() => {- const success = initializeDesktopLayout();- if (success) {- isDesktopLayoutInitialized.value = true;- console.log('Desktop layout initialized after recording selection');- }+ try {+ summaryMarkdownEditorInstance.value = new EasyMDE({+ element: summaryMarkdownEditor.value,+ spellChecker: false,+ autofocus: true,+ placeholder: "Enter summary in Markdown format...",+ status: false,+ toolbar: [+ "bold", "italic", "heading", "|",+ "quote", "unordered-list", "ordered-list", "|",+ "link", "image", "|",+ "preview", "side-by-side", "fullscreen", "|",+ "guide"+ ],+ previewClass: ["editor-preview", "notes-preview"],+ theme: isDarkMode.value ? "dark" : "light"});+ } catch (error) {+ console.error('Failed to initialize summary markdown editor:', error);+ editingSummary.value = true;}- }- });-- const toggleEditMobileMeetingDate = () => {- editingMobileMeetingDate.value = !editingMobileMeetingDate.value;- if (!editingMobileMeetingDate.value && selectedRecording.value) {- // If toggling off (i.e., saving), call saveInlineEdit- saveInlineEdit('meeting_date');- }- };+ };- // Toggle transcription view mode- const toggleTranscriptionViewMode = () => {- transcriptionViewMode.value = transcriptionViewMode.value === 'simple' ? 'bubble' : 'simple';- localStorage.setItem('transcriptionViewMode', transcriptionViewMode.value);- };+ const pollInboxRecordings = async () => {+ try {+ const response = await fetch('/api/inbox_recordings');+ if (!response.ok) {+ // Silently fail, as this is a background task+ return;+ }+ const inboxRecordings = await response.json();++ if (inboxRecordings && inboxRecordings.length > 0) {+ inboxRecordings.forEach(recording => {+ // Add to main recordings list if it's not there already+ const existingRecording = recordings.value.find(r => r.id === recording.id);+ if (!existingRecording) {+ recordings.value.unshift(recording);+ }- const seekAudio = (time, context = 'main') => {- let audioPlayer = null;- if (context === 'modal') {- // The audio player in the modal has the class directly on the audio element- audioPlayer = document.querySelector('audio.speaker-modal-transcript');- } else {- audioPlayer = document.querySelector('.main-content-area audio');- }+ // Check if this recording is already in the upload queue+ const existingItem = uploadQueue.value.find(item => item.recordingId === recording.id);+ if (!existingItem) {+ console.log(`Found new inbox recording: ${recording.original_filename}`);+ // Add it to the queue to be displayed in the progress modal+ const inboxItem = {+ file: {+ name: recording.original_filename || `Recording ${recording.id}`,+ size: recording.file_size || 0+ },+ status: 'pending', // It's already being processed on backend+ recordingId: recording.id,+ clientId: `inbox-${recording.id}-${Date.now()}`,+ error: null,+ isReprocessing: true, // Use reprocessing logic to poll for status+ reprocessType: 'transcription'+ };+ uploadQueue.value.unshift(inboxItem);++ // If nothing is currently being processed, make this the active item for the main progress bar+ if (!isProcessingActive.value && !currentlyProcessingFile.value) {+ currentlyProcessingFile.value = inboxItem;+ }++ // Show progress modal if it's hidden+ progressPopupMinimized.value = false;+ progressPopupClosed.value = false;- if (audioPlayer) {- const wasPlaying = !audioPlayer.paused;- audioPlayer.currentTime = time;- if (wasPlaying) {- audioPlayer.play();- }- } else {- console.warn(`Audio player not found for context: ${context}`);- // Fallback to old method if new one fails- const oldPlayer = document.querySelector('audio');- if(oldPlayer) {- const wasPlaying = !oldPlayer.paused;- oldPlayer.currentTime = time;- if (wasPlaying) {- oldPlayer.play();+ // Start polling its status+ startReprocessingPoll(recording.id);+ }+ });}+ } catch (error) {+ console.error('Error polling for inbox recordings:', error);}- }- };+ };- const seekAudioFromEvent = (event) => {- const segmentElement = event.target.closest('[data-start-time]');- if (!segmentElement) return;+ // --- System Audio Detection ---+ const detectSystemAudioCapabilities = async () => {+ systemAudioSupported.value = false;+ canRecordSystemAudio.value = false;+ systemAudioError.value = '';- const time = parseFloat(segmentElement.dataset.startTime);- if (isNaN(time)) return;+ // Check if getDisplayMedia is available+ if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {+ systemAudioError.value = 'getDisplayMedia API not supported';+ return;+ }- // Determine context by checking if we're inside the speaker modal- const isInSpeakerModal = event.target.closest('.speaker-modal-transcript') !== null;- const context = isInSpeakerModal ? 'modal' : 'main';-- seekAudio(time, context);- };+ try {+ // Test if we can request system audio (this will prompt user)+ // We'll do this only when user actually tries to record+ systemAudioSupported.value = true;+ canRecordSystemAudio.value = true;+ systemAudioError.value = '';+ } catch (error) {+ systemAudioError.value = error.message;+ console.warn('System audio detection failed:', error);+ }+ };- const onPlayerVolumeChange = (event) => {- const newVolume = event.target.volume;- playerVolume.value = newVolume;- localStorage.setItem('playerVolume', newVolume);- };+ const detectBrowser = () => {+ const userAgent = navigator.userAgent;+ if (userAgent.includes("Firefox")) {+ browser.value = "firefox";+ } else if (userAgent.includes("Chrome")) {+ browser.value = "chrome";+ } else if (userAgent.includes("Safari")) {+ browser.value = "safari";+ } else if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {+ browser.value = "ie";+ } else {+ browser.value = "unknown";+ }+ };- // Watch for volume changes to apply to all audio elements- watch(playerVolume, (newVolume) => {- const audioElements = document.querySelectorAll('audio');- audioElements.forEach(audio => {- if (audio.volume !== newVolume) {- audio.volume = newVolume;+ // --- Lifecycle ---+ onMounted(async () => {+ const loader = document.getElementById('loader');+ const app = document.getElementById('app');+ if (loader) {+ loader.style.opacity = '0';+ setTimeout(() => {+ loader.style.display = 'none';+ }, 500);}- });- });+ if (app) {+ app.style.opacity = '1';+ }+ const appDiv = document.getElementById('app');+ if (appDiv) {+ const asrFlag = appDiv.dataset.useAsrEndpoint;+ useAsrEndpoint.value = asrFlag === 'True' || asrFlag === 'true';+ currentUserName.value = appDiv.dataset.currentUserName || '';+ }++ // Load configuration first+ await loadConfiguration();++ // Detect system audio capabilities+ await detectSystemAudioCapabilities();++ detectBrowser();++ loadRecordings();+ initializeDarkMode();+ initializeColorScheme();++ const savedVolume = localStorage.getItem('playerVolume');+ if (savedVolume !== null) {+ playerVolume.value = parseFloat(savedVolume);+ }++ const savedTranscriptionViewMode = localStorage.getItem('transcriptionViewMode');+ if (savedTranscriptionViewMode) {+ transcriptionViewMode.value = savedTranscriptionViewMode;+ }++ // Load saved column widths+ const savedLeftWidth = localStorage.getItem('transcriptColumnWidth');+ const savedRightWidth = localStorage.getItem('summaryColumnWidth');+ if (savedLeftWidth && savedRightWidth) {+ leftColumnWidth.value = parseFloat(savedLeftWidth);+ rightColumnWidth.value = parseFloat(savedRightWidth);+ }++ const updateMobileStatus = () => {+ windowWidth.value = window.innerWidth;+ };++ window.addEventListener('resize', updateMobileStatus);+ updateMobileStatus();++ // Start polling for inbox recordings+ setInterval(pollInboxRecordings, 10000); // Poll every 10 seconds- return {- // State- currentView, dragover, recordings, selectedRecording, // currentRecording removed- showEditModal, showDeleteModal, showResetModal, editingRecording, recordingToDelete, recordingToReset,- isLoadingRecordings, globalError, maxFileSizeMB, isDarkMode, // <-- Added isDarkMode- // Multi-upload State- uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,- isProcessingActive, progressPopupMinimized, progressPopupClosed,- // Chat State- showChat, chatMessages, chatInput, isChatLoading, chatMessagesRef, // <-- Added chatMessagesRef- // Resize functionality- transcriptionFlex, tabsFlex,- // Computed- groupedRecordings, totalInQueue, completedInQueue, queuedFiles, finishedFilesInQueue, isMobileScreen,- processedTranscription, // <-- ADDED: Expose processedTranscription computed property- // Inline editing state- editingParticipants, editingMeetingDate, editingSummary, editingNotes,- // Methods- handleDrop, handleFileSelect, /*autoSave removed*/ loadRecordings, selectedTab, // <-- Added selectedTab- selectRecording, editRecording, cancelEdit, saveEdit, confirmDelete,- cancelDelete, deleteRecording, switchToUploadView, switchToGalleryView,- formatFileSize, setGlobalError, handleDragLeave, formatStatus, getStatusClass,- formatDisplayDate, // <-- ADDED: Expose date formatting function- formatDuration,- toggleDarkMode, // <-- Added toggleDarkMode- toggleSidebar, isSidebarCollapsed, // <-- Added sidebar state and function- toggleMobileMenu, closeMobileMenu, isMobileMenuOpen, // <-- Added mobile menu state and functions- // Inbox and Highlight methods- toggleInbox, toggleHighlight,- // Inline editing methods- toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, toggleEditNotes, saveInlineEdit,- editingMobileMeetingDate, // Expose for mobile- // Chat Methods- sendChatMessage, copyMessage, copyTranscription,- // User menu- isUserMenuOpen,- isMobileUserMenuOpen, // <-- Added mobile user menu state- // Search- searchQuery,- // Audio Recording- isRecording,- canRecordAudio,- audioBlobURL,- recordingTime,- startRecording,- stopRecording,- uploadRecordedAudio,- discardRecording,- formatTime,- // Reprocessing- reprocessTranscription,- reprocessSummary,- confirmReset,- cancelReset,- executeReset,- showReprocessModal,- reprocessType,- reprocessRecording,- confirmReprocess,- cancelReprocess,- executeReprocess,- // ASR Reprocessing- asrReprocessOptions,- // Speaker Identification- showSpeakerModal,- speakerMap,- regenerateSummaryAfterSpeakerUpdate,- identifiedSpeakers,- hasSpeakerNames,- openSpeakerModal,- closeSpeakerModal,- saveSpeakerNames,- highlightedTranscript,- highlightedSpeaker,- highlightSpeakerInTranscript,- clearSpeakerHighlight,- useAsrEndpoint,- // Mobile tabs- selectedMobileTab,- switchMobileTab,- toggleEditMobileMeetingDate, // Expose for mobile- transcriptionViewMode,- toggleTranscriptionViewMode,- legendExpanded, // Speaker legend expansion state- // Speaker database functionality- speakerSuggestions,- loadingSuggestions,- searchSpeakers,- selectSpeakerSuggestion,- autoIdentifySpeakers,- isAutoIdentifying,- // Color scheme functionality- currentColorScheme,- showColorSchemeModal,- colorSchemes,- openColorSchemeModal,- closeColorSchemeModal,- selectColorScheme,- resetColorScheme,- // Main column resizer refs (not needed in template but good practice if they were)- // leftMainColumn, rightMainColumn, mainColumnResizer, mainContentColumns,- seekAudio,- seekAudioFromEvent,- playerVolume,- onPlayerVolumeChange- }- },- delimiters: ['${', '}'] // Keep Vue delimiters distinct from Flask's Jinja-}).mount('#app');+ const handleEsc = (e) => {+ if (e.key === 'Escape') {+ if (showColorSchemeModal.value) {+ closeColorSchemeModal();+ }+ if (showEditModal.value) {+ cancelEdit();+ }+ if (showDeleteModal.value) {+ cancelDelete();+ }+ if (showSortOptions.value) {+ showSortOptions.value = false;+ }+ }+ };+ document.addEventListener('keydown', handleEsc);++ // Click away handler for dropdowns+ const handleClickAway = (e) => {+ // Close user menu if clicking outside+ if (isUserMenuOpen.value) {+ // Check if we clicked within the user menu area (button or dropdown)+ const userMenuButton = e.target.closest('button[class*="flex items-center gap-2"]');+ const userMenuDropdown = e.target.closest('div[class*="absolute right-0"]');+ const userMenuContainer = e.target.closest('.relative');++ // Check if the click was on the user menu button specifically+ const isUserMenuButtonClick = userMenuButton && userMenuButton.querySelector('i.fa-user-circle');++ // If we didn't click on the user menu button or dropdown, close it+ if (!isUserMenuButtonClick && !userMenuDropdown && !userMenuContainer) {+ isUserMenuOpen.value = false;+ }+ }+ };+ document.addEventListener('click', handleClickAway);+ });+ return {+ // Core State+ currentView, dragover, recordings, selectedRecording, selectedTab, searchQuery,+ isLoadingRecordings, globalError, maxFileSizeMB, sortBy,++ // UI State+ browser,+ isSidebarCollapsed, searchTipsExpanded, isUserMenuOpen, isDarkMode, currentColorScheme,+ showColorSchemeModal, windowWidth, isMobileScreen,+ mobileTab, isMetadataExpanded,++ // Upload State+ uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,+ isProcessingActive, progressPopupMinimized, progressPopupClosed,+ totalInQueue, completedInQueue, finishedFilesInQueue,++ // Audio Recording+ isRecording, canRecordAudio, canRecordSystemAudio, systemAudioSupported, systemAudioError, audioBlobURL, recordingTime, recordingNotes, visualizer, micVisualizer, systemVisualizer, recordingMode,+ showSystemAudioHelp,++ // Modal State+ showEditModal, showDeleteModal, showResetModal, editingRecording, recordingToDelete,+ showTextEditorModal, showAsrEditorModal, editingTranscriptionContent, editingSegments, availableSpeakers,++ // Inline Editing+ editingParticipants, editingMeetingDate, editingSummary, editingNotes,++ // Markdown Editor+ notesMarkdownEditor, markdownEditorInstance, summaryMarkdownEditor, summaryMarkdownEditorInstance, recordingNotesEditor,++ // Transcription+ transcriptionViewMode, legendExpanded, highlightedSpeaker, processedTranscription,++ // Chat+ showChat, chatMessages, chatInput, isChatLoading, chatMessagesRef,++ // Audio Player+ playerVolume,++ // Column Resizing+ leftColumnWidth, rightColumnWidth, isResizing,++ // App Configuration+ useAsrEndpoint, currentUserName,++ // Computed+ filteredRecordings, groupedRecordings, activeRecordingMetadata,++ // Color Schemes+ colorSchemes,++ // Methods+ setGlobalError, formatFileSize, formatDisplayDate, formatStatus, getStatusClass, formatTime,+ toggleDarkMode, applyColorScheme, initializeColorScheme, openColorSchemeModal,+ closeColorSchemeModal, selectColorScheme, resetColorScheme,+ toggleSidebar, switchToUploadView, selectRecording,+ handleDragOver, handleDragLeave, handleDrop, handleFileSelect, addFilesToQueue,+ startRecording, stopRecording, uploadRecordedAudio, discardRecording,+ loadRecordings, saveMetadata, editRecording, cancelEdit, saveEdit,+ confirmDelete, cancelDelete, deleteRecording,+ toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, cancelEditSummary, saveEditSummary, toggleEditNotes,+ cancelEditNotes, saveEditNotes, initializeMarkdownEditor, saveInlineEdit,+ sendChatMessage, startColumnResize, handleChatKeydown, seekAudio, seekAudioFromEvent, onPlayerVolumeChange,+ showToast, copyMessage, copyTranscription, copySummary, copyNotes,+ toggleInbox, toggleHighlight,+ toggleTranscriptionViewMode,+ reprocessTranscription,+ reprocessSummary,+ resetRecordingStatus,+ confirmReset,+ cancelReset,+ executeReset,+ openTranscriptionEditor,+ openTextEditorModal,+ closeTextEditorModal,+ saveTranscription,+ openAsrEditorModal,+ closeAsrEditorModal,+ saveAsrTranscription,+ adjustTime,+ filterSpeakers,+ openSpeakerSuggestions,+ closeSpeakerSuggestions,+ selectSpeaker,+ addSegment,+ removeSegment,+ showReprocessModal,+ reprocessType,+ reprocessRecording,+ cancelReprocess,+ executeReprocess,+ asrReprocessOptions,+ showSpeakerModal,+ showShareModal,+ recordingToShare,+ shareOptions,+ generatedShareLink,+ userShares,+ isLoadingShares,+ showSharesListModal,+ speakerMap,+ regenerateSummaryAfterSpeakerUpdate,+ identifiedSpeakers,+ hasSpeakerNames,+ openSpeakerModal,+ closeSpeakerModal,+ saveSpeakerNames,+ highlightedTranscript,+ highlightedSpeaker,+ highlightSpeakerInTranscript,+ focusSpeaker,+ blurSpeaker,+ clearSpeakerHighlight,+ speakerSuggestions,+ loadingSuggestions,+ searchSpeakers,+ selectSpeakerSuggestion,+ autoIdentifySpeakers,+ isAutoIdentifying,+ formatDuration,+ openShareModal,+ closeShareModal,+ createShare,+ openSharesList,+ closeSharesList,+ updateShare,+ deleteShare,+ copyShareLink+ }+ },+ delimiters: ['${', '}']+ }).mount('#app');});diff --git a/static/manifest.json b/static/manifest.jsonindex 5887bbba..0dfff1b8 100644--- a/static/manifest.json+++ b/static/manifest.json@@ -1,8 +1,8 @@{- "id": "com.whispertranscribe.app",- "name": "WhisperTranscribe",+ "id": "com.speakr.app",+ "name": "Speakr","short_name": "WhisperT",- "description": "WhisperTranscribe Application - Audio transcription and summarization",+ "description": "Speakr - Audio transcription and summarization","start_url": "/","scope": "/","display": "standalone",@@ -38,6 +38,12 @@"sizes": "512x512","type": "image/png","purpose": "maskable"+ },+ {+ "src": "/static/img/icon-180x180.png",+ "sizes": "180x180",+ "type": "image/png",+ "purpose": "any"}],"shortcuts": [diff --git a/static/offline.html b/static/offline.htmlindex 0b46fb39..fc054898 100644--- a/static/offline.html+++ b/static/offline.html@@ -3,8 +3,8 @@<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Offline - WhisperTranscribe</title>- <link rel="icon" href="/static/img/favicon.svg" type="image/svg+xml">+ <title>Offline - Speakr</title>+ <link rel="icon" href="/static/img/favicon.ico" type="image/svg+xml"><style>body {font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;@@ -55,7 +55,7 @@</head><body><div class="container">- <img src="/static/img/favicon.svg" alt="WhisperTranscribe Logo">+ <img src="/static/img/favicon.ico" alt="Speakr Logo"><h1>You're Offline</h1><p>It looks like you're not connected to the internet. Please check your connection and try again.</p><p>Some content may be unavailable until you're back online.</p>diff --git a/static/sw.js b/static/sw.jsindex 73e70592..c2170441 100644--- a/static/sw.js+++ b/static/sw.js@@ -1,4 +1,4 @@-const CACHE_NAME = 'whispertranscribe-cache-v3';+const CACHE_NAME = 'Speakr-cache-v3';const ASSETS_TO_CACHE = ['/','/static/offline.html',@@ -7,7 +7,7 @@ const ASSETS_TO_CACHE = ['/static/js/app.js','/static/img/icon-192x192.png', // Assuming you will add this'/static/img/icon-512x512.png', // Assuming you will add this- '/static/img/favicon.svg', // Keep existing SVG as a fallback or for other uses+ '/static/img/favicon.ico', // Keep existing SVG as a fallback or for other uses// HTML templates (these are typically served via routes, but caching the routes themselves is handled by fetch strategies)// We cache '/' which should serve the main page.// Other specific page routes like /login, /register, /account will be handled by networkFirst.diff --git a/templates/account.html b/templates/account.htmlindex cfaab586..9bf50bc0 100644--- a/templates/account.html+++ b/templates/account.html@@ -4,104 +4,48 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - Speakr</title>- <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml"><script src="https://cdn.tailwindcss.com"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">- <style>- /* Dark Mode CSS Variables */- :root {- /* Light mode variables */- --bg-primary: #f3f4f6; /* gray-100 */- --bg-secondary: #ffffff; /* white */- --bg-tertiary: #f9fafb; /* gray-50 */- --bg-accent: #dbeafe; /* blue-100 */- --bg-accent-hover: #bfdbfe; /* blue-200 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #1d4ed8; /* blue-700 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #b91c1c; /* red-700 */- --bg-danger-light: #fee2e2; /* red-100 */- --bg-info-light: #dbeafe; /* blue-100 */- --bg-warn-light: #fef3c7; /* amber-100 */- --bg-success-light: #d1fae5; /* green-100 */- --bg-pending-light: #f5f5f4; /* stone-100 */- --bg-input: #ffffff; /* white */-- --text-primary: #1f2937; /* gray-800 */- --text-secondary: #374151; /* gray-700 */- --text-muted: #6b7280; /* gray-500 */- --text-light: #9ca3af; /* gray-400 */- --text-accent: #1d4ed8; /* blue-700 */- --text-button: #ffffff; /* white */- --text-danger: #b91c1c; /* red-700 */- --text-danger-strong: #991b1b; /* red-800 */- --text-info-strong: #1e40af; /* blue-800 */- --text-warn-strong: #92400e; /* amber-800 */- --text-success-strong: #065f46; /* green-800 */- --text-pending-strong: #44403c; /* stone-700 */-- --border-primary: #e5e7eb; /* gray-200 */- --border-secondary: #d1d5db; /* gray-300 */- --border-accent: #93c5fd; /* blue-300 */- --border-danger: #f87171; /* red-400 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #bfdbfe; /* blue-200 */- }+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <script>+ // Function to apply the theme based on localStorage+ function applyTheme() {+ // Apply dark mode+ const savedMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }- .dark {- /* Dark mode variables */- --bg-primary: #111827; /* gray-900 */- --bg-secondary: #1f2937; /* gray-800 */- --bg-tertiary: #374151; /* gray-700 */- --bg-accent: #1e3a8a; /* blue-900 */- --bg-accent-hover: #1e40af; /* blue-800 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #3b82f6; /* blue-500 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #ef4444; /* red-500 */- --bg-danger-light: #7f1d1d; /* red-900 */- --bg-info-light: #1e3a8a; /* blue-900 */- --bg-warn-light: #78350f; /* amber-900 */- --bg-success-light: #064e3b; /* green-900 */- --bg-pending-light: #292524; /* stone-800 */- --bg-input: #374151; /* gray-700 */-- --text-primary: #f3f4f6; /* gray-100 */- --text-secondary: #d1d5db; /* gray-300 */- --text-muted: #9ca3af; /* gray-400 */- --text-light: #6b7280; /* gray-500 */- --text-accent: #60a5fa; /* blue-400 */- --text-button: #ffffff; /* white */- --text-danger: #f87171; /* red-400 */- --text-danger-strong: #fca5a5; /* red-300 */- --text-info-strong: #93c5fd; /* blue-300 */- --text-warn-strong: #fcd34d; /* amber-300 */- --text-success-strong: #6ee7b7; /* green-300 */- --text-pending-strong: #d6d3d1; /* stone-300 */-- --border-primary: #374151; /* gray-700 */- --border-secondary: #4b5563; /* gray-600 */- --border-accent: #1d4ed8; /* blue-700 */- --border-danger: #ef4444; /* red-500 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #1e40af; /* blue-800 */- }+ // Apply color scheme+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const isDark = document.documentElement.classList.contains('dark');+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';++ // Remove all other theme classes+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];+ themeClasses.forEach(theme => {+ document.documentElement.classList.remove(`theme-light-${theme}`);+ document.documentElement.classList.remove(`theme-dark-${theme}`);+ });- html {- background-color: var(--bg-primary);- color: var(--text-primary);- transition: background-color 0.3s, color 0.3s;- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ // Add the correct theme class+ if (savedScheme !== 'blue') {+ document.documentElement.classList.add(themePrefix + savedScheme);+ }}- html, body { height: 100%; margin: 0; }- </style>+ applyTheme();+ </script></head><body class="bg-[var(--bg-primary)] text-[var(--text-primary)]"><div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen"><header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>@@ -137,9 +81,20 @@<main class="flex-grow"><div class="bg-[var(--bg-secondary)] p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">- <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Account Information</h2>-- {% with messages = get_flashed_messages(with_categories=true) %}+ <div class="mb-6 border-b border-[var(--border-primary)]">+ <nav class="-mb-px flex space-x-8" aria-label="Tabs">+ <a href="#" id="tab-account" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm border-[var(--border-accent)] text-[var(--text-accent)]">+ Account Information+ </a>+ <a href="#" id="tab-shares" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]">+ Shared Transcripts+ </a>+ </nav>+ </div>++ <div id="content-account">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Account Information</h2>+ {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">@@ -287,6 +242,14 @@</div></div></div>+ </div>++ <div id="content-shares" class="hidden">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">My Shared Transcripts</h2>+ <div id="shares-container" class="space-y-4">+ <!-- Shares will be loaded here by JavaScript -->+ </div>+ </div></div></main>@@ -400,6 +363,133 @@</div><script>+ document.addEventListener('DOMContentLoaded', function() {+ const tabAccount = document.getElementById('tab-account');+ const tabShares = document.getElementById('tab-shares');+ const contentAccount = document.getElementById('content-account');+ const contentShares = document.getElementById('content-shares');+ const sharesContainer = document.getElementById('shares-container');++ function showAccountTab() {+ tabAccount.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabAccount.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ contentAccount.classList.remove('hidden');+ contentShares.classList.add('hidden');+ }++ function showSharesTab() {+ tabShares.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabShares.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ contentShares.classList.remove('hidden');+ contentAccount.classList.add('hidden');+ loadShares();+ }++ tabAccount.addEventListener('click', (e) => {+ e.preventDefault();+ showAccountTab();+ });++ tabShares.addEventListener('click', (e) => {+ e.preventDefault();+ showSharesTab();+ });++ async function loadShares() {+ sharesContainer.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';+ try {+ const response = await fetch('/api/shares');+ const shares = await response.json();+ if (!response.ok) throw new Error(shares.error || 'Failed to load');++ if (shares.length === 0) {+ sharesContainer.innerHTML = '<p class="text-center text-[var(--text-muted)]">You have not shared any transcripts yet.</p>';+ return;+ }++ sharesContainer.innerHTML = '';+ shares.forEach(share => {+ const shareEl = document.createElement('div');+ shareEl.className = 'bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]';+ shareEl.innerHTML = `+ <div class="flex justify-between items-start">+ <div>+ <p class="font-semibold">${escapeHtml(share.recording_title)}</p>+ <p class="text-sm text-[var(--text-muted)]">Shared on: ${share.created_at}</p>+ </div>+ <button data-share-id="${share.id}" class="delete-share-btn text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>+ </div>+ <div class="mt-4 flex items-center gap-4">+ <label class="flex items-center text-sm">+ <input type="checkbox" data-share-id="${share.id}" data-share-prop="share_summary" class="share-checkbox h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" ${share.share_summary ? 'checked' : ''}>+ <span class="ml-2">Share Summary</span>+ </label>+ <label class="flex items-center text-sm">+ <input type="checkbox" data-share-id="${share.id}" data-share-prop="share_notes" class="share-checkbox h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" ${share.share_notes ? 'checked' : ''}>+ <span class="ml-2">Share Notes</span>+ </label>+ </div>+ <div class="mt-4">+ <input value="{{ request.url_root }}share/${share.public_id}" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">+ </div>+ `;+ sharesContainer.appendChild(shareEl);+ });++ document.querySelectorAll('.delete-share-btn').forEach(btn => {+ btn.addEventListener('click', handleDeleteShare);+ });+ document.querySelectorAll('.share-checkbox').forEach(box => {+ box.addEventListener('change', handleUpdateShare);+ });++ } catch (error) {+ sharesContainer.innerHTML = `<p class="text-center text-red-500">Error loading shares: ${error.message}</p>`;+ }+ }++ async function handleDeleteShare(event) {+ const shareId = event.currentTarget.dataset.shareId;+ if (!confirm('Are you sure you want to delete this share? This will revoke access to the public link.')) return;++ try {+ const response = await fetch(`/api/share/${shareId}`, { method: 'DELETE' });+ if (!response.ok) throw new Error('Failed to delete');+ loadShares();+ } catch (error) {+ alert('Error deleting share.');+ }+ }++ async function handleUpdateShare(event) {+ const shareId = event.currentTarget.dataset.shareId;+ const prop = event.currentTarget.dataset.shareProp;+ const value = event.currentTarget.checked;++ try {+ const response = await fetch(`/api/share/${shareId}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ [prop]: value })+ });+ if (!response.ok) throw new Error('Failed to update');+ } catch (error) {+ alert('Error updating share.');+ event.currentTarget.checked = !value; // Revert on failure+ }+ }++ function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }+ });+// Dark mode toggle functionalityconst darkModeToggle = document.getElementById('darkModeToggle');const darkModeIcon = document.getElementById('darkModeIcon');diff --git a/templates/admin.html b/templates/admin.htmlindex 707d0aef..21162639 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -4,109 +4,49 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Admin Dashboard - Speakr</title>- <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml"><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">- <style>- /* Dark Mode CSS Variables */- :root {- /* Light mode variables */- --bg-primary: #f3f4f6; /* gray-100 */- --bg-secondary: #ffffff; /* white */- --bg-tertiary: #f9fafb; /* gray-50 */- --bg-accent: #dbeafe; /* blue-100 */- --bg-accent-hover: #bfdbfe; /* blue-200 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #1d4ed8; /* blue-700 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #b91c1c; /* red-700 */- --bg-danger-light: #fee2e2; /* red-100 */- --bg-info-light: #dbeafe; /* blue-100 */- --bg-warn-light: #fef3c7; /* amber-100 */- --bg-success-light: #d1fae5; /* green-100 */- --bg-pending-light: #f5f5f4; /* stone-100 */- --bg-input: #ffffff; /* white */-- --text-primary: #1f2937; /* gray-800 */- --text-secondary: #374151; /* gray-700 */- --text-muted: #6b7280; /* gray-500 */- --text-light: #9ca3af; /* gray-400 */- --text-accent: #1d4ed8; /* blue-700 */- --text-button: #ffffff; /* white */- --text-danger: #b91c1c; /* red-700 */- --text-danger-strong: #991b1b; /* red-800 */- --text-info-strong: #1e40af; /* blue-800 */- --text-warn-strong: #92400e; /* amber-800 */- --text-success-strong: #065f46; /* green-800 */- --text-pending-strong: #44403c; /* stone-700 */-- --border-primary: #e5e7eb; /* gray-200 */- --border-secondary: #d1d5db; /* gray-300 */- --border-accent: #93c5fd; /* blue-300 */- --border-danger: #f87171; /* red-400 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #bfdbfe; /* blue-200 */- }-- .dark {- /* Dark mode variables */- --bg-primary: #111827; /* gray-900 */- --bg-secondary: #1f2937; /* gray-800 */- --bg-tertiary: #374151; /* gray-700 */- --bg-accent: #1e3a8a; /* blue-900 */- --bg-accent-hover: #1e40af; /* blue-800 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #3b82f6; /* blue-500 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #ef4444; /* red-500 */- --bg-danger-light: #7f1d1d; /* red-900 */- --bg-info-light: #1e3a8a; /* blue-900 */- --bg-warn-light: #78350f; /* amber-900 */- --bg-success-light: #064e3b; /* green-900 */- --bg-pending-light: #292524; /* stone-800 */- --bg-input: #374151; /* gray-700 */-- --text-primary: #f3f4f6; /* gray-100 */- --text-secondary: #d1d5db; /* gray-300 */- --text-muted: #9ca3af; /* gray-400 */- --text-light: #6b7280; /* gray-500 */- --text-accent: #60a5fa; /* blue-400 */- --text-button: #ffffff; /* white */- --text-danger: #f87171; /* red-400 */- --text-danger-strong: #fca5a5; /* red-300 */- --text-info-strong: #93c5fd; /* blue-300 */- --text-warn-strong: #fcd34d; /* amber-300 */- --text-success-strong: #6ee7b7; /* green-300 */- --text-pending-strong: #d6d3d1; /* stone-300 */+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <script>+ // Function to apply the theme based on localStorage+ function applyTheme() {+ // Apply dark mode+ const savedMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }- --border-primary: #374151; /* gray-700 */- --border-secondary: #4b5563; /* gray-600 */- --border-accent: #1d4ed8; /* blue-700 */- --border-danger: #ef4444; /* red-500 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #1e40af; /* blue-800 */- }+ // Apply color scheme+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const isDark = document.documentElement.classList.contains('dark');+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';++ // Remove all other theme classes+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];+ themeClasses.forEach(theme => {+ document.documentElement.classList.remove(`theme-light-${theme}`);+ document.documentElement.classList.remove(`theme-dark-${theme}`);+ });- html {- background-color: var(--bg-primary);- color: var(--text-primary);- transition: background-color 0.3s, color 0.3s;- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ // Add the correct theme class+ if (savedScheme !== 'blue') {+ document.documentElement.classList.add(themePrefix + savedScheme);+ }}- html, body { height: 100%; margin: 0; }- .custom-scrollbar::-webkit-scrollbar { width: 6px; }- .custom-scrollbar::-webkit-scrollbar-track { background: var(--scrollbar-track); border-radius: 12px; }- .custom-scrollbar::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 12px; }- .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover); }- </style>+ applyTheme();+ </script></head><body class="bg-[var(--bg-primary)] text-[var(--text-primary)]"><div id="app" class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen"><header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>@@ -165,6 +105,11 @@class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"><i class="fas fa-chart-bar mr-2"></i> System Statistics</button>+ <button @click="activeTab = 'settings'"+ :class="activeTab === 'settings' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"+ class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">+ <i class="fas fa-cogs mr-2"></i> System Settings+ </button></nav></div>@@ -340,6 +285,68 @@</div></div></div>++ <!-- System Settings Tab -->+ <div v-show="activeTab === 'settings'">+ <div class="flex justify-between items-center mb-4">+ <h3 class="text-lg font-medium text-[var(--text-secondary)]">System Settings</h3>+ <button @click="loadSettings" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">+ <i class="fas fa-sync-alt mr-2"></i> Refresh+ </button>+ </div>++ <!-- Settings List -->+ <div class="space-y-4">+ <div v-for="setting in settings" :key="setting.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex justify-between items-start">+ <div class="flex-grow">+ <h4 class="text-md font-medium text-[var(--text-primary)] mb-1">${ setting.key }</h4>+ <p class="text-sm text-[var(--text-muted)] mb-2">${ setting.description || 'No description available' }</p>+ <div class="flex items-center space-x-2">+ <span class="text-xs px-2 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded">${ setting.setting_type }</span>+ <span class="text-xs text-[var(--text-muted)]">Last updated: ${ formatDate(setting.updated_at) }</span>+ </div>+ </div>+ <div class="ml-4 flex items-center space-x-2">+ <div class="text-right">+ <div class="text-sm font-medium text-[var(--text-primary)]">+ <span v-if="setting.setting_type === 'boolean'">+ <span v-if="setting.value === 'true'" class="text-[var(--text-success-strong)]">+ <i class="fas fa-check-circle mr-1"></i> Enabled+ </span>+ <span v-else class="text-[var(--text-danger-strong)]">+ <i class="fas fa-times-circle mr-1"></i> Disabled+ </span>+ </span>+ <span v-else-if="setting.key === 'transcript_length_limit' && setting.value === '-1'" class="text-[var(--text-info-strong)]">+ <i class="fas fa-infinity mr-1"></i> No Limit+ </span>+ <span v-else-if="setting.key === 'transcript_length_limit'" class="text-[var(--text-primary)]">+ ${ Number(setting.value).toLocaleString() } characters+ </span>+ <span v-else-if="setting.key === 'max_file_size_mb'" class="text-[var(--text-primary)]">+ ${ Number(setting.value).toLocaleString() } MB+ </span>+ <span v-else>${ setting.value || 'Not set' }</span>+ </div>+ </div>+ <button @click="editSetting(setting)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)] p-1" title="Edit Setting">+ <i class="fas fa-edit"></i>+ </button>+ </div>+ </div>+ </div>++ <div v-if="settings.length === 0" class="text-center py-8">+ <div v-if="isLoadingSettings">+ <i class="fas fa-spinner fa-spin mr-2"></i> Loading settings...+ </div>+ <div v-else class="text-[var(--text-muted)]">+ No system settings found.+ </div>+ </div>+ </div>+ </div></div></main>@@ -450,7 +457,9 @@failed_recordings: 0,top_users: []});+ const settings = ref([]);const isLoadingUsers = ref(true);+ const isLoadingSettings = ref(false);const userSearchQuery = ref('');const isDarkMode = ref(false);const isUserMenuOpen = ref(false);@@ -510,6 +519,69 @@}};+ const loadSettings = async () => {+ isLoadingSettings.value = true;+ try {+ const response = await fetch('/admin/settings');+ if (!response.ok) throw new Error('Failed to load settings');++ const data = await response.json();+ settings.value = data;+ } catch (error) {+ console.error('Error loading settings:', error);+ // Show error notification+ } finally {+ isLoadingSettings.value = false;+ }+ };++ const editSetting = (setting) => {+ // Create a prompt for editing the setting+ let newValue = prompt(+ `Edit setting: ${setting.key}\n\nDescription: ${setting.description || 'No description'}\nType: ${setting.setting_type}\nCurrent value: ${setting.value || 'Not set'}\n\nEnter new value:`,+ setting.value || ''+ );++ if (newValue !== null) {+ updateSetting(setting.key, newValue, setting.description, setting.setting_type);+ }+ };++ const updateSetting = async (key, value, description, settingType) => {+ try {+ const response = await fetch('/admin/settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ key: key,+ value: value,+ description: description,+ setting_type: settingType+ })+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to update setting');+ }++ // Reload settings+ await loadSettings();++ } catch (error) {+ console.error('Error updating setting:', error);+ alert(error.message);+ }+ };++ const formatDate = (dateString) => {+ if (!dateString) return 'Never';+ const date = new Date(dateString);+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();+ };+const addUser = async () => {if (newUser.value.password !== newUser.value.confirmPassword) {alert('Passwords do not match');@@ -691,6 +763,8 @@loadUsers();} else if (newTab === 'stats') {loadStats();+ } else if (newTab === 'settings') {+ loadSettings();}});@@ -699,7 +773,9 @@activeTab,users,stats,+ settings,isLoadingUsers,+ isLoadingSettings,userSearchQuery,isDarkMode,isUserMenuOpen,@@ -718,6 +794,10 @@// MethodsloadUsers,loadStats,+ loadSettings,+ editSetting,+ updateSetting,+ formatDate,addUser,editUser,updateUser,diff --git a/templates/index.html b/templates/index.htmlindex fa11a01a..37adc0b5 100644--- a/templates/index.html+++ b/templates/index.html@@ -1,883 +1,1069 @@<!DOCTYPE html>-<html lang="en">+<html lang="en" class="h-full"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Speakr</title>- <link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">- <meta name="theme-color" content="#007bff">- <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">+ <meta name="csrf-token" content="{{ csrf_token() }}">+ <title>Speakr - Audio Transcription & Summarization</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">- <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>- <script src="{{ url_for('static', filename='js/app.js') }}"></script>+ <!-- EasyMDE Markdown Editor -->+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">+ <script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}">+ <link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='img/icon-32x32.png') }}">+ <link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='img/icon-16x16.png') }}">+ <link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='img/icon-180x180.png') }}">+ <link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">+ <meta name="theme-color" content="#2563eb">+ <script>+ tailwind.config = {+ darkMode: 'class',+ theme: {+ extend: {+ maxHeight: {+ '85vh': '85vh',+ '90vh': '90vh'+ },+ colors: {+ primary: 'var(--bg-primary)',+ secondary: 'var(--bg-secondary)',+ accent: 'var(--bg-accent)'+ }+ }+ }+ }+ </script></head>-<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">- <div- id="app"- class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col"- :class="{ 'use-asr-endpoint': useAsrEndpoint }"- data-use-asr-endpoint="{{ use_asr_endpoint }}"- data-current-user-name="{{ current_user.name or '' }}">- <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">- <h1 class="text-3xl font-bold text-[var(--text-primary)] cursor-pointer flex items-center" @click="switchToGalleryView" title="Go to Gallery">- <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">- Speakr- </h1>- <div class="flex items-center space-x-2 lg:space-x-2">- <!-- Hamburger Menu for Mobile -->- <button @click="toggleMobileMenu" class="lg:hidden p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" title="Open Menu">- <i class="fas fa-bars"></i>- </button>- <!-- Dark Mode Toggle - visible on all sizes -->- <button @click="toggleDarkMode" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" :title="isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'">- <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>+<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">+ <div id="loader" class="fixed inset-0 bg-gray-800 flex items-center justify-center z-50">+ <div class="text-white text-lg">Loading...</div>+ </div>+ <div id="app" v-cloak+ data-use-asr-endpoint="{{ use_asr_endpoint }}"+ data-current-user-name="{{ current_user.name if current_user.is_authenticated else '' }}"+ class="h-full flex flex-col opacity-0 transition-opacity duration-500">++ <!-- Header -->+ <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">+ <!-- Left side: Menu toggle and logo -->+ <div class="flex items-center gap-4">+ <!-- Menu Toggle Button -->+ <button @click="toggleSidebar"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200">+ <i class="fas fa-bars text-lg"></i></button>- {% if current_user.is_authenticated %}- <!-- Add New Recording Button for Mobile Header -->- <button @click="switchToUploadView" class="lg:hidden p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" title="New Recording">++ <!-- Logo and Title -->+ <div class="flex items-center gap-3">+ <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-8 h-8">+ <h1 class="text-xl font-bold text-[var(--text-primary)]">Speakr</h1>+ </div>+ </div>++ <!-- Right side: User menu and controls -->+ <div class="flex items-center gap-3">+ <!-- New Recording Button -->+ <button @click="switchToUploadView"+ class="px-3 py-1.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-sm flex items-center gap-2"><i class="fas fa-plus"></i>+ <span class="hidden sm:inline">New Recording</span></button>- <!-- Mobile User Menu Button -->- <div class="relative lg:hidden">- <button @click="isMobileUserMenuOpen = !isMobileUserMenuOpen" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" title="User Menu">- <i class="fas fa-user"></i>- </button>- <div v-if="isMobileUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-50">- <a href="{{ url_for('account') }}" @click="isMobileUserMenuOpen = false" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-user-circle mr-2"></i> Account- </a>- <button @click="openColorSchemeModal(); isMobileUserMenuOpen = false;" class="w-full text-left px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-palette mr-2"></i> Color Schemes- </button>- {% if current_user.is_admin %}- <a href="{{ url_for('admin') }}" @click="isMobileUserMenuOpen = false" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-user-shield mr-2"></i> Admin- </a>- {% endif %}- <a href="{{ url_for('logout') }}" @click="isMobileUserMenuOpen = false" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">- <i class="fas fa-sign-out-alt mr-2"></i> Logout- </a>- </div>- </div>- {% endif %}- <!-- Desktop Menu Items - hidden on small screens, shown on lg and up -->- <div class="hidden lg:flex items-center space-x-2">++ <!-- User menu -->{% if current_user.is_authenticated %}- <button @click="switchToUploadView" class="px-4 py-2 mr-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">- <i class="fas fa-plus mr-1"></i> New Recording- </button>- <button- @click="switchToGalleryView"- :class="{- 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)]': currentView !== 'gallery',- 'bg-[var(--bg-accent)] text-[var(--text-accent)] border border-[var(--border-accent)]': currentView === 'gallery'- }"- class="px-4 py-2 rounded-lg shadow-sm hover:bg-[var(--bg-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-1 transition duration-150 ease-in-out">- <i class="fas fa-images mr-1"></i> Gallery- </button>- <!-- User dropdown menu -->- <div class="relative ml-2">- <button @click="isUserMenuOpen = !isUserMenuOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">- <i class="fas fa-user mr-2"></i>- <span>{{ current_user.username }}</span>- <i class="fas fa-chevron-down ml-2"></i>+ <div class="relative">+ <button @click="isUserMenuOpen = !isUserMenuOpen"+ class="flex items-center gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200">+ <i class="fas fa-user-circle text-lg"></i>+ <span class="hidden sm:inline">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>+ <i class="fas fa-chevron-down text-xs"></i></button>- <div v-if="isUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">- <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-user-circle mr-2"></i> Account++ <!-- User dropdown -->+ <div v-if="isUserMenuOpen"+ class="absolute right-0 mt-2 w-56 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-50">+ <a href="/account" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-cog mr-2 w-4 text-center"></i>Account Settings</a>- <button @click="openColorSchemeModal(); isUserMenuOpen = false;" class="w-full text-left px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-palette mr-2"></i> Color Schemes- </button>{% if current_user.is_admin %}- <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">- <i class="fas fa-user-shield mr-2"></i> Admin+ <a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-user-shield mr-2 w-4 text-center"></i>Admin</a>{% endif %}- <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">- <i class="fas fa-sign-out-alt mr-2"></i> Logout+ <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">+ <i class="fas fa-share-alt mr-2 w-4 text-center"></i>Shared Transcripts+ </button>+ <div class="border-t border-[var(--border-primary)] my-1"></div>+ <button @click="toggleDarkMode" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'" class="mr-2 w-4 text-center"></i>+ <span>${ isDarkMode ? 'Light Mode' : 'Dark Mode' }</span>+ </button>+ <button @click="openColorSchemeModal" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">+ <i class="fas fa-palette mr-2 w-4 text-center"></i>+ <span>Color Scheme</span>+ </button>+ <div class="border-t border-[var(--border-primary)] my-1"></div>+ <a href="/logout" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-sign-out-alt mr-2 w-4 text-center"></i>Logout</a></div></div>- {% else %}- <a href="{{ url_for('login') }}" class="px-4 py-2 ml-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">- <i class="fas fa-sign-in-alt mr-1"></i> Login- </a>- <a href="{{ url_for('register') }}" class="px-4 py-2 ml-2 text-[var(--text-secondary)] hover:text-[var(--text-accent)] border border-[var(--border-secondary)] rounded-lg">- <i class="fas fa-user-plus mr-1"></i> Register- </a>{% endif %}- </div></div></header>- <!-- Reprocess Confirmation Modal -->- <div v-if="showReprocessModal" @click="cancelReprocess" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">- <!-- Header with gradient background -->- <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">- <div class="flex items-center">- <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">- <i class="fas fa-sync-alt text-white text-lg"></i>+ <div class="flex-1 flex overflow-hidden relative">+ <!-- Mobile Sidebar Backdrop -->+ <div v-if="!isSidebarCollapsed && isMobileScreen"+ @click="toggleSidebar"+ class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden">+ </div>++ <!-- Sidebar -->+ <aside :class="['sidebar', isSidebarCollapsed ? 'collapsed' : '']">+ <div class="sidebar-content-wrapper">+ <!-- Sidebar Header -->+ <div class="p-4 border-b border-[var(--border-primary)] flex-shrink-0">+ <div class="flex items-center justify-between mb-4">+ <h2 class="text-lg font-semibold">Recordings</h2>+ <button @click="switchToUploadView"+ class="px-3 py-1.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-sm">+ <i class="fas fa-plus mr-1"></i>New+ </button></div>- <div>- <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1">Confirm Reprocessing</h3>- <p class="text-sm text-[var(--text-muted)] capitalize">${ reprocessType } reprocessing</p>++ <!-- Search and Sort Controls -->+ <div class="space-y-3">+ <!-- Search Input -->+ <div class="relative">+ <input v-model="searchQuery"+ type="text"+ placeholder="Search recordings... (try: date:today, date:2025-01)"+ class="w-full px-3 py-2 pl-9 pr-8 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] text-sm"></i>+ <button v-if="searchQuery"+ @click="searchQuery = ''"+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)] text-sm">+ <i class="fas fa-times"></i>+ </button>+ </div>++ <!-- Sort Toggle -->+ <button @click="sortBy = sortBy === 'created_at' ? 'meeting_date' : 'created_at'"+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">+ <span class="flex items-center">+ <i :class="['fas mr-2 text-[var(--text-muted)]', sortBy === 'meeting_date' ? 'fa-calendar' : 'fa-upload']"></i>+ Sort by: ${sortBy === 'meeting_date' ? 'Meeting Date' : 'Upload Date'}+ </span>+ <i class="fas fa-exchange-alt text-[var(--text-muted)]"></i>+ </button>++ <!-- Search Help -->+ <div class="text-xs text-[var(--text-muted)] space-y-1">+ <button @click="searchTipsExpanded = !searchTipsExpanded" class="flex items-center justify-between w-full text-left">+ <span>Search tips:</span>+ <i :class="['fas', 'fa-chevron-down', 'transition-transform', { 'rotate-180': searchTipsExpanded }]"></i>+ </button>+ <div v-if="searchTipsExpanded" class="pl-2 space-y-0.5 pt-1">+ <div>• <code class="bg-[var(--bg-tertiary)] px-1 rounded">date:today</code> - Today's recordings</div>+ <div>• <code class="bg-[var(--bg-tertiary)] px-1 rounded">date:2025-01</code> - January 2025</div>+ <div>• <code class="bg-[var(--bg-tertiary)] px-1 rounded">date:thisweek</code> - This week</div>+ </div>+ </div></div></div>- </div>-- <!-- Content -->- <div class="p-6 modal-content">- <div v-if="reprocessRecording" class="mb-6">- <div class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)]">- <div class="flex items-start space-x-3">- <i class="fas fa-file-audio text-[var(--text-accent)] mt-1"></i>- <div class="flex-1 min-w-0">- <h4 class="font-medium text-[var(--text-primary)] truncate" :title="reprocessRecording.title">- ${ reprocessRecording.title || 'Untitled Recording' }- </h4>- <p class="text-sm text-[var(--text-muted)] mt-1">- Created: ${ new Date(reprocessRecording.created_at).toLocaleDateString() }- </p>++ <!-- Recordings List -->+ <div class="flex-1 overflow-y-auto p-4">+ <div v-if="isLoadingRecordings" class="text-center py-8">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ <p class="mt-2 text-[var(--text-muted)]">Loading recordings...</p>+ </div>++ <div v-else-if="filteredRecordings.length === 0" class="text-center py-8">+ <i class="fas fa-microphone-slash text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No recordings found</p>+ </div>++ <div v-else class="space-y-2">+ <div v-for="group in groupedRecordings" :key="group.title" class="mb-6">+ <h3 class="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">+ ${group.title}+ </h3>+ <div class="space-y-1">+ <div v-for="recording in group.items"+ :key="recording.id"+ @click="selectRecording(recording)"+ :class="[+ 'p-3 rounded-lg cursor-pointer transition-all duration-200 border',+ selectedRecording?.id === recording.id+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)]'+ : 'bg-[var(--bg-tertiary)] border-transparent hover:bg-[var(--bg-accent-hover)]'+ ]">+ <div class="flex items-start justify-between">+ <div class="flex-1 min-w-0">+ <h4 class="font-medium text-sm truncate" :class="selectedRecording?.id === recording.id ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]'">+ ${recording.title || 'Untitled Recording'}+ </h4>+ <p class="text-xs text-[var(--text-muted)] mt-1">+ ${formatDisplayDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at)}+ </p>+ <div v-if="recording.participants" class="text-xs text-[var(--text-muted)] mt-1 truncate">+ ${recording.participants}+ </div>+ </div>+ <div class="flex items-center gap-1 ml-2">+ <!-- Show Failed status for failed recordings -->+ <span v-if="recording.status === 'FAILED'"+ class="status-badge status-failed">+ <i class="fas fa-exclamation-circle mr-1"></i>+ Failed+ </span>++ <!-- Show Processing status for non-completed recordings -->+ <span v-else-if="recording.status !== 'COMPLETED'"+ :class="getStatusClass(recording.status)"+ class="status-badge">+ ${formatStatus(recording.status)}+ </span>++ <!-- For completed recordings, show highlight and inbox badges -->+ <template v-else>+ <span v-if="recording.is_highlighted"+ @click.stop="toggleHighlight(recording)"+ class="status-badge status-highlighted clickable-badge"+ title="Remove from starred">+ <i class="fas fa-star"></i>+ </span>+ <span v-if="recording.is_inbox"+ @click.stop="toggleInbox(recording)"+ class="status-badge status-inbox clickable-badge"+ title="Mark as read">+ <i class="fas fa-inbox"></i>+ </span>+ </template>+ </div>+ </div>+ </div></div></div></div></div>-- <div class="space-y-4">- <div class="flex items-start space-x-3">- <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">- <i class="fas fa-exclamation-triangle text-amber-600 text-xs"></i>- </div>- <div>- <p class="text-[var(--text-secondary)] font-medium mb-1">What will happen?</p>- <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">- The audio will be re-transcribed from scratch. This will also regenerate the title and summary based on the new transcription.- </p>- <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">- The audio will be re-transcribed using the ASR endpoint. This includes diarization and will regenerate the title and summary.- </p>- <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">- A new title and summary will be generated based on the existing transcription.- </p>- </div>+ </div>+ </aside>++ <!-- Main Content -->+ <main class="main-content"+ :class="{ 'sidebar-open': !isSidebarCollapsed }"+ @dragover.prevent="handleDragOver"+ @dragleave="handleDragLeave"+ @drop.prevent="handleDrop">++ <!-- Drag Overlay -->+ <div v-if="dragover" class="absolute inset-0 bg-[var(--bg-accent)] bg-opacity-90 flex items-center justify-center z-50 pointer-events-none">+ <div class="text-center p-8 bg-[var(--bg-secondary)] rounded-xl shadow-2xl border-2 border-dashed border-[var(--border-accent)]">+ <i class="fas fa-cloud-upload-alt text-6xl text-[var(--text-accent)] mb-4"></i>+ <h3 class="text-2xl font-bold text-[var(--text-primary)] mb-2">Drop Audio Files Here</h3>+ <p class="text-[var(--text-muted)]">Release to upload your audio files</p>+ </div>+ </div>++ <div class="flex-1 flex flex-col overflow-hidden">+ <!-- Upload View -->+ <div v-if="currentView === 'upload'" class="flex-1 flex items-center justify-center p-4 md:p-8">+ <div class="max-w-lg w-full">+ <div class="text-center mb-8">+ <i class="fas fa-microphone text-5xl md:text-6xl text-[var(--text-accent)] mb-4"></i>+ <h2 class="text-2xl md:text-3xl font-bold mb-2">Upload or Record Audio</h2>+ <p class="text-[var(--text-muted)]">Drag and drop an audio file, click to browse, or start a new recording.</p></div>- <!-- ASR Options -->- <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">- <h4 class="text-md font-semibold text-[var(--text-secondary)]">ASR Options</h4>- <div>- <label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Language</label>- <input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-xl border border-[var(--border-primary)]">+ <!-- File Upload Area -->+ <div @drop="handleDrop" @dragover="handleDragOver" @dragleave="handleDragLeave" @click="$refs.fileInput.click()"+ :class="['border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all duration-300', dragover ? 'border-[var(--border-accent)] bg-[var(--bg-accent)]' : 'border-[var(--border-secondary)] hover:border-[var(--border-accent)]']">+ <i class="fas fa-cloud-upload-alt text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-secondary)] mb-2">Click to upload or drag and drop</p>+ <p class="text-xs text-[var(--text-muted)]">Supports MP3, WAV, M4A, AMR, and more</p></div>- <div>- <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Min Speakers</label>- <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional">+ <input ref="fileInput" type="file" @change="handleFileSelect" accept="audio/*" multiple class="hidden">++ <!-- Divider -->+ <div class="my-6 flex items-center">+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div>+ <span class="flex-shrink mx-4 text-xs text-[var(--text-muted)] uppercase">Or</span>+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div></div>- <div>- <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Max Speakers</label>- <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional">++ <!-- Audio Recording Options -->+ <div class="space-y-3">+ <h3 class="text-sm font-medium text-[var(--text-secondary)] text-center">Recording Options</h3>++ <!-- Microphone Recording -->+ <button @click="startRecording('microphone')"+ class="w-full px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2">+ <i class="fas fa-microphone"></i>+ <span>Record Microphone</span>+ </button>++ <!-- System Audio Recording -->+ <button @click="startRecording('system')"+ v-if="canRecordSystemAudio"+ class="w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2">+ <i class="fas fa-desktop"></i>+ <span>Record System Audio</span>+ </button>++ <!-- Both Audio Sources -->+ <button @click="startRecording('both')"+ v-if="canRecordSystemAudio"+ class="w-full px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center justify-center gap-2">+ <i class="fas fa-microphone"></i>+ <i class="fas fa-desktop ml-1"></i>+ <span>Record Both</span>+ </button>++ <!-- Help Text -->+ <div class="text-xs text-[var(--text-muted)] space-y-1 mt-3">+ <div class="flex items-center justify-between">+ <span><strong>Microphone:</strong> Records your voice only</span>+ <i class="fas fa-microphone text-red-500 flex-shrink-0"></i>+ </div>+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">+ <span><strong>System Audio:</strong> Records meeting participants and system sounds</span>+ <i class="fas fa-desktop text-blue-500 flex-shrink-0"></i>+ </div>+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">+ <span><strong>Both:</strong> Records your voice + meeting participants (recommended for online meetings)</span>+ <div class="flex items-center gap-1 flex-shrink-0">+ <i class="fas fa-microphone text-purple-500"></i>+ <i class="fas fa-desktop text-purple-500"></i>+ </div>+ </div>+ <div v-if="!canRecordSystemAudio" class="text-amber-600 dark:text-amber-400">+ <i class="fas fa-exclamation-triangle mr-1"></i>+ System audio recording not supported in this browser+ <button @click="showSystemAudioHelp = true" class="ml-2 text-blue-500 hover:text-blue-600 underline text-sm">+ Help+ </button>+ </div>+ </div></div></div>-- <div class="flex items-start space-x-3">- <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">- <i class="fas fa-clock text-blue-600 text-xs"></i>+ </div>+ </div>++ <!-- Recording View -->+ <div v-else-if="currentView === 'recording'" class="flex-1 flex flex-col p-4 md:p-8 bg-[var(--bg-primary)]">+ <div class="flex-1 flex flex-col max-w-4xl w-full mx-auto bg-[var(--bg-secondary)] rounded-xl border border-[var(--border-primary)] overflow-hidden">+ <!-- Top: Visualizer and Status -->+ <div class="flex-shrink-0 p-4 md:p-6 text-center bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)]">+ <div v-if="isRecording" class="w-full mx-auto mb-4">+ <!-- Dual visualizer for 'both' mode -->+ <div v-if="recordingMode === 'both'" class="max-w-4xl mx-auto flex gap-4">+ <div class="w-1/2 h-32 md:h-40 flex flex-col bg-[var(--bg-primary)] rounded-lg p-2">+ <div class="flex-1 w-full overflow-hidden rounded-md">+ <canvas ref="micVisualizer" class="w-full h-full"></canvas>+ </div>+ <p class="text-xs text-[var(--text-muted)] pt-1">Microphone</p>+ </div>+ <div class="w-1/2 h-32 md:h-40 flex flex-col bg-[var(--bg-primary)] rounded-lg p-2">+ <div class="flex-1 w-full overflow-hidden rounded-md">+ <canvas ref="systemVisualizer" class="w-full h-full"></canvas>+ </div>+ <p class="text-xs text-[var(--text-muted)] pt-1">System Audio</p>+ </div>+ </div>+ <!-- Single visualizer for other modes -->+ <div v-else class="h-32 md:h-40 max-w-2xl mx-auto bg-[var(--bg-primary)] rounded-lg p-2 flex flex-col">+ <div class="flex-1 w-full overflow-hidden rounded-md">+ <canvas ref="visualizer" class="w-full h-full"></canvas>+ </div>+ <p class="text-xs text-[var(--text-muted)] pt-1 capitalize">${recordingMode}</p>+ </div>+ </div>+ <div v-if="!isRecording && audioBlobURL" class="h-24 md:h-32 w-full flex items-center justify-center mb-4">+ <audio :src="audioBlobURL" controls class="w-full max-w-md"></audio></div><div>- <p class="text-[var(--text-secondary)] font-medium mb-1">Processing time</p>- <p class="text-sm text-[var(--text-muted)]">- This may take a few minutes to complete. You can continue using the app while processing.- </p>+ <div class="text-2xl font-mono text-[var(--text-accent)]">${formatTime(recordingTime)}</div>+ <p class="text-sm text-[var(--text-muted)]">${ isRecording ? 'Recording in progress...' : 'Recording finished' }</p></div></div>- <div class="flex items-start space-x-3" v-if="reprocessType === 'transcription'">- <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">- <i class="fas fa-info-circle text-red-600 text-xs"></i>- </div>- <div>- <p class="text-[var(--text-secondary)] font-medium mb-1">Important note</p>- <p class="text-sm text-[var(--text-muted)]">- Any manual edits to the transcription, title, or summary will be overwritten.- </p>+ <!-- Middle: Notepad -->+ <div class="flex-1 p-4 md:p-6 min-h-0 overflow-hidden flex flex-col">+ <label for="recordingNotes" class="block text-sm font-medium text-[var(--text-secondary)] mb-2 flex-shrink-0">+ <i class="fas fa-pencil-alt mr-1"></i>+ Recording Notes (Markdown)+ </label>+ <div class="flex-1 min-h-0 recording-notes-editor">+ <textarea ref="recordingNotesEditor" v-model="recordingNotes"+ class="w-full h-full bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg p-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] resize-none"+ placeholder="Type your notes in Markdown format..."+ rows="10"></textarea></div></div>- <div class="flex items-start space-x-3" v-else-if="reprocessType === 'summary'">- <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">- <i class="fas fa-info-circle text-red-600 text-xs"></i>+ <!-- Bottom: Action Buttons -->+ <div class="flex-shrink-0 p-4 md:p-6 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)]">+ <div v-if="isRecording" class="text-center">+ <button @click="stopRecording"+ class="px-8 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors animate-pulse">+ <i class="fas fa-stop mr-2"></i>Stop Recording+ </button></div>- <div>- <p class="text-[var(--text-secondary)] font-medium mb-1">Important note</p>- <p class="text-sm text-[var(--text-muted)]">- Any manual edits to the title or summary will be overwritten.- </p>+ <div v-if="!isRecording && audioBlobURL" class="flex flex-col sm:flex-row gap-3 justify-center">+ <button @click="uploadRecordedAudio"+ class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2">+ <i class="fas fa-upload"></i>+ <span>Upload Recording & Notes</span>+ </button>+ <button @click="discardRecording"+ class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors flex items-center justify-center gap-2">+ <i class="fas fa-trash"></i>+ <span>Discard</span>+ </button></div></div></div></div>-- <!-- Footer with action buttons -->- <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">- <button- @click="cancelReprocess"- class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">- <i class="fas fa-times mr-2"></i>- Cancel- </button>- <button- @click="executeReprocess"- class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center shadow-lg font-medium transform hover:scale-105">- <i class="fas fa-sync-alt mr-2"></i>- Start Reprocessing- </button>- </div>- </div>- </div>- <!-- Reset Status Confirmation Modal -->- <div v-if="showResetModal" @click="cancelReset" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">- <div class="p-6 text-center">- <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 dark:bg-orange-800 mb-4">- <i class="fas fa-exclamation-triangle text-2xl text-orange-500 dark:text-orange-300"></i>- </div>- <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2">Reset Recording Status?</h3>- <p class="text-sm text-[var(--text-muted)] mb-6">- This will mark the recording as 'Failed'. This is useful if processing is stuck. You will be able to reprocess it afterwards.- </p>- </div>- <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3">- <button @click="cancelReset" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">- Cancel- </button>- <button @click="executeReset" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600">- Yes, Reset Status- </button>- </div>- </div>- </div>- <!-- Speaker Identification Modal -->- <div v-if="showSpeakerModal" @click="closeSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-4xl flex flex-col max-h-[90vh]">- <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0">- <h3 class="text-xl font-bold text-[var(--text-primary)]">Identify Speakers</h3>- <!-- Warning for too many speakers -->- <div v-if="identifiedSpeakers.length > 8" class="mt-3 p-3 bg-[var(--bg-warn-light)] border border-amber-300 dark:border-amber-800 rounded-lg">- <div class="flex items-start">- <i class="fas fa-exclamation-triangle text-[var(--text-warn-strong)] mt-0.5 mr-2"></i>- <div class="text-sm">- <p class="font-medium text-[var(--text-warn-strong)]">More speakers than available colors</p>- <p class="text-[var(--text-warn-strong)] mt-1">- You have ${ identifiedSpeakers.length } speakers, but only 8 unique colors are available.- Colors will repeat after the 8th speaker.- </p>++ <!-- Recording Detail View -->+ <div v-else-if="currentView === 'detail' && selectedRecording" class="flex-1 flex flex-col overflow-hidden">+ <!-- Mobile View -->+ <div v-if="isMobileScreen" class="flex-1 flex flex-col overflow-hidden">+ <!-- Mobile Header -->+ <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-4 flex-shrink-0">+ <div @click="isMetadataExpanded = !isMetadataExpanded" class="cursor-pointer">+ <div class="flex items-start justify-between">+ <div class="flex-1 min-w-0">+ <h1 class="text-lg font-bold text-[var(--text-primary)] truncate">+ ${selectedRecording.title || 'Untitled Recording'}+ </h1>+ <p class="text-sm text-[var(--text-muted)] truncate">+ ${selectedRecording.participants || 'No participants'}+ </p>+ </div>+ <i :class="['fas', 'fa-chevron-down', 'transition-transform', { 'rotate-180': isMetadataExpanded }]"></i>+ </div></div>- </div>- </div>- </div>- <div class="flex-grow flex overflow-hidden modal-content">- <div class="w-1/3 p-6 space-y-4 overflow-y-auto custom-scrollbar border-r border-[var(--border-primary)]">- <div v-for="(speaker, index) in identifiedSpeakers" :key="speaker" class="space-y-3">- <!-- Speaker label with color indicator and "This is Me" checkbox on same line -->- <div class="flex items-center justify-between">- <div class="flex items-center space-x-2">- <div :class="speakerMap[speaker].color" class="w-4 h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>- <span class="font-mono text-sm text-[var(--text-muted)]">${ speaker }</span>- <span v-if="index >= 8" class="text-xs text-[var(--text-warn-strong)] bg-[var(--bg-warn-light)] px-2 py-0.5 rounded-full" title="Color repeats from speaker ${ ((index % 8) + 1) }">- Repeat- </span>+ <!-- Expandable Metadata and Actions -->+ <div v-if="isMetadataExpanded" class="mt-4 space-y-4">+ <div class="space-y-2 text-sm text-[var(--text-muted)]">+ <div class="flex items-center gap-2">+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>+ <span>${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}</span>+ </div>+ <div v-if="activeRecordingMetadata" class="flex flex-wrap items-center gap-x-4 gap-y-2">+ <span v-for="(item, index) in activeRecordingMetadata" :key="index" class="flex items-center gap-1.5">+ <i :class="item.icon"></i>+ <span :title="item.fullText || item.text">${item.text}</span>+ </span>+ </div>+ <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">+ <span :class="getStatusClass(selectedRecording.status)" class="status-badge">+ ${formatStatus(selectedRecording.status)}+ </span>+ </div>+ </div>+ <!-- Action Buttons -->+ <div class="flex items-center gap-2 overflow-x-auto pb-2">+ <button @click="toggleInbox(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_inbox ? 'text-blue-500' : ''" :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'"><i class="fas fa-inbox"></i></button>+ <button @click="toggleHighlight(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''" :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'"><i class="fas fa-star"></i></button>+ <button @click="editRecording(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-edit"></i></button>+ <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'"><i class="fas fa-redo-alt"></i></button>+ <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" title="Reprocess summary"><i class="fas fa-sync-alt"></i></button>+ <button @click="confirmReset(selectedRecording)" v-if="['PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500" title="Reset stuck processing"><i class="fas fa-undo"></i></button>+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" title="Identify Speakers"><i class="fas fa-user-tag"></i></button>+ <button @click="confirmDelete(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors"><i class="fas fa-trash"></i></button></div>- <label class="flex items-center text-sm text-[var(--text-muted)]">- <input type="checkbox" v-model="speakerMap[speaker].isMe" @focus="highlightSpeakerInTranscript(speaker)" @blur="clearSpeakerHighlight" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">- <span class="ml-2">Me</span>- </label></div>-- <!-- Autocomplete input field - disabled when "This is Me" is checked -->- <div class="relative">- <input- type="text"- v-model="speakerMap[speaker].name"- @input="searchSpeakers($event.target.value, speaker)"- @focus="highlightSpeakerInTranscript(speaker)"- @blur="clearSpeakerHighlight(); setTimeout(() => speakerSuggestions[speaker] = [], 200)"- :disabled="speakerMap[speaker].isMe"- class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"- :placeholder="speakerMap[speaker].isMe ? 'Me' : 'Enter name for ' + speaker"- autocomplete="off">-- <!-- Loading indicator -->- <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe" class="absolute right-3 top-1/2 transform -translate-y-1/2">- <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>+ </div>++ <!-- Mobile Audio Player -->+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">+ <audio controls :src="'/audio/' + selectedRecording.id" class="w-full"></audio>+ </div>++ <!-- Mobile Tab Navigation -->+ <div class="flex-shrink-0 bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex overflow-x-auto">+ <button @click="mobileTab = 'transcript'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'transcript' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">Transcript</button>+ <button @click="mobileTab = 'summary'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'summary' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">Summary</button>+ <button @click="mobileTab = 'notes'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'notes' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">Notes</button>+ <button @click="mobileTab = 'chat'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'chat' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">Chat</button>+ </div>++ <!-- Mobile Tab Content -->+ <div class="flex-1 overflow-y-auto p-4">+ <!-- Transcript Panel -->+ <div v-if="mobileTab === 'transcript'" class="h-full flex flex-col space-y-4">+ <div class="flex items-center justify-end gap-2 flex-shrink-0">+ <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">+ <button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']"><i class="fas fa-list"></i></button>+ <button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']"><i class="fas fa-comments"></i></button>+ </div>+ <button @click="copyTranscription" class="copy-btn"><i class="fas fa-copy"></i></button>+ <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn"><i class="fas fa-edit"></i></button></div>-- <!-- Suggestions dropdown -->- <div v-if="speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"- class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">- <div class="py-1">- <div v-for="suggestion in speakerSuggestions[speaker]"- :key="suggestion.id"- @mousedown="selectSpeakerSuggestion(speaker, suggestion)"- class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">- <div class="flex-grow">- <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>- <div class="text-xs text-[var(--text-muted)]">- Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }- <span v-if="suggestion.last_used">- • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }- </span>+ <div class="flex-grow overflow-y-auto mobile-content-box">+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ <p class="mt-2 text-[var(--text-muted)]">Processing transcription...</p>+ </div>+ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No transcription available</p>+ </div>+ <div v-else>+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'" class="transcription-simple-view">+ <div v-if="processedTranscription.hasDialogue">+ <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="speaker-segment" @click="seekAudioFromEvent" :data-start-time="segment.startTime">+ <div v-if="segment.showSpeaker" :class="['speaker-tablet', segment.color]">${segment.speaker}</div>+ <div class="speaker-text">${segment.sentence}</div>+ </div>+ </div>+ <div v-else>+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">+ <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors" @click="seekAudioFromEvent" :data-start-time="segment.startTime">${segment.sentence}</div>+ </div>+ <div v-else class="whitespace-pre-wrap">${processedTranscription.content}</div>+ </div>+ </div>+ <div v-else-if="transcriptionViewMode === 'bubble'" class="transcription-with-speakers">+ <div v-for="(row, rowIndex) in processedTranscription.bubbleRows" :key="`${selectedRecording.id}-bubble-row-${rowIndex}`" :class="['bubble-row', row.isMe ? 'speaker-me' : '']">+ <div v-for="bubble in row.bubbles" :key="bubble.startTime || Math.random()" :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']" @click="seekAudioFromEvent" :data-start-time="bubble.startTime">+ <div class="speaker-bubble-content">${bubble.sentence}</div></div></div>- <i class="fas fa-user text-[var(--text-muted)] ml-2"></i></div></div></div></div>- </div>- </div>- <div class="w-2/3 p-6 flex flex-col overflow-hidden">- <!-- Audio Player Section -->- <div class="mb-4 flex-shrink-0">- <h4 class="font-semibold text-[var(--text-secondary)] mb-2">Audio Player</h4>- <div class="bg-[var(--bg-audio-player)] p-3 rounded-lg shadow border border-[var(--border-primary)]">- <audio controls class="w-full h-10 speaker-modal-transcript" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">- Your browser does not support the audio element.- </audio>- </div>- </div>-- <!-- Transcript Section -->- <div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent">- <div v-if="processedTranscription.isJson">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2" :data-start-time="segment.startTime">- <p>- <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId">[${ segment.speaker }]</span>:- <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5">${ segment.sentence }</span>- </p>+ <!-- Summary Panel -->+ <div v-if="mobileTab === 'summary'" class="h-full flex flex-col space-y-4">+ <div class="flex items-center justify-end gap-2 flex-shrink-0">+ <button @click="copySummary" class="copy-btn"><i class="fas fa-copy"></i></button>+ <button @click="toggleEditSummary" class="copy-btn"><i class="fas fa-edit"></i></button></div>- </div>- <div v-else v-html="highlightedTranscript"></div>- </div>- </div>- </div>- <div class="p-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex-shrink-0">- <label class="flex items-center text-sm text-[var(--text-muted)]">- <input type="checkbox" v-model="regenerateSummaryAfterSpeakerUpdate" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">- <span class="ml-2">Regenerate summary after updating names</span>- </label>- </div>- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">- <div>- <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">- <i class="fas fa-magic mr-2"></i>- <span v-if="!isAutoIdentifying">Auto Identify</span>- <span v-else>- <i class="fas fa-spinner fa-spin mr-2"></i>- Identifying...- </span>- </button>- </div>- <div class="flex space-x-3">- <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>- <button- @click="saveSpeakerNames"- :disabled="!hasSpeakerNames"- :class="hasSpeakerNames- ? 'px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer'- : 'px-4 py-2 bg-gray-400 text-gray-200 rounded-lg cursor-not-allowed'"- >- Save Names- </button>- </div>- </div>- </div>- </div>-- <!-- Color Scheme Modal -->- <div v-if="showColorSchemeModal" @click="closeColorSchemeModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">- <!-- Header -->- <div class="p-6 border-b border-[var(--border-primary)] flex-shrink-0">- <div class="flex items-center justify-between">- <div class="flex items-center">- <div class="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-600 rounded-full flex items-center justify-center mr-4 shadow-lg">- <i class="fas fa-palette text-white text-lg"></i>- </div>- <div>- <h3 class="text-xl font-bold text-[var(--text-primary)]">Color Schemes</h3>- <p class="text-sm text-[var(--text-muted)]">Choose your preferred color theme</p>- </div>- </div>- <button @click="closeColorSchemeModal" class="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors duration-200 rounded-full h-8 w-8 flex items-center justify-center hover:bg-[var(--bg-tertiary)]">- <i class="fas fa-times"></i>- </button>- </div>- </div>-- <!-- Content -->- <div class="p-6 overflow-y-auto custom-scrollbar modal-content flex-grow">- <!-- Current Mode Indicator -->- <div class="mb-6 p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)]">- <div class="flex items-center justify-between">- <div class="flex items-center">- <i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'" class="text-[var(--text-accent)] mr-3"></i>- <div>- <p class="font-medium text-[var(--text-primary)]">Current Mode: ${ isDarkMode ? 'Dark' : 'Light' }</p>- <p class="text-sm text-[var(--text-muted)]">Switch between light and dark modes using the toggle in the header</p>+ <div class="flex-grow overflow-y-auto mobile-content-box">+ <div v-if="editingSummary" class="h-full flex flex-col">+ <div class="markdown-editor-container flex-1">+ <textarea ref="summaryMarkdownEditor" v-model="selectedRecording.summary"></textarea>+ </div>+ <div class="flex justify-end gap-2 mt-2">+ <button @click="cancelEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button @click="saveEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">Save</button>+ </div>+ </div>+ <div v-else>+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ <p class="mt-2 text-[var(--text-muted)]">Generating summary...</p>+ </div>+ <div v-else-if="!selectedRecording.summary" class="text-center py-8">+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No summary available</p>+ </div>+ <div v-else class="summary-box h-full" v-html="selectedRecording.summary_html || selectedRecording.summary"></div>+ </div></div></div>- <div class="text-right">- <p class="text-sm font-medium text-[var(--text-secondary)]">Active Theme</p>- <p class="text-xs text-[var(--text-muted)]">${ colorSchemes[isDarkMode ? 'dark' : 'light'].find(s => s.id === currentColorScheme)?.name || 'Unknown' }</p>+ <!-- Notes Panel -->+ <div v-if="mobileTab === 'notes'" class="h-full flex flex-col space-y-4">+ <div class="flex items-center justify-end gap-2 flex-shrink-0">+ <button @click="copyNotes" class="copy-btn"><i class="fas fa-copy"></i></button>+ <button @click="toggleEditNotes" class="copy-btn"><i class="fas fa-edit"></i></button>+ </div>+ <div class="flex-grow overflow-y-auto mobile-content-box">+ <div v-if="editingNotes" class="h-full flex flex-col">+ <div class="markdown-editor-container flex-1">+ <textarea ref="notesMarkdownEditor" v-model="selectedRecording.notes"></textarea>+ </div>+ <div class="flex justify-end gap-2 mt-2">+ <button @click="cancelEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button @click="saveEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">Save</button>+ </div>+ </div>+ <div v-else>+ <div v-if="!selectedRecording.notes" class="text-center py-8">+ <i class="fas fa-sticky-note text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No notes available</p>+ </div>+ <div v-else class="notes-box h-full" v-html="selectedRecording.notes_html || selectedRecording.notes"></div>+ </div>+ </div></div>- </div>- </div>-- <!-- Light Mode Themes -->- <div class="mb-8">- <h4 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">- <i class="fas fa-sun text-yellow-500 mr-2"></i>- Light Mode Themes- </h4>- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div v-for="scheme in colorSchemes.light" :key="'light-' + scheme.id"- @click="selectColorScheme(scheme.id)"- class="cursor-pointer p-4 rounded-lg border-2 transition-all duration-200 hover:shadow-lg"- :class="!isDarkMode && currentColorScheme === scheme.id ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20' : 'border-[var(--border-secondary)] hover:border-[var(--border-accent)]'">- <div class="flex items-center justify-between mb-3">- <h5 class="font-semibold text-[var(--text-primary)]">${ scheme.name }</h5>- <div v-if="!isDarkMode && currentColorScheme === scheme.id" class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">- <i class="fas fa-check text-white text-xs"></i>+ <!-- Chat Panel -->+ <div v-if="mobileTab === 'chat'" class="h-full flex flex-col rounded-lg border border-[var(--border-primary)] overflow-hidden">+ <div ref="chatMessagesRef" class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">+ <div v-if="chatMessages.length === 0" class="text-center py-8">+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">Ask questions about this transcription</p>+ </div>+ <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.role === 'user' ? 'user-message ml-auto' : 'ai-message']">+ <div v-if="message.html" v-html="message.html"></div>+ <div v-else class="whitespace-pre-wrap">${message.content}</div>+ </div>+ <div v-if="isChatLoading" class="ai-message">+ <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...</div></div>- <p class="text-sm text-[var(--text-muted)] mb-3">${ scheme.description }</p>- <!-- Color Preview -->- <div class="flex space-x-2">- <div class="w-6 h-6 rounded-full" :class="scheme.id === 'blue' ? 'bg-blue-500' : scheme.id === 'emerald' ? 'bg-emerald-500' : scheme.id === 'purple' ? 'bg-purple-500' : scheme.id === 'rose' ? 'bg-rose-500' : scheme.id === 'amber' ? 'bg-amber-500' : 'bg-teal-500'"></div>- <div class="w-6 h-6 rounded-full" :class="scheme.id === 'blue' ? 'bg-blue-100' : scheme.id === 'emerald' ? 'bg-emerald-100' : scheme.id === 'purple' ? 'bg-purple-100' : scheme.id === 'rose' ? 'bg-rose-100' : scheme.id === 'amber' ? 'bg-amber-100' : 'bg-teal-100'"></div>- <div class="w-6 h-6 rounded-full bg-gray-100"></div>- <div class="w-6 h-6 rounded-full bg-white border border-gray-200"></div>+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">+ <div class="flex gap-2">+ <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'" placeholder="Ask about this transcription..." class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>+ <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">+ <i class="fas fa-paper-plane"></i>+ </button>+ </div></div></div></div></div>-- <!-- Dark Mode Themes -->- <div>- <h4 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">- <i class="fas fa-moon text-blue-400 mr-2"></i>- Dark Mode Themes- </h4>- <div class="grid grid-cols-1 md:grid-cols-2 gap-4">- <div v-for="scheme in colorSchemes.dark" :key="'dark-' + scheme.id"- @click="selectColorScheme(scheme.id)"- class="cursor-pointer p-4 rounded-lg border-2 transition-all duration-200 hover:shadow-lg"- :class="isDarkMode && currentColorScheme === scheme.id ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20' : 'border-[var(--border-secondary)] hover:border-[var(--border-accent)]'">- <div class="flex items-center justify-between mb-3">- <h5 class="font-semibold text-[var(--text-primary)]">${ scheme.name }</h5>- <div v-if="isDarkMode && currentColorScheme === scheme.id" class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">- <i class="fas fa-check text-white text-xs"></i>+ <!-- Desktop View -->+ <div v-else class="flex-1 flex flex-col overflow-hidden">+ <!-- Recording Header -->+ <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-6 flex-shrink-0">+ <div class="flex flex-col">+ <div class="flex items-start justify-between">+ <div class="flex-1 min-w-0">+ <h1 class="text-2xl font-bold text-[var(--text-primary)] mb-2">+ ${selectedRecording.title || 'Untitled Recording'}+ </h1>+ </div>++ <!-- Action Buttons -->+ <div class="flex items-center gap-2 ml-4">+ <button @click="toggleInbox(selectedRecording)"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ :class="selectedRecording.is_inbox ? 'text-blue-500' : ''"+ :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">+ <i class="fas fa-inbox"></i>+ </button>+ <button @click="toggleHighlight(selectedRecording)"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''"+ :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">+ <i class="fas fa-star"></i>+ </button>+ <button @click="editRecording(selectedRecording)"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-edit"></i>+ </button>+ <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">+ <i class="fas fa-redo-alt"></i>+ </button>+ <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ title="Reprocess summary">+ <i class="fas fa-sync-alt"></i>+ </button>+ <button @click="confirmReset(selectedRecording)" v-if="['PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"+ title="Reset stuck processing">+ <i class="fas fa-undo"></i>+ </button>+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ title="Identify Speakers">+ <i class="fas fa-user-tag"></i>+ </button>+ <button @click="confirmDelete(selectedRecording)"+ class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">+ <i class="fas fa-trash"></i>+ </button>+ <button @click="openShareModal(selectedRecording)"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ title="Share Recording">+ <i class="fas fa-share-alt"></i>+ </button></div></div>- <p class="text-sm text-[var(--text-muted)] mb-3">${ scheme.description }</p>- <!-- Color Preview -->- <div class="flex space-x-2">- <div class="w-6 h-6 rounded-full" :class="scheme.id === 'blue' ? 'bg-blue-600' : scheme.id === 'emerald' ? 'bg-emerald-600' : scheme.id === 'purple' ? 'bg-purple-600' : scheme.id === 'rose' ? 'bg-rose-600' : scheme.id === 'amber' ? 'bg-amber-600' : 'bg-teal-600'"></div>- <div class="w-6 h-6 rounded-full" :class="scheme.id === 'blue' ? 'bg-blue-900' : scheme.id === 'emerald' ? 'bg-emerald-900' : scheme.id === 'purple' ? 'bg-purple-900' : scheme.id === 'rose' ? 'bg-rose-900' : scheme.id === 'amber' ? 'bg-amber-900' : 'bg-teal-900'"></div>- <div class="w-6 h-6 rounded-full bg-gray-700"></div>- <div class="w-6 h-6 rounded-full bg-gray-900 border border-gray-600"></div>++ <!-- Metadata Row -->+ <div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-[var(--text-muted)] mt-2">+ <!-- Participants -->+ <div class="flex items-center gap-2">+ <i class="fas fa-users text-[var(--text-accent)]"></i>+ <span v-if="!editingParticipants"+ @click="toggleEditParticipants"+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">+ ${selectedRecording.participants || 'No participants'}+ </span>+ <input v-else+ v-model="selectedRecording.participants"+ @blur="toggleEditParticipants"+ @keyup.enter="toggleEditParticipants"+ class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">+ </div>++ <!-- Meeting Date -->+ <div class="flex items-center gap-2">+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>+ <span v-if="!editingMeetingDate"+ @click="toggleEditMeetingDate"+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">+ ${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}+ </span>+ <input v-else+ v-model="selectedRecording.meeting_date"+ @blur="toggleEditMeetingDate"+ @keyup.enter="toggleEditMeetingDate"+ type="date"+ class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">+ </div>++ <!-- Other Metadata -->+ <div v-if="activeRecordingMetadata" class="flex flex-wrap items-center gap-x-6 gap-y-2">+ <span v-for="(item, index) in activeRecordingMetadata" :key="index" class="flex items-center gap-1.5">+ <i :class="item.icon"></i>+ <span :title="item.fullText || item.text">${item.text}</span>+ </span>+ </div>++ <!-- Status -->+ <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">+ <span :class="getStatusClass(selectedRecording.status)" class="status-badge">+ ${formatStatus(selectedRecording.status)}+ </span>+ </div></div></div></div>- </div>- </div>-- <!-- Footer -->- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0">- <button @click="resetColorScheme" class="px-4 py-2 text-[var(--text-muted)] hover:text-[var(--text-secondary)] transition-colors duration-200 flex items-center">- <i class="fas fa-undo mr-2"></i>- Reset to Default- </button>- <button @click="closeColorSchemeModal" class="px-6 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors duration-200 flex items-center shadow-sm">- <i class="fas fa-check mr-2"></i>- Done- </button>- </div>- </div>- </div>-- <!-- Overlay for mobile fly-in menu -->- <div v-if="isMobileMenuOpen" @click="closeMobileMenu" class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"></div>-- <div v-if="globalError" class="mb-4 p-4 bg-[var(--bg-danger-light)] border border-[var(--border-danger)] text-[var(--text-danger-strong)] rounded-lg" role="alert">- <div class="flex justify-between items-center">- <div>- <strong class="font-bold">Error:</strong>- <span class="block sm:inline ml-2">${ globalError }</span>- </div>- <button @click="globalError = null" class="text-[var(--text-danger-strong)] hover:text-[var(--text-danger)] font-bold">×</button>- </div>- </div>-- <!-- Sidebar toggle button will be positioned relative to the main container -->-- <main class="flex-grow"- @dragover.prevent="dragover = true"- @dragleave.prevent="handleDragLeave"- @drop.prevent="handleDrop">-- <div v-if="dragover" class="absolute inset-0 flex items-center justify-center bg-[var(--border-focus)]/20 z-10 rounded-lg pointer-events-none border-4 border-dashed border-[var(--border-focus)]">- <div class="text-center p-6 bg-[var(--bg-secondary)] rounded-lg shadow-xl">- <i class="fas fa-upload text-4xl text-[var(--text-accent)] mb-3"></i>- <p class="text-xl font-semibold text-[var(--text-secondary)]">Drop audio file(s) here to upload</p>- </div>- </div>-- {% if current_user.is_authenticated %}- <div v-if="currentView === 'gallery'" class="flex-grow flex flex-col rounded-lg relative">- <!-- Mobile Layout (shown only on mobile when recording is selected) -->- <div v-if="selectedRecording" class="mobile-layout bg-[var(--bg-secondary)] rounded-lg shadow-md">- <!-- New Mobile Header Section -->- <div class="p-4 border-b border-[var(--border-primary)]">- <h3 class="text-xl font-semibold text-[var(--text-primary)] mb-2 truncate" :title="selectedRecording.title || 'Loading...'">- ${ selectedRecording.title || 'Loading...' }- </h3>- <div class="flex items-center justify-between mb-3">- <span v-if="selectedRecording.status" :class="getStatusClass(selectedRecording.status)" class="status-badge text-xs">- ${ formatStatus(selectedRecording.status) }- </span>- <div class="flex space-x-2 items-center">- <button @click="toggleInbox(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105"- :class="selectedRecording.is_inbox ? 'bg-blue-100 text-blue-600 hover:bg-blue-200 dark:bg-blue-800 dark:text-blue-200 dark:hover:bg-blue-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'"- :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">- <i class="fas fa-inbox"></i>- </button>- <button @click="toggleHighlight(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105"- :class="selectedRecording.is_highlighted ? 'bg-yellow-100 text-yellow-600 hover:bg-yellow-200 dark:bg-yellow-700 dark:text-yellow-200 dark:hover:bg-yellow-600' : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'"- :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">- <i class="fas fa-star"></i>- </button>- <button @click="editRecording(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Edit Details">- <i class="fas fa-edit"></i>- </button>- <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">- <i class="fas fa-redo-alt"></i>- </button>- <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Reprocess summary">- <i class="fas fa-sync-alt"></i>- </button>- <button @click="confirmReset(selectedRecording)" v-if="selectedRecording && (selectedRecording.status === 'PROCESSING' || selectedRecording.status === 'SUMMARIZING')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-orange-100 text-orange-600 hover:bg-orange-200 dark:bg-orange-700 dark:text-orange-200 dark:hover:bg-orange-600"- title="Reset Stuck Status">- <i class="fas fa-power-off"></i>- </button>- <button @click="openSpeakerModal" v-if="identifiedSpeakers.length > 0"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Identify Speakers">- <i class="fas fa-user-tag"></i>- </button>- <button @click="confirmDelete(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] hover:bg-[var(--bg-danger)] hover:text-[var(--text-button)]"- title="Delete Recording">- <i class="fas fa-trash"></i>- </button>- </div>- </div>- </div>-- <!-- Mobile Audio Player Section -->- <div class="mobile-audio-section border-b border-[var(--border-primary)]">- <h4 class="font-semibold text-sm text-[var(--text-secondary)] mb-1">Audio Player</h4>- <div class="bg-[var(--bg-audio-player)] p-3 rounded-lg shadow border border-[var(--border-primary)]">- <audio controls class="w-full h-10" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">- Your browser does not support the audio element.- </audio>- </div>- </div>-- <!-- Mobile Tab Navigation -->- <div class="mobile-tab-nav">- <div class="tab-list">- <button @click="switchMobileTab('transcript')"- :class="selectedMobileTab === 'transcript' ? 'active' : ''"- class="mobile-tab-button">- <i class="fas fa-file-text mr-1"></i> Transcript- </button>- <button @click="switchMobileTab('summary')"- :class="selectedMobileTab === 'summary' ? 'active' : ''"- class="mobile-tab-button">- <i class="fas fa-file-alt mr-1"></i> Summary- </button>- <button @click="switchMobileTab('notes')"- :class="selectedMobileTab === 'notes' ? 'active' : ''"- class="mobile-tab-button">- <i class="fas fa-sticky-note mr-1"></i> Notes- </button>- <button @click="switchMobileTab('chat')"- :class="selectedMobileTab === 'chat' ? 'active' : ''"- class="mobile-tab-button">- <i class="fas fa-comments mr-1"></i> Chat- </button>- <button @click="switchMobileTab('metadata')"- :class="selectedMobileTab === 'metadata' ? 'active' : ''"- class="mobile-tab-button">- <i class="fas fa-info-circle mr-1"></i> Metadata- </button>- </div>- </div>- <!-- Mobile Tab Content -->- <div class="mobile-tab-content">- <!-- Transcript Tab -->- <div class="mobile-tab-panel" :class="{ active: selectedMobileTab === 'transcript' }">- <div class="mobile-transcript-content">- <div class="mobile-content-header">- <h4 class="mobile-content-title">Transcription</h4>- <div class="mobile-content-actions">- <!-- View Mode Toggle for Mobile -->+ <!-- Main Content Split View -->+ <div id="mainContentColumns" class="flex-1 flex overflow-hidden">+ <!-- Left Panel: Transcription -->+ <div id="leftMainColumn" class="flex flex-col overflow-hidden" :style="{width: leftColumnWidth + '%'}">+ <!-- Transcription Header -->+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 border-b border-[var(--border-primary)] flex items-center justify-between">+ <h3 class="font-semibold flex items-center">+ <i class="fas fa-file-text mr-2"></i>+ Transcription+ </h3>+ <div class="flex items-center gap-2">+ <!-- View Mode Toggle --><div v-if="processedTranscription.hasDialogue" class="view-mode-toggle"><button @click="toggleTranscriptionViewMode"- :class="{ active: transcriptionViewMode === 'simple' }"- class="toggle-button">- <i class="fas fa-list"></i> Simple+ :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']">+ <i class="fas fa-list"></i>Simple</button><button @click="toggleTranscriptionViewMode"- :class="{ active: transcriptionViewMode === 'bubble' }"- class="toggle-button">- <i class="fas fa-comments"></i> Bubbles+ :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']">+ <i class="fas fa-comments"></i>Bubble</button></div>- <button @click="copyTranscription($event)" class="mobile-action-btn" title="Copy to clipboard">- <i class="fas fa-copy"></i>++ <!-- Copy Button -->+ <button @click="copyTranscription"+ class="copy-btn">+ <i class="fas fa-copy mr-1"></i>Copy+ </button>+ <!-- Edit Transcription Button -->+ <button @click="openTranscriptionEditor"+ v-if="selectedRecording && selectedRecording.transcription"+ class="copy-btn">+ <i class="fas fa-edit mr-1"></i>Edit</button>- <!-- Reprocess transcription button moved to main header --></div></div>- <div class="mobile-content-box">- <div v-if="selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'SUMMARIZING'">- <!-- Speaker Legend (if dialogue detected and bubble view) -->- <div v-if="processedTranscription.hasDialogue && transcriptionViewMode === 'bubble'" class="speaker-legend" :class="{ expanded: legendExpanded }">- <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">- <div class="speaker-legend-title">- <i class="fas fa-users"></i>- <span>Speakers</span>- <span class="speaker-count-indicator">(${ processedTranscription.speakers.length })</span>- </div>- <i class="fas fa-chevron-down speaker-legend-toggle"></i>++ <!-- Transcription Content -->+ <div class="flex-1 overflow-y-auto p-4">+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ <p class="mt-2 text-[var(--text-muted)]">Processing transcription...</p>+ </div>++ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No transcription available</p>+ </div>++ <!-- Speaker Legend (for dialogue transcriptions in bubble view only) -->+ <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"+ :class="['speaker-legend', legendExpanded ? 'expanded' : '']">+ <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">+ <div class="speaker-legend-title">+ <i class="fas fa-users"></i>+ Speakers+ <span class="speaker-count-indicator">(${processedTranscription.speakers.length})</span></div>- <div class="speaker-legend-content">- <div v-for="speaker in processedTranscription.speakers" :key="speaker.name" :class="[speaker.color, 'speaker-legend-item']">- <span class="speaker-name">${ speaker.name }</span>- </div>+ <i class="fas fa-chevron-down speaker-legend-toggle"></i>+ </div>+ <div class="speaker-legend-content">+ <div v-for="(speaker, index) in processedTranscription.speakers"+ :key="`${selectedRecording.id}-speaker-legend-${index}`"+ :class="['speaker-legend-item', speaker.color]">+ <span class="speaker-name">${speaker.name}</span></div></div>-- <!-- Transcription Content -->- <div v-if="processedTranscription.hasDialogue" @click="seekAudioFromEvent">- <!-- Simple View -->- <div v-if="transcriptionViewMode === 'simple'" class="transcription-simple-view">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment" :data-start-time="segment.startTime">- <div v-if="segment.showSpeaker" :class="[segment.color, 'speaker-tablet']">${ segment.speaker }</div>+ </div>++ <!-- Transcription Display -->+ <div v-if="selectedRecording.transcription">+ <!-- Simple View -->+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'"+ class="transcription-simple-view">+ <div v-if="processedTranscription.hasDialogue">+ <div v-for="segment in processedTranscription.simpleSegments"+ :key="segment.startTime || Math.random()"+ class="speaker-segment"+ @click="seekAudioFromEvent"+ :data-start-time="segment.startTime">+ <div v-if="segment.showSpeaker"+ :class="['speaker-tablet', segment.color]">+ ${segment.speaker}+ </div><div class="speaker-text">- <span class="word">${ segment.sentence }</span>+ ${segment.sentence}</div></div></div>- <!-- Bubble View -->- <div v-else class="transcription-with-speakers">- <div v-for="(row, index) in processedTranscription.bubbleRows" :key="index"- :class="['bubble-row', { 'speaker-me': row.isMe }]">- <div v-for="(bubble, bubbleIndex) in row.bubbles" :key="bubbleIndex"- :class="[row.color, 'speaker-bubble', { 'speaker-me': row.isMe }]" :data-start-time="bubble.startTime">- <div class="speaker-bubble-content">- <span class="word">${ bubble.sentence }</span>- </div>+ <div v-else>+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">+ <div v-for="segment in processedTranscription.simpleSegments"+ :key="segment.startTime || Math.random()"+ class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors"+ @click="seekAudioFromEvent"+ :data-start-time="segment.startTime">+ ${segment.sentence}</div></div>+ <div v-else class="whitespace-pre-wrap">+ ${processedTranscription.content}+ </div></div></div>- <div v-else @click="seekAudioFromEvent">- <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index"- class="cursor-pointer hover:bg-[var(--bg-tertiary)] p-1 rounded"- :data-start-time="segment.startTime">- <span>${ segment.sentence }</span>++ <!-- Bubble View -->+ <div v-else-if="transcriptionViewMode === 'bubble'"+ class="transcription-with-speakers">+ <div v-for="(row, rowIndex) in processedTranscription.bubbleRows"+ :key="`${selectedRecording.id}-bubble-row-${rowIndex}`"+ :class="['bubble-row', row.isMe ? 'speaker-me' : '']">+ <div v-for="bubble in row.bubbles"+ :key="bubble.startTime || Math.random()"+ :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']"+ @click="seekAudioFromEvent"+ :data-start-time="bubble.startTime">+ <div class="speaker-bubble-content">+ ${bubble.sentence}+ </div></div></div>- <pre v-else class="whitespace-pre-wrap font-sans">${ processedTranscription.content || 'No transcription available.' }</pre></div></div>- <div v-else-if="selectedRecording.status === 'FAILED'" class="text-[var(--text-danger)]">- <p class="font-medium mb-2">Processing Failed:</p>- <pre class="whitespace-pre-wrap font-sans">${ selectedRecording.transcription || 'An unknown error occurred.' }</pre>- </div>- <div v-else class="flex items-center justify-center text-[var(--text-muted)] h-full">- <i class="fas fa-spinner fa-spin mr-2"></i> Transcription in progress...- </div></div></div>- </div>- <!-- Summary Tab -->- <div class="mobile-tab-panel" :class="{ active: selectedMobileTab === 'summary' }">- <div class="mobile-summary-content">- <div class="mobile-content-header">- <h4 class="mobile-content-title">Summary</h4>- <div class="mobile-content-actions">- <button @click="toggleEditSummary" class="mobile-action-btn" title="Edit Summary">- <i class="fas fa-edit"></i>- </button>- <!-- Reprocess summary and Identify Speakers buttons moved to main header -->+ <!-- Resizable Divider - Minimal but functional -->+ <div id="mainColumnResizer" @mousedown="startColumnResize"></div>++ <!-- Right Panel: Summary/Notes and Chat -->+ <div id="rightMainColumn" class="flex flex-col overflow-hidden" :style="{width: rightColumnWidth + '%'}">+ <!-- Audio Player -->+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">+ <div class="audio-player-container">+ <audio controls+ :src="'/audio/' + selectedRecording.id"+ :volume="playerVolume"+ @volumechange="onPlayerVolumeChange"+ class="w-full">+ Your browser does not support the audio element.+ </audio></div></div>- <div class="mobile-content-box summary-box" style="overflow-y: auto;">- <div v-if="selectedRecording.status === 'COMPLETED'" class="h-full">- <div v-if="!editingSummary" class="prose-styles" v-html="selectedRecording.summary_html || selectedRecording.summary || 'No summary generated.'"></div>- <textarea v-else v-model="selectedRecording.summary" @blur="saveInlineEdit('summary')" class="w-full h-full bg-transparent border-none focus:ring-0 focus:outline-none resize-none" placeholder="Enter summary"></textarea>++ <!-- Summary/Notes Tabs -->+ <div class="flex-1 flex flex-col overflow-hidden">+ <!-- Tab Navigation -->+ <div class="bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex">+ <button @click="selectedTab = 'summary'"+ :class="[+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',+ selectedTab === 'summary'+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'+ ]">+ Summary+ </button>+ <button @click="selectedTab = 'notes'"+ :class="[+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',+ selectedTab === 'notes'+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'+ ]">+ Notes+ </button></div>- <div v-else-if="selectedRecording.status === 'FAILED'" class="text-[var(--text-danger)] h-full overflow-y-auto" v-html="selectedRecording.summary_html || selectedRecording.summary || 'Summary generation failed or was skipped.'"></div>- <div v-else class="flex items-center justify-center text-[var(--text-muted)] h-full">- <i class="fas fa-spinner fa-spin mr-2"></i> Summary pending...- </div>- </div>- </div>- </div>-- <!-- Notes Tab -->- <div class="mobile-tab-panel" :class="{ active: selectedMobileTab === 'notes' }">- <div class="mobile-notes-content">- <div class="mobile-content-header">- <h4 class="mobile-content-title">Notes</h4>- <div class="mobile-content-actions">- <button @click="toggleEditNotes" class="mobile-action-btn" title="Edit Notes">- <i class="fas fa-edit"></i>- </button>- </div>- </div>- <div class="mobile-content-box notes-box">- <div v-if="!editingNotes" v-html="selectedRecording.notes_html || selectedRecording.notes || 'No notes'"></div>- <textarea v-else v-model="selectedRecording.notes" @blur="saveInlineEdit('notes')" class="w-full h-full bg-transparent border-none focus:ring-0 focus:outline-none resize-none" placeholder="Enter notes"></textarea>- </div>- </div>- </div>- <!-- Chat Tab -->- <div class="mobile-tab-panel" :class="{ active: selectedMobileTab === 'chat' }">- <div class="mobile-chat-content">- <div class="mobile-chat-messages" ref="chatMessagesRef">- <div v-if="chatMessages.length === 0" class="flex items-center justify-center h-full text-[var(--text-muted)]">- <div class="text-center">- <i class="fas fa-comments text-2xl mb-2"></i>- <p>Ask questions about the transcript</p>- </div>- </div>- <div v-for="(message, index) in chatMessages" :key="index" class="message" :class="message.role === 'user' ? 'user-message bg-[var(--bg-accent)] text-[var(--text-accent)]' : 'ai-message bg-[var(--bg-tertiary)] text-[var(--text-secondary)]'">- <div class="flex justify-between items-start">- <div class="flex-grow" v-if="message.role === 'user'">${ message.content }</div>- <div class="flex-grow" v-else v-html="message.html || message.content"></div>- <button v-if="message.role === 'assistant'" @click="copyMessage(message.content, $event)" class="ml-2 text-[var(--text-light)] hover:text-[var(--text-muted)]" title="Copy response">- <i class="fas fa-copy text-xs"></i>- </button>+ <!-- Tab Content -->+ <div class="flex-1 overflow-hidden">+ <!-- Summary Tab -->+ <div v-if="selectedTab === 'summary'" class="h-full p-4 overflow-y-auto">+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ <p class="mt-2 text-[var(--text-muted)]">Generating summary...</p>+ </div>++ <div v-else-if="!selectedRecording.summary" class="text-center py-8">+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">No summary available</p>+ </div>++ <div v-else class="content-box">+ <button v-if="!editingSummary"+ @click="toggleEditSummary"+ class="hover-edit-btn">+ <i class="fas fa-edit mr-1"></i>Edit+ </button>++ <div v-if="!editingSummary"+ class="summary-box"+ v-html="selectedRecording.summary_html || selectedRecording.summary">+ </div>+ <div v-else class="h-full flex flex-col">+ <div class="markdown-editor-container flex-1">+ <textarea ref="summaryMarkdownEditor"+ v-model="selectedRecording.summary"+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"+ placeholder="Enter summary in Markdown format...">+ </textarea>+ </div>+ <div class="flex justify-end gap-2 mt-2">+ <button @click="cancelEditSummary"+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">+ Cancel+ </button>+ <button @click="saveEditSummary"+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">+ Save+ </button>+ </div>+ </div>+ </div></div>- </div>- <div v-if="isChatLoading" class="message ai-message bg-[var(--bg-tertiary)] text-[var(--text-secondary)]">- <div class="flex items-center">- <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...++ <!-- Notes Tab -->+ <div v-if="selectedTab === 'notes'" class="h-full p-4 overflow-y-auto">+ <div class="content-box h-full">+ <button v-if="!editingNotes"+ @click="toggleEditNotes"+ class="hover-edit-btn">+ <i class="fas fa-edit mr-1"></i>Edit+ </button>++ <div v-if="!editingNotes"+ class="notes-box h-full">+ <div v-if="selectedRecording.notes_html"+ v-html="selectedRecording.notes_html">+ </div>+ <div v-else-if="selectedRecording.notes"+ class="whitespace-pre-wrap">+ ${selectedRecording.notes}+ </div>+ <div v-else class="text-[var(--text-muted)] italic">+ Click to add notes...+ </div>+ </div>++ <div v-else class="h-full flex flex-col">+ <div class="markdown-editor-container flex-1">+ <textarea ref="notesMarkdownEditor"+ v-model="selectedRecording.notes"+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"+ placeholder="Enter notes in Markdown format...">+ </textarea>+ </div>+ <div class="flex justify-end gap-2 mt-2">+ <button @click="cancelEditNotes"+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">+ Cancel+ </button>+ <button @click="saveEditNotes"+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">+ Save+ </button>+ </div>+ </div>+ </div></div></div></div>- <div class="mobile-chat-input">- <textarea- v-model="chatInput"- @keyup.enter.exact="sendChatMessage"- @keyup.enter.shift.exact.prevent="chatInput += '\n'"- placeholder="Ask about the transcript... (Shift+Enter for new line)"- :disabled="isChatLoading || !selectedRecording || selectedRecording.status !== 'COMPLETED'"- class="custom-scrollbar"- ></textarea>- <button- @click="sendChatMessage"- :disabled="!chatInput.trim() || isChatLoading || !selectedRecording || selectedRecording.status !== 'COMPLETED'"- >- <i class="fas fa-paper-plane"></i>++ <!-- Chat Section -->+ <div class="border-t border-[var(--border-primary)] flex flex-col">+ <!-- Chat Toggle -->+ <button @click="showChat = !showChat"+ class="bg-[var(--bg-tertiary)] px-4 py-3 text-left hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-between">+ <span class="font-medium flex items-center">+ <i class="fas fa-comments mr-2"></i>+ Chat with Transcription+ </span>+ <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i></button>- </div>- </div>- </div>- <!-- Metadata Tab -->- <div class="mobile-tab-panel" :class="{ active: selectedMobileTab === 'metadata' }">- <div class="mobile-metadata-content">- <div class="mobile-content-header">- <h4 class="mobile-content-title">Metadata</h4>- </div>- <div class="mobile-content-box">- <!-- Participants Section (Editable) -->- <div class="mb-4 p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <div class="flex justify-between items-center mb-2">- <dt class="font-medium text-[var(--text-primary)]">Participants</dt>- <button @click="toggleEditParticipants" class="mobile-action-btn" title="Edit Participants">- <i class="fas" :class="editingParticipants ? 'fa-check' : 'fa-edit'"></i>- </button>- </div>- <div v-if="!editingParticipants" class="text-sm text-[var(--text-secondary)]">- ${ selectedRecording.participants || 'None specified' }+ <!-- Chat Content -->+ <div v-if="showChat" class="flex-1 flex flex-col min-h-0 max-h-96">+ <!-- Chat Messages -->+ <div ref="chatMessagesRef"+ class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">+ <div v-if="chatMessages.length === 0" class="text-center py-8">+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>+ <p class="text-[var(--text-muted)]">Ask questions about this transcription</p>+ </div>++ <div v-for="(message, index) in chatMessages"+ :key="index"+ :class="[+ 'message',+ message.role === 'user' ? 'user-message ml-auto' : 'ai-message'+ ]">+ <div class="copyable" v-if="message.role === 'assistant'">+ <button @click="copyMessage(message.content, $event)"+ class="copy-btn absolute top-2 right-2 opacity-0 group-hover:opacity-100">+ <i class="fas fa-copy"></i>+ </button>+ <div v-if="message.html" v-html="message.html"></div>+ <div v-else class="whitespace-pre-wrap">${message.content}</div>+ </div>+ <div v-else class="whitespace-pre-wrap">${message.content}</div>+ </div>++ <div v-if="isChatLoading" class="ai-message">+ <i class="fas fa-spinner fa-spin mr-2"></i>+ Thinking...+ </div></div>- <textarea v-else v-model="selectedRecording.participants" @blur="saveInlineEdit('participants')" class="w-full p-2 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded focus:ring-[var(--ring-focus)] focus:border-[var(--border-focus)] text-[var(--text-primary)] resize-none" rows="2" placeholder="Enter participants"></textarea>- </div>- <!-- Other Metadata -->- <div class="space-y-3">- <div class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <dt class="font-medium text-sm text-[var(--text-primary)] mb-0.5">Original Filename</dt>- <dd class="text-sm text-[var(--text-secondary)] break-all">${ selectedRecording.original_filename || 'N/A' }</dd>- </div>- <div class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <dt class="font-medium text-sm text-[var(--text-primary)] mb-0.5">File Size</dt>- <dd class="text-sm text-[var(--text-secondary)]">${ formatFileSize(selectedRecording.file_size) }</dd>- </div>- <div class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <dt class="font-medium text-sm text-[var(--text-primary)] mb-0.5">Created</dt>- <dd class="text-sm text-[var(--text-secondary)]">${ new Date(selectedRecording.created_at).toLocaleString() }</dd>- </div>- <div v-if="selectedRecording.completed_at" class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <dt class="font-medium text-sm text-[var(--text-primary)] mb-0.5">Processed On</dt>- <dd class="text-sm text-[var(--text-secondary)]">${ new Date(selectedRecording.completed_at).toLocaleString() }</dd>- </div>- <div v-if="selectedRecording.processing_time_seconds" class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <dt class="font-medium text-sm text-[var(--text-primary)] mb-0.5">Processing Time</dt>- <dd class="text-sm text-[var(--text-secondary)]">${ formatDuration(selectedRecording.processing_time_seconds) }</dd>- </div>- <div class="p-3 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">- <div class="flex justify-between items-center mb-0.5">- <dt class="font-medium text-sm text-[var(--text-primary)]">Meeting Date</dt>- <button @click="toggleEditMobileMeetingDate" class="mobile-action-btn text-xs" :title="editingMobileMeetingDate ? 'Save Date' : 'Edit Date'">- <i class="fas" :class="editingMobileMeetingDate ? 'fa-check' : 'fa-edit'"></i>+ <!-- Chat Input -->+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">+ <div class="flex gap-2">+ <textarea v-model="chatInput"+ @keydown="handleChatKeydown"+ :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'"+ placeholder="Ask about this transcription... (Enter to send, Ctrl+Enter for new line)"+ class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"+ rows="2">+ </textarea>+ <button @click="sendChatMessage"+ :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'"+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">+ <i class="fas fa-paper-plane"></i></button></div>- <div v-if="!editingMobileMeetingDate"- @click="toggleEditMobileMeetingDate"- class="text-sm text-[var(--text-secondary)] cursor-pointer hover:text-[var(--text-accent)]">- ${ selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'Click to add' }- </div>- <input v-else- type="date"- v-model="selectedRecording.meeting_date"- @blur="saveInlineEdit('meeting_date'); editingMobileMeetingDate = false;"- class="w-full p-1 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded focus:ring-[var(--ring-focus)] focus:border-[var(--border-focus)] text-[var(--text-primary)]">+ <p v-if="selectedRecording.status !== 'COMPLETED'"+ class="text-xs text-[var(--text-muted)] mt-2">+ Chat will be available once transcription is complete+ </p></div></div></div>@@ -886,777 +1072,780 @@</div></div>- <!-- Desktop Layout (shown only on desktop) -->- <div class="desktop-layout">- <!-- Sidebar toggle button that appears when sidebar is collapsed - positioned at the left edge of main content, aligned with title -->- <button v-if="isSidebarCollapsed && !isMobileScreen"- @click="toggleSidebar"- class="absolute -left-3 top-6 z-20 bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-2 pl-1 pr-3 rounded-r-lg shadow-lg text-[var(--text-accent)] hover:text-[var(--text-primary)] hover:shadow-xl transition-all duration-300 transform hover:translate-x-1 border-r border-t border-b border-[var(--border-accent)]"- title="Show Sidebar">- <i class="fas fa-chevron-right"></i>- </button>-- <div class="grid grid-cols-1 lg:grid-cols-4 gap-6 flex-grow">- <!-- Sidebar: Conditional classes for mobile fly-in and desktop normal -->- <div- :class="{- 'fixed inset-y-0 left-0 z-50 w-4/5 max-w-xs bg-[var(--bg-secondary)] shadow-xl transform transition-transform duration-300 ease-in-out': isMobileScreen,- 'translate-x-0': isMobileScreen && isMobileMenuOpen,- '-translate-x-full': isMobileScreen && !isMobileMenuOpen,- 'lg:col-span-1 sidebar-container max-h-85vh': !isMobileScreen- }"- v-show="isMobileMenuOpen || (!isMobileScreen && !isSidebarCollapsed)"- class="bg-[var(--bg-secondary)] p-4 rounded-lg shadow-md lg:sticky lg:top-6">- <div class="flex justify-between items-center mb-2 sticky top-0 bg-[var(--bg-secondary)] pb-2 border-b border-[var(--border-primary)] sidebar-header">- <h3 class="text-lg font-semibold text-[var(--text-primary)]">Recordings</h3>- <!-- Close button for mobile fly-in, hide button for desktop -->- <button @click="isMobileScreen ? closeMobileMenu() : toggleSidebar()"- class="p-1 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200"- :title="isMobileScreen ? 'Close Menu' : (isSidebarCollapsed ? 'Show Sidebar' : 'Hide Sidebar')">- <i :class="isMobileScreen ? 'fas fa-times' : 'fas fa-chevron-left'"></i>- </button>- </div>+ <!-- Empty State -->+ <div v-else class="flex-1 flex items-center justify-center">+ <div class="text-center">+ <i class="fas fa-microphone text-6xl text-[var(--text-muted)] mb-4"></i>+ <h2 class="text-2xl font-bold mb-2">Select a Recording</h2>+ <p class="text-[var(--text-muted)] mb-6">Choose a recording from the sidebar to view its transcription and summary</p>+ <button @click="switchToUploadView"+ class="px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">+ <i class="fas fa-plus mr-2"></i>Upload New Recording+ </button>+ </div>+ </div>+ </div>+ </div>- <!-- New Recording Button for Mobile Menu (Sidebar) -->- {% if current_user.is_authenticated %}- <button- v-if="isMobileScreen"- @click="switchToUploadView(); closeMobileMenu();"- class="w-full flex items-center justify-center mb-3 px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">- <i class="fas fa-plus mr-2"></i> New Recording+ <!-- Upload Progress Popup -->+ <div v-if="uploadQueue.length > 0 && !progressPopupClosed"+ :class="[+ 'progress-popup',+ progressPopupMinimized ? 'minimized' : ''+ ]">+ <div class="bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg overflow-hidden">+ <!-- Progress Header -->+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 flex items-center justify-between">+ <div class="flex items-center gap-2">+ <i class="fas fa-upload text-[var(--text-accent)]"></i>+ <span class="font-medium">Upload Progress</span>+ <span class="text-sm text-[var(--text-muted)]">(${completedInQueue}/${totalInQueue})</span>+ </div>+ <div class="flex items-center gap-2">+ <button @click="progressPopupMinimized = !progressPopupMinimized"+ class="p-1 rounded hover:bg-[var(--bg-accent)] transition-colors">+ <i :class="progressPopupMinimized ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i></button>- {% endif %}+ <button @click="progressPopupClosed = true"+ class="p-1 rounded hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div>- <!-- Search input -->- <div class="relative mb-3 sticky top-12 z-10 bg-[var(--bg-secondary)]">- <div class="flex items-center bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] focus-within:border-[var(--border-focus)] focus-within:ring-1 focus-within:ring-[var(--ring-focus)]">- <i class="fas fa-search text-[var(--text-muted)] ml-3 mr-2"></i>- <input- v-model="searchQuery"- type="text"- placeholder="Search recordings..."- class="w-full py-2 pr-3 bg-transparent border-0 focus:ring-0 focus:outline-none text-sm text-[var(--text-primary)]"- />- <button- v-if="searchQuery"- @click="searchQuery = ''"- class="text-[var(--text-muted)] hover:text-[var(--text-primary)] mr-3"- >- <i class="fas fa-times-circle"></i>- </button>- </div>+ <!-- Progress Content -->+ <div v-if="!progressPopupMinimized" class="p-4 max-h-64 overflow-y-auto">+ <div v-if="currentlyProcessingFile" class="mb-4 p-3 bg-[var(--bg-accent)] rounded-lg">+ <div class="flex items-center justify-between mb-2">+ <span class="font-medium truncate min-w-0">${currentlyProcessingFile.file.name}</span>+ <span class="text-sm flex-shrink-0 ml-2">${processingProgress}%</span></div>- <div v-if="isLoadingRecordings" class="text-center text-[var(--text-muted)] py-4 sidebar-content">- <i class="fas fa-spinner fa-spin mr-2"></i> Loading recordings...+ <div class="w-full bg-[var(--bg-secondary)] rounded-full h-2">+ <div class="bg-[var(--bg-button)] h-2 rounded-full transition-all duration-300"+ :style="{width: processingProgress + '%'}"></div></div>- <div v-else-if="recordings.length === 0 && uploadQueue.length === 0" class="text-center text-[var(--text-muted)] py-4 flex-grow flex flex-col items-center justify-center sidebar-content">- <i class="fas fa-folder-open text-4xl text-[var(--text-light)] mb-3"></i>- <p>No recordings yet.</p>- <p>Upload one or drag & drop anywhere!</p>+ <p class="text-sm text-[var(--text-muted)] mt-1">${processingMessage}</p>+ </div>++ <div v-if="finishedFilesInQueue.length > 0" class="space-y-2">+ <h4 class="text-sm font-medium text-[var(--text-secondary)]">Completed</h4>+ <div v-for="item in finishedFilesInQueue"+ :key="item.clientId"+ class="progress-list-item p-2 bg-[var(--bg-tertiary)] rounded">+ <i :class="[+ 'fas',+ item.status === 'completed' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500'+ ]"></i>+ <span class="truncate">${item.file.name}</span>+ <span :class="[+ 'text-xs',+ item.status === 'completed' ? 'text-green-600' : 'text-red-600'+ ]">+ ${item.status === 'completed' ? 'Done' : 'Failed'}+ </span></div>- <div v-else class="space-y-4 custom-scrollbar sidebar-content">- <div v-for="group in groupedRecordings" :key="group.title" class="mb-3">- <h4 class="font-medium text-[var(--text-muted)] text-xs uppercase tracking-wider mb-2 sticky top-0 bg-[var(--bg-secondary)] py-1">${ group.title }</h4>- <ul class="space-y-1">- <li v-for="recording in group.items"- :key="recording.id"- @click="selectRecording(recording); if(isMobileScreen) closeMobileMenu();"- class="cursor-pointer p-3 rounded-md flex justify-between items-center transition duration-150 ease-in-out"- :class="{- 'bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] ring-1 ring-[var(--border-accent)] text-[var(--text-accent)]': selectedRecording?.id === recording.id,- 'hover:bg-[var(--bg-tertiary)] text-[var(--text-primary)]': selectedRecording?.id !== recording.id- }">- <div class="flex items-center overflow-hidden mr-2">- <i class="fas fa-file-audio text-[var(--text-accent)] mr-2 flex-shrink-0"></i>- <span class="text-sm font-medium truncate" :title="recording.title || 'Loading title...'">${ recording.title || '(Processing...)' }</span>- </div>- <div class="flex space-x-2 flex-shrink-0 items-center">- <span v-if="recording.status === 'PROCESSING'" class="text-xs text-[var(--text-info-strong)] italic flex items-center" title="Transcribing...">- <i class="fas fa-spinner fa-spin mr-1"></i> Transcribing- </span>- <span v-else-if="recording.status === 'SUMMARIZING'" class="text-xs text-[var(--text-warn-strong)] italic flex items-center" title="Generating Summary...">- <i class="fas fa-spinner fa-spin mr-1"></i> Summarizing- </span>- <span v-else-if="recording.status === 'PENDING'" class="text-xs text-[var(--text-pending-strong)] italic flex items-center" title="Waiting...">- <i class="fas fa-clock mr-1"></i> Pending- </span>- <span v-else-if="recording.status === 'FAILED'" class="text-xs text-[var(--text-danger-strong)] italic flex items-center" title="Processing Failed">- <i class="fas fa-exclamation-triangle mr-1"></i> Failed- </span>- <span v-if="recording.is_inbox" class="text-blue-500 cursor-pointer hover:text-blue-700" title="Mark as Read" @click.stop="toggleInbox(recording)">- <i class="fas fa-inbox"></i>- </span>- <span v-if="recording.is_highlighted" class="text-yellow-500" title="Highlighted">- <i class="fas fa-star"></i>- </span>- <button @click.stop="editRecording(recording)" class="text-[var(--text-muted)] hover:text-[var(--text-accent)] text-xs p-1 rounded hover:bg-[var(--bg-tertiary)]" title="Edit Details">- <i class="fas fa-edit"></i>- </button>- <button @click.stop="confirmDelete(recording)" class="text-[var(--text-muted)] hover:text-[var(--text-danger)] text-xs p-1 rounded hover:bg-[var(--bg-tertiary)]" title="Delete Recording">- <i class="fas fa-trash"></i>- </button>- </div>- </li>- </ul>- </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Modals -->+ <!-- Edit Modal -->+ <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">+ <div class="p-6 border-b border-[var(--border-primary)]">+ <h3 class="text-lg font-semibold">Edit Recording</h3>+ </div>+ <div class="p-6 space-y-4">+ <div>+ <label class="block text-sm font-medium mb-2">Title</label>+ <input v-model="editingRecording.title"+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ </div>+ <div>+ <label class="block text-sm font-medium mb-2">Participants</label>+ <input v-model="editingRecording.participants"+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ </div>+ <div>+ <label class="block text-sm font-medium mb-2">Meeting Date</label>+ <input v-model="editingRecording.meeting_date"+ type="date"+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ </div>+ <div>+ <label class="block text-sm font-medium mb-2">Notes</label>+ <textarea v-model="editingRecording.notes"+ rows="4"+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ </textarea>+ </div>+ </div>+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">+ <button @click="cancelEdit"+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">+ Cancel+ </button>+ <button @click="saveEdit"+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">+ Save Changes+ </button>+ </div>+ </div>+ </div>++ <!-- Delete Confirmation Modal -->+ <div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-md">+ <div class="p-6">+ <div class="flex items-center gap-4 mb-4">+ <i class="fas fa-exclamation-triangle text-3xl text-[var(--text-danger)]"></i>+ <div>+ <h3 class="text-lg font-semibold">Delete Recording</h3>+ <p class="text-[var(--text-muted)]">This action cannot be undone.</p></div></div>+ <p class="text-[var(--text-secondary)] mb-6">+ Are you sure you want to delete "${recordingToDelete?.title || 'this recording'}"?+ </p>+ <div class="flex justify-end gap-3">+ <button @click="cancelDelete"+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">+ Cancel+ </button>+ <button @click="deleteRecording"+ class="px-4 py-2 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors">+ Delete+ </button>+ </div>+ </div>+ </div>+ </div>- <div v-if="!isMobileScreen" :class="(!isMobileScreen && isSidebarCollapsed) ? 'lg:col-span-4' : 'lg:col-span-3'" class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-md flex flex-col max-h-85vh main-content-area">- <div v-if="selectedRecording" class="flex-grow flex flex-col">- <div class="recording-header">- <div class="recording-title-row">- <div class="responsive-title-container">- <h3 class="text-2xl font-semibold text-[var(--text-primary)] flex items-center">- <span class="responsive-title">${ selectedRecording.title || 'Loading...' }</span>- </h3>- </div>- <div class="responsive-button-container">- <button @click="toggleInbox(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105"- :class="selectedRecording.is_inbox ? 'bg-blue-100 text-blue-600 hover:bg-blue-200 dark:bg-blue-800 dark:text-blue-200 dark:hover:bg-blue-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'"- :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">- <i class="fas fa-inbox"></i>- </button>- <button @click="toggleHighlight(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105"- :class="selectedRecording.is_highlighted ? 'bg-yellow-100 text-yellow-600 hover:bg-yellow-200 dark:bg-yellow-700 dark:text-yellow-200 dark:hover:bg-yellow-600' : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'"- :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">- <i class="fas fa-star"></i>- </button>- <button @click="editRecording(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Edit Details">- <i class="fas fa-edit"></i>- </button>- <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">- <i class="fas fa-redo-alt"></i>- </button>- <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Reprocess summary">- <i class="fas fa-sync-alt"></i>- </button>- <button @click="confirmReset(selectedRecording)" v-if="selectedRecording && (selectedRecording.status === 'PROCESSING' || selectedRecording.status === 'SUMMARIZING')"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-orange-100 text-orange-600 hover:bg-orange-200 dark:bg-orange-700 dark:text-orange-200 dark:hover:bg-orange-600"- title="Reset Stuck Status">- <i class="fas fa-power-off"></i>- </button>- <button @click="openSpeakerModal" v-if="identifiedSpeakers.length > 0"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"- title="Identify Speakers">- <i class="fas fa-user-tag"></i>- </button>- <button @click="confirmDelete(selectedRecording)"- class="p-2 rounded-md text-sm transition-all hover:scale-105 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] hover:bg-[var(--bg-danger)] hover:text-[var(--text-button)]"- title="Delete Recording">- <i class="fas fa-trash"></i>- </button>- </div>+ <!-- Color Scheme Modal -->+ <div v-if="showColorSchemeModal" class="color-scheme-modal" @click.self="closeColorSchemeModal">+ <div class="color-scheme-modal-content">+ <div class="color-scheme-header">+ <h2 class="color-scheme-title">+ <i class="fas fa-palette"></i>+ Choose Color Scheme+ </h2>+ <p class="color-scheme-subtitle">Customize your interface with beautiful color themes</p>+ </div>++ <div class="color-scheme-body">+ <div class="color-scheme-section">+ <h3 class="color-scheme-section-title">+ <i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'"></i>+ ${isDarkMode ? 'Dark' : 'Light'} Themes+ </h3>+ <div class="color-scheme-grid">+ <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"+ :key="scheme.id"+ @click="selectColorScheme(scheme.id)"+ :class="['color-scheme-option', currentColorScheme === scheme.id ? 'active' : '']">+ <div class="color-scheme-preview">+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-primary color-scheme-preview-segment`"></div>+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-secondary color-scheme-preview-segment`"></div>+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-tertiary color-scheme-preview-segment`"></div></div>- <div class="recording-metadata-row">- <!-- Display Meeting Date with edit functionality -->- <div class="metadata-item">- <i class="fas fa-calendar-alt metadata-icon"></i>- <span class="metadata-label">Meeting:</span>- <span v-if="!editingMeetingDate"- @click="toggleEditMeetingDate"- class="metadata-value editable">- ${ selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'Click to add' }- </span>- <span v-else class="inline-flex items-center">- <input type="date"- v-model="selectedRecording.meeting_date"- @blur="saveInlineEdit('meeting_date')"- class="metadata-edit-input" />- <button @click="saveInlineEdit('meeting_date')"- class="metadata-edit-button">- <i class="fas fa-check"></i>- </button>- </span>- </div>-- <div class="metadata-item">- <i class="fas fa-clock metadata-icon"></i>- <span class="metadata-label">Created:</span>- <span class="metadata-value">${ new Date(selectedRecording.created_at).toLocaleString() }</span>- </div>-- <!-- Status Badge -->- <div v-if="selectedRecording.status !== 'COMPLETED'" class="metadata-item">- <i class="fas fa-info-circle metadata-icon"></i>- <span class="metadata-label">Status:</span>- <span :class="getStatusClass(selectedRecording.status)" class="status-badge">- ${ formatStatus(selectedRecording.status) }- </span>- </div>+ <div class="color-scheme-name">${scheme.name}</div>+ <div class="color-scheme-description">${scheme.description}</div>+ <div v-if="currentColorScheme === scheme.id" class="color-scheme-check">+ <i class="fas fa-check"></i></div></div>+ </div>+ </div>+ </div>++ <div class="color-scheme-footer">+ <button @click="resetColorScheme" class="color-scheme-reset-btn">+ <i class="fas fa-undo mr-2"></i>Reset to Default+ </button>+ <button @click="closeColorSchemeModal" class="color-scheme-close-btn">+ Close+ </button>+ </div>+ </div>+ </div>- <!-- Main content area with flex layout -->- <div id="mainContentColumns" class="flex flex-col md:flex-row flex-grow overflow-y-auto" style="max-height: 75vh;">- <!-- Left Column: Participants, Transcription, Summary & Notes -->- <div id="leftMainColumn" class="content-column left-content" style="width: 40%;">- <!-- Participants Section -->- <div class="participants-section">- <div class="flex justify-between items-center mb-1">- <h4 class="font-semibold text-[var(--text-secondary)]">Participants</h4>- <button @click="toggleEditParticipants" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded">- <i class="fas" :class="editingParticipants ? 'fa-check' : 'fa-edit'"></i>- </button>- </div>- <div v-if="!editingParticipants" class="text-sm bg-[var(--bg-tertiary)] p-3 rounded-xl border border-[var(--border-primary)] min-h-[40px] text-[var(--text-secondary)]">${ selectedRecording.participants || 'None specified' }</div>- <textarea v-else v-model="selectedRecording.participants" @blur="saveInlineEdit('participants')" class="text-sm bg-[var(--bg-tertiary)] p-3 rounded border border-[var(--border-primary)] min-h-[40px] w-full focus:ring-[var(--ring-focus)] focus:border-[var(--border-focus)] text-[var(--text-secondary)]" placeholder="Enter participants"></textarea>- </div>-- <!-- Transcription Section -->- <div class="transcription-section" :style="{ flex: transcriptionFlex }">- <div class="flex justify-between items-center mb-1">- <h4 class="font-semibold text-[var(--text-secondary)]">Transcription</h4>- <div class="flex items-center space-x-2">- <!-- View Mode Toggle - compact tablet style next to copy button -->- <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">- <button @click="toggleTranscriptionViewMode"- :class="{ active: transcriptionViewMode === 'simple' }"- class="toggle-button">- <i class="fas fa-list"></i> Simple- </button>- <button @click="toggleTranscriptionViewMode"- :class="{ active: transcriptionViewMode === 'bubble' }"- class="toggle-button">- <i class="fas fa-comments"></i> Bubbles- </button>- </div>- <button @click="copyTranscription($event)" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded" title="Copy to clipboard">- <i class="fas fa-copy"></i>- </button>- </div>- </div>-- <div class="transcription-box custom-scrollbar relative">- <div v-if="selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'SUMMARIZING'" class="copyable">- <!-- Speaker Legend (if dialogue detected and bubble view) -->- <div v-if="processedTranscription.hasDialogue && transcriptionViewMode === 'bubble'" class="speaker-legend" :class="{ expanded: legendExpanded }">- <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">- <div class="speaker-legend-title">- <i class="fas fa-users"></i>- <span>Speakers</span>- <span class="speaker-count-indicator">(${ processedTranscription.speakers.length })</span>- </div>- <i class="fas fa-chevron-down speaker-legend-toggle"></i>- </div>- <div class="speaker-legend-content">- <div v-for="speaker in processedTranscription.speakers" :key="speaker.name" :class="[speaker.color, 'speaker-legend-item']">- <span class="speaker-name">${ speaker.name }</span>- </div>- </div>- </div>-- <!-- Transcription Content -->- <div v-if="processedTranscription.hasDialogue" @click="seekAudioFromEvent">- <!-- Simple View -->- <div v-if="transcriptionViewMode === 'simple'" class="transcription-simple-view">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment" :data-start-time="segment.startTime">- <div v-if="segment.showSpeaker" :class="[segment.color, 'speaker-tablet']">${ segment.speaker }</div>- <div class="speaker-text">- <span class="word">${ segment.sentence }</span>- </div>- </div>- </div>- <!-- Bubble View -->- <div v-else class="transcription-with-speakers">- <div v-for="(row, index) in processedTranscription.bubbleRows" :key="index"- :class="['bubble-row', { 'speaker-me': row.isMe }]">- <div v-for="(bubble, bubbleIndex) in row.bubbles" :key="bubbleIndex"- :class="[row.color, 'speaker-bubble', { 'speaker-me': row.isMe }]" :data-start-time="bubble.startTime">- <div class="speaker-bubble-content">- <span class="word">${ bubble.sentence }</span>- </div>- </div>- </div>- </div>- </div>- <div v-else @click="seekAudioFromEvent">- <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index"- class="cursor-pointer hover:bg-[var(--bg-tertiary)] p-1 rounded"- :data-start-time="segment.startTime">- <span>${ segment.sentence }</span>- </div>- </div>- <pre v-else class="whitespace-pre-wrap font-sans">${ processedTranscription.content || 'No transcription available.' }</pre>- </div>- </div>- <div v-else-if="selectedRecording.status === 'FAILED'" class="text-[var(--text-danger)]">- <p class="font-medium mb-2">Processing Failed:</p>- <pre class="whitespace-pre-wrap font-sans">${ selectedRecording.transcription || 'An unknown error occurred.' }</pre>- </div>- <div v-else class="flex items-center justify-center text-[var(--text-muted)] h-full">- <i class="fas fa-spinner fa-spin mr-2"></i> Transcription in progress...- </div>+ <!-- Reprocess Confirmation Modal -->+ <div v-if="showReprocessModal" @click="cancelReprocess" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">+ <!-- Header with gradient background -->+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">+ <div class="flex items-center">+ <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">+ <i class="fas fa-sync-alt text-white text-lg"></i>+ </div>+ <div>+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1">Confirm Reprocessing</h3>+ <p class="text-sm text-[var(--text-muted)] capitalize">${ reprocessType } reprocessing</p>+ </div>+ </div>+ </div>++ <!-- Content -->+ <div class="p-6 modal-content">+ <div v-if="reprocessRecording" class="mb-6">+ <div class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)]">+ <div class="flex items-start space-x-3">+ <i class="fas fa-file-audio text-[var(--text-accent)] mt-1"></i>+ <div class="flex-1 min-w-0">+ <h4 class="font-medium text-[var(--text-primary)] truncate" :title="reprocessRecording.title">+ ${ reprocessRecording.title || 'Untitled Recording' }+ </h4>+ <p class="text-sm text-[var(--text-muted)] mt-1">+ Created: ${ new Date(reprocessRecording.created_at).toLocaleDateString() }+ </p>+ </div>+ </div>+ </div>+ </div>++ <div class="space-y-4">+ <div class="flex items-start space-x-3">+ <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">+ <i class="fas fa-exclamation-triangle text-amber-600 text-xs"></i>+ </div>+ <div>+ <p class="text-[var(--text-secondary)] font-medium mb-1">What will happen?</p>+ <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">+ The audio will be re-transcribed from scratch. This will also regenerate the title and summary based on the new transcription.+ </p>+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">+ The audio will be re-transcribed using the ASR endpoint. This includes diarization and will regenerate the title and summary.+ </p>+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">+ A new title and summary will be generated based on the existing transcription.+ </p>+ </div>+ </div>++ <!-- ASR Options -->+ <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">+ <h4 class="text-md font-semibold text-[var(--text-secondary)]">ASR Options</h4>+ <div>+ <label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Language</label>+ <input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">+ </div>+ <div>+ <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Min Speakers</label>+ <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional">+ </div>+ <div>+ <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Max Speakers</label>+ <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional">+ </div>+ </div>++ <div class="flex items-start space-x-3">+ <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">+ <i class="fas fa-clock text-blue-600 text-xs"></i>+ </div>+ <div>+ <p class="text-[var(--text-secondary)] font-medium mb-1">Processing time</p>+ <p class="text-sm text-[var(--text-muted)]">+ This may take a few minutes to complete. You can continue using the app while processing.+ </p>+ </div>+ </div>++ <div class="flex items-start space-x-3" v-if="reprocessType === 'transcription'">+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">+ <i class="fas fa-info-circle text-red-600 text-xs"></i>+ </div>+ <div>+ <p class="text-[var(--text-secondary)] font-medium mb-1">Important note</p>+ <p class="text-sm text-[var(--text-muted)]">+ Any manual edits to the transcription, title, or summary will be overwritten.+ </p>+ </div>+ </div>++ <div class="flex items-start space-x-3" v-else-if="reprocessType === 'summary'">+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">+ <i class="fas fa-info-circle text-red-600 text-xs"></i>+ </div>+ <div>+ <p class="text-[var(--text-secondary)] font-medium mb-1">Important note</p>+ <p class="text-sm text-[var(--text-muted)]">+ Any manual edits to the title or summary will be overwritten.+ </p>+ </div>+ </div>+ </div>+ </div>++ <!-- Footer with action buttons -->+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">+ <button+ @click="cancelReprocess"+ class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">+ <i class="fas fa-times mr-2"></i>+ Cancel+ </button>+ <button+ @click="executeReprocess"+ class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center shadow-lg font-medium transform hover:scale-105">+ <i class="fas fa-sync-alt mr-2"></i>+ Start Reprocessing+ </button>+ </div>+ </div>+ </div>+ <!-- Reset Status Confirmation Modal -->+ <div v-if="showResetModal" @click="cancelReset" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">+ <div class="p-6 text-center">+ <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 dark:bg-orange-800 mb-4">+ <i class="fas fa-exclamation-triangle text-2xl text-orange-500 dark:text-orange-300"></i>+ </div>+ <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2">Reset Recording Status?</h3>+ <p class="text-sm text-[var(--text-muted)] mb-6">+ This will mark the recording as 'Failed'. This is useful if processing is stuck. You will be able to reprocess it afterwards.+ </p>+ </div>+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3">+ <button @click="cancelReset" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">+ Cancel+ </button>+ <button @click="executeReset" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600">+ Yes, Reset Status+ </button>+ </div>+ </div>+ </div>+ <!-- Simple Transcription Editor Modal -->+ <div v-if="showTextEditorModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">+ <div class="p-6 border-b border-[var(--border-primary)]">+ <h3 class="text-lg font-semibold">Edit Transcription</h3>+ </div>+ <div class="p-6 space-y-4 overflow-y-auto flex-1">+ <div>+ <label class="block text-sm font-medium mb-2">Transcription Content</label>+ <textarea v-model="editingTranscriptionContent"+ rows="15"+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] font-mono text-sm">+ </textarea>+ </div>+ </div>+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">+ <button @click="closeTextEditorModal"+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">+ Cancel+ </button>+ <button @click="saveTranscription"+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">+ Save Changes+ </button>+ </div>+ </div>+ </div>++ <!-- ASR Transcription Editor Modal -->+ <div v-if="showAsrEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-6xl flex flex-col max-h-[90vh]">+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0 flex justify-between items-center">+ <h3 class="text-xl font-bold text-[var(--text-primary)]">Edit ASR Transcription</h3>+ <button @click="closeAsrEditorModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-times"></i>+ </button>+ </div>+ <div class="flex-grow overflow-y-auto custom-scrollbar p-6">+ <table class="min-w-full asr-editor-table">+ <thead>+ <tr>+ <th class="w-1/4">Speaker</th>+ <th class="w-24">Start</th>+ <th class="w-24">End</th>+ <th>Sentence</th>+ <th class="w-12"><span class="sr-only">Actions</span></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(segment, index) in editingSegments" :key="segment.id || index">+ <td>+ <div class="speaker-combobox" @mouseleave="closeSpeakerSuggestions(index)">+ <input type="text" v-model="segment.speaker" @input="filterSpeakers(index)" @focus="openSpeakerSuggestions(index)" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] speaker-combobox-input" />+ <div class="speaker-combobox-arrow">+ <i class="fas fa-chevron-down text-xs"></i></div>- </div>-- <!-- Resizable Handle -->- <div- class="resize-handle cursor-ns-resize h-2 bg-[var(--border-primary)] hover:bg-[var(--border-accent)] rounded-full my-1 flex items-center justify-center"- title="Drag to resize">- <div class="w-10 h-1 bg-[var(--text-light)] rounded-full"></div>- </div>-- <!-- Tabs Section -->- <div class="tab-section" :style="{ flex: tabsFlex }">- <div class="border-b border-[var(--border-primary)]">- <div class="flex justify-between items-center">- <nav class="-mb-px flex space-x-4" aria-label="Tabs">- <button @click="selectedTab = 'summary'"- :class="selectedTab === 'summary' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"- class="whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm">- Summary- </button>- <button @click="selectedTab = 'notes'"- :class="selectedTab === 'notes' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"- class="whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm">- Notes- </button>- <button @click="selectedTab = 'metadata'"- :class="selectedTab === 'metadata' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"- class="whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm">- Metadata- </button>- </nav>- <div class="flex space-x-1 items-center h-full py-3">- <!-- Summary buttons - shown when summary tab is active -->- <template v-if="selectedTab === 'summary'">- <button @click="toggleEditSummary" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded" title="Edit Summary">- <i class="fas fa-edit"></i>- </button>- </template>- <!-- Notes buttons - shown when notes tab is active -->- <template v-if="selectedTab === 'notes'">- <button @click="toggleEditNotes" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded" title="Edit Notes">- <i class="fas fa-edit"></i>- </button>- </template>- </div>- </div>+ <div v-if="segment.showSuggestions" class="speaker-combobox-suggestions">+ <div v-for="speaker in segment.filteredSpeakers" @mousedown="selectSpeaker(index, speaker)" class="speaker-suggestion-item">${speaker}</div></div>- <div class="pt-4 flex-grow flex flex-col min-h-0">- <!-- Summary Panel -->- <div v-show="selectedTab === 'summary'" class="h-full">- <div v-if="selectedRecording.status === 'COMPLETED'" class="h-full">- <div v-if="!editingSummary" class="content-box h-full flex flex-col min-h-0">- <div class="summary-box custom-scrollbar" v-html="selectedRecording.summary_html || selectedRecording.summary || 'No summary generated.'">- </div>- </div>- <textarea v-else v-model="selectedRecording.summary" @blur="saveInlineEdit('summary')" class="summary-box custom-scrollbar bg-[var(--bg-tertiary)] border-[var(--border-primary)] text-[var(--text-secondary)] w-full focus:ring-[var(--ring-focus)] focus:border-[var(--border-focus)] tab-content-box" placeholder="Enter summary"></textarea>- </div>- <div v-else-if="selectedRecording.status === 'FAILED'" class="summary-box text-[var(--text-danger)] custom-scrollbar bg-[var(--bg-tertiary)] border-[var(--border-primary)] tab-content-box" v-html="selectedRecording.summary_html || selectedRecording.summary || 'Summary generation failed or was skipped.'">- </div>- <div v-else class="h-24 flex items-center justify-center p-4 bg-[var(--bg-tertiary)] rounded border border-[var(--border-primary)] text-[var(--text-muted)]">- <i class="fas fa-spinner fa-spin mr-2"></i> Summary pending...- </div>- </div>-- <!-- Notes Panel -->- <div v-show="selectedTab === 'notes'" class="h-full">- <div v-if="!editingNotes" class="content-box h-full flex flex-col min-h-0">- <div class="notes-box custom-scrollbar" v-html="selectedRecording.notes_html || selectedRecording.notes || 'No notes'"></div>- </div>- <textarea v-else v-model="selectedRecording.notes" @blur="saveInlineEdit('notes')" class="notes-box custom-scrollbar w-full focus:ring-[var(--ring-focus)] focus:border-[var(--border-focus)] tab-content-box flex-1 height-100" placeholder="Enter notes"></textarea>- </div>-- <!-- Metadata Panel (in separate tab) -->- <div v-show="selectedTab === 'metadata'" class="h-full">- <div class="metadata-panel custom-scrollbar tab-content-box">- <dl class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-4 text-sm">- <div class="metadata-grid-item">- <dt><i class="fas fa-file-alt mr-2 text-[var(--text-muted)]"></i>Original Filename</dt>- <dd>${ selectedRecording.original_filename || 'N/A' }</dd>- </div>- <div class="metadata-grid-item">- <dt><i class="fas fa-database mr-2 text-[var(--text-muted)]"></i>File Size</dt>- <dd>${ formatFileSize(selectedRecording.file_size) }</dd>- </div>- <div v-if="selectedRecording.completed_at" class="metadata-grid-item">- <dt><i class="fas fa-check-circle mr-2 text-[var(--text-muted)]"></i>Processed On</dt>- <dd>${ new Date(selectedRecording.completed_at).toLocaleString() }</dd>- </div>- <div v-if="selectedRecording.processing_time_seconds" class="metadata-grid-item">- <dt><i class="fas fa-hourglass-half mr-2 text-[var(--text-muted)]"></i>Processing Time</dt>- <dd>${ formatDuration(selectedRecording.processing_time_seconds) }</dd>- </div>- </dl>- </div>- </div>+ </div>+ </td>+ <td>+ <div class="custom-number-input">+ <input type="number" step="0.01" v-model.number="segment.start_time" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" />+ <div class="number-spinners">+ <button @click="adjustTime(index, 'start_time', 0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5" /></svg></button>+ <button @click="adjustTime(index, 'start_time', -0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /></svg></button></div></div>- </div>-- <!-- Resizer Handle for Main Columns -->- <div id="mainColumnResizer"- class="hidden md:flex items-center justify-center w-2 bg-transparent cursor-ew-resize flex-shrink-0 mx-1 group"- title="Drag to resize columns">- <div class="w-1 h-10 bg-[var(--text-light)] group-hover:bg-[var(--border-accent)] rounded-full transition-colors duration-150"></div>- </div>-- <!-- Right Column: Audio & Chat -->- <div id="rightMainColumn" class="content-column right-content flex-grow">- <!-- Audio Player Section -->- <div class="audio-section">- <h4 class="font-semibold text-[var(--text-secondary)] mb-2">Audio Player</h4>- <div class="bg-[var(--bg-audio-player)] p-3 rounded-lg shadow border border-[var(--border-primary)]">- <audio controls class="w-full h-10" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">- Your browser does not support the audio element.- </audio>+ </td>+ <td>+ <div class="custom-number-input">+ <input type="number" step="0.01" v-model.number="segment.end_time" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" />+ <div class="number-spinners">+ <button @click="adjustTime(index, 'end_time', 0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5" /></svg></button>+ <button @click="adjustTime(index, 'end_time', -0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /></svg></button></div></div>+ </td>+ <td>+ <textarea v-model="segment.sentence" rows="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"></textarea>+ </td>+ <td class="text-center">+ <button @click="removeSegment(index)" class="text-red-500 hover:text-red-700">+ <i class="fas fa-trash"></i>+ </button>+ </td>+ </tr>+ </tbody>+ </table>+ <div class="mt-4">+ <button @click="addSegment" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">+ <i class="fas fa-plus mr-2"></i> Add Segment+ </button>+ </div>+ </div>+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">+ <button @click="closeAsrEditorModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button @click="saveAsrTranscription" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save Changes</button>+ </div>+ </div>+ </div>- <!-- Chat Section -->- <div class="chat-section">- <h4 class="font-semibold text-[var(--text-secondary)] mb-2 flex-shrink-0">Chat with Transcript</h4>- <div class="chat-container border-[var(--border-primary)] bg-[var(--bg-secondary)] h-full">- <div class="chat-messages custom-scrollbar" ref="chatMessagesRef">- <div v-if="chatMessages.length === 0" class="flex items-center justify-center h-full text-[var(--text-muted)]">- <div class="text-center">- <i class="fas fa-comments text-2xl mb-2"></i>- <p>Ask questions about the transcript</p>- </div>- </div>- <div v-for="(message, index) in chatMessages" :key="index" class="message" :class="message.role === 'user' ? 'user-message bg-[var(--bg-accent)] text-[var(--text-accent)]' : 'ai-message bg-[var(--bg-tertiary)] text-[var(--text-secondary)]'">- <div class="flex justify-between items-start">- <div class="flex-grow" v-if="message.role === 'user'">${ message.content }</div>- <div class="flex-grow" v-else v-html="message.html || message.content"></div>- <button v-if="message.role === 'assistant'" @click="copyMessage(message.content, $event)" class="ml-2 text-[var(--text-light)] hover:text-[var(--text-muted)]" title="Copy response">- <i class="fas fa-copy text-xs"></i>- </button>- </div>- </div>- <div v-if="isChatLoading" class="message ai-message bg-[var(--bg-tertiary)] text-[var(--text-secondary)]">- <div class="flex items-center">- <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...- </div>+ <!-- Speaker Identification Modal -->+ <div v-if="showSpeakerModal" @click="closeSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-4xl flex flex-col max-h-[90vh]">+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0">+ <h3 class="text-xl font-bold text-[var(--text-primary)]">Identify Speakers</h3>+ <!-- Warning for too many speakers -->+ <div v-if="identifiedSpeakers.length > 8" class="mt-3 p-3 bg-[var(--bg-warn-light)] border border-amber-300 dark:border-amber-800 rounded-lg">+ <div class="flex items-start">+ <i class="fas fa-exclamation-triangle text-[var(--text-warn-strong)] mt-0.5 mr-2"></i>+ <div class="text-sm">+ <p class="font-medium text-[var(--text-warn-strong)]">More speakers than available colors</p>+ <p class="text-[var(--text-warn-strong)] mt-1">+ You have ${ identifiedSpeakers.length } speakers, but only 8 unique colors are available.+ Colors will repeat after the 8th speaker.+ </p>+ </div>+ </div>+ </div>+ </div>+ <div class="flex-grow flex overflow-hidden modal-content">+ <div class="w-1/3 p-6 space-y-4 overflow-y-auto custom-scrollbar border-r border-[var(--border-primary)]">+ <div v-for="(speaker, index) in identifiedSpeakers" :key="`${selectedRecording.id}-speaker-${index}-${speaker}`" class="space-y-3">+ <!-- Speaker label with color indicator and "This is Me" checkbox on same line -->+ <div class="flex items-center justify-between">+ <div class="flex items-center space-x-2">+ <div :class="speakerMap[speaker].color" class="w-4 h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>+ <span class="font-mono text-sm text-[var(--text-muted)]">${ speaker }</span>+ <span v-if="index >= 8" class="text-xs text-[var(--text-warn-strong)] bg-[var(--bg-warn-light)] px-2 py-0.5 rounded-full" title="Color repeats from speaker ${ ((index % 8) + 1) }">+ Repeat+ </span>+ </div>+ <label class="flex items-center text-sm text-[var(--text-muted)]">+ <input type="checkbox" v-model="speakerMap[speaker].isMe" @focus="highlightSpeakerInTranscript(speaker)" @blur="clearSpeakerHighlight" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <span class="ml-2">Me</span>+ </label>+ </div>++ <!-- Autocomplete input field - disabled when "This is Me" is checked -->+ <div class="relative">+ <input+ type="text"+ v-model="speakerMap[speaker].name"+ @input="searchSpeakers($event.target.value, speaker)"+ @focus="focusSpeaker(speaker)"+ @blur="blurSpeaker(); setTimeout(() => speakerSuggestions[speaker] = [], 200)"+ :disabled="speakerMap[speaker].isMe"+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"+ :placeholder="speakerMap[speaker].isMe ? 'Me' : 'Enter name for ' + speaker"+ autocomplete="off">++ <!-- Loading indicator -->+ <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe" class="absolute right-3 top-1/2 transform -translate-y-1/2">+ <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>+ </div>++ <!-- Suggestions dropdown -->+ <div v-if="speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"+ class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">+ <div class="py-1">+ <div v-for="suggestion in speakerSuggestions[speaker]"+ :key="suggestion.id"+ @mousedown="selectSpeakerSuggestion(speaker, suggestion)"+ class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">+ <div class="flex-grow">+ <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>+ <div class="text-xs text-[var(--text-muted)]">+ Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }+ <span v-if="suggestion.last_used">+ • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }+ </span></div></div>- <div class="chat-input-container border-t-[var(--border-primary)]">- <textarea- v-model="chatInput"- @keyup.enter.exact="sendChatMessage"- @keyup.enter.shift.exact.prevent="chatInput += '\n'"- placeholder="Ask about the transcript... (Shift+Enter for new line)"- class="flex-grow px-3 py-2 border-0 focus:ring-0 focus:outline-none bg-[var(--bg-input)] text-[var(--text-primary)] placeholder-[var(--text-muted)] resize-none custom-scrollbar"- :disabled="isChatLoading || !selectedRecording || selectedRecording.status !== 'COMPLETED'"- rows="3"- ></textarea>- <button- @click="sendChatMessage"- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"- :disabled="!chatInput.trim() || isChatLoading || !selectedRecording || selectedRecording.status !== 'COMPLETED'"- >- <i class="fas" :class="isChatLoading ? 'fa-spinner fa-spin' : 'fa-paper-plane'"></i>- </button>- </div>+ <i class="fas fa-user text-[var(--text-muted)] ml-2"></i></div></div></div></div></div>- <div v-else class="flex flex-col items-center justify-center text-center text-[var(--text-muted)] flex-grow">- <i class="fas fa-hand-pointer text-4xl text-[var(--text-light)] mb-4"></i>- <p class="text-lg font-medium mb-2">Select a recording from the list to view details.</p>- <p>Or, drag and drop audio file(s) anywhere on this page to upload.</p>+ </div>+ <div class="w-2/3 p-6 flex flex-col overflow-hidden">+ <!-- Audio Player Section -->+ <div class="mb-4 flex-shrink-0">+ <h4 class="font-semibold text-[var(--text-secondary)] mb-2">Audio Player</h4>+ <div class="bg-[var(--bg-audio-player)] p-3 rounded-lg shadow border border-[var(--border-primary)]">+ <audio controls class="w-full h-10 speaker-modal-transcript" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">+ Your browser does not support the audio element.+ </audio>+ </div>+ </div>++ <!-- Transcript Section -->+ <div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent">+ <div v-if="processedTranscription.isJson">+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2" :data-start-time="segment.startTime">+ <p>+ <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId">[${ segment.speaker }]</span>:+ <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5">${ segment.sentence }</span>+ </p>+ </div>+ </div>+ <div v-else v-html="highlightedTranscript"></div></div></div></div>+ <div class="p-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex-shrink-0">+ <label class="flex items-center text-sm text-[var(--text-muted)]">+ <input type="checkbox" v-model="regenerateSummaryAfterSpeakerUpdate" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <span class="ml-2">Regenerate summary after updating names</span>+ </label></div>-- <!-- Mobile fallback when no recording selected -->- <div v-if="!selectedRecording" class="mobile-layout">- <div class="flex flex-col items-center justify-center text-center text-[var(--text-muted)] h-full p-8">- <i class="fas fa-hand-pointer text-4xl text-[var(--text-light)] mb-4"></i>- <p class="text-lg font-medium mb-2">Select a recording from the menu to view details.</p>- <p>Tap the menu button in the header to browse recordings.</p>+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">+ <div>+ <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">+ <i class="fas fa-magic mr-2"></i>+ <span v-if="!isAutoIdentifying">Auto Identify</span>+ <span v-else>+ <i class="fas fa-spinner fa-spin mr-2"></i>+ Identifying...+ </span>+ </button>+ </div>+ <div class="flex space-x-3">+ <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button+ @click="saveSpeakerNames"+ :disabled="!hasSpeakerNames"+ :class="hasSpeakerNames+ ? 'px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer'+ : 'px-4 py-2 bg-gray-400 text-gray-200 rounded-lg cursor-not-allowed'"+ >+ Save Names+ </button></div></div></div>+ </div>- <div v-if="currentView === 'upload'"- class="flex-grow flex items-center justify-center p-4">- <div class="w-full max-w-lg bg-[var(--bg-secondary)] p-8 rounded-xl shadow-lg border border-[var(--border-primary)] text-center drag-area"- :class="{'border-[var(--border-focus)] bg-[var(--bg-accent)]': dragover}">- <div class="py-8">- <i class="fas fa-cloud-upload-alt text-5xl mb-5 text-[var(--text-accent)]"></i>- <h2 class="text-xl font-semibold text-[var(--text-secondary)] mb-2">Upload New Recordings</h2>- <p class="text-[var(--text-muted)] mb-4">Drag & drop your audio files here or click below.</p>- <input type="file" @change="handleFileSelect" accept="audio/*" class="hidden" ref="fileInput" multiple>- <div class="flex flex-col sm:flex-row sm:justify-center sm:items-center mt-4 space-y-3 sm:space-y-0 sm:space-x-3">- <template v-if="!isRecording">- <button @click="$refs.fileInput.click()" class="w-full sm:w-auto px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] shadow-sm transition duration-150 ease-in-out flex items-center justify-center">- <i class="fas fa-file-import mr-2"></i> Select Files- </button>- <!-- New Record Audio Button -->- <button @click="startRecording" v-if="canRecordAudio" class="w-full sm:w-auto px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 shadow-sm transition duration-150 ease-in-out flex items-center justify-center">- <i class="fas fa-microphone mr-2"></i> Record Audio- </button>- </template>- <button @click="stopRecording" v-if="isRecording" class="w-full sm:w-auto px-6 py-3 bg-red-500 text-white rounded-lg hover:bg-red-600 shadow-sm transition duration-150 ease-in-out flex items-center justify-center">- <i class="fas fa-stop mr-2"></i> Stop Recording- </button>- </div>- <div v-if="isRecording" class="mt-3 text-[var(--text-muted)]">- <i class="fas fa-circle text-red-500 fa-xs blink mr-1"></i> Recording: ${ formatTime(recordingTime) }- </div>- <div v-if="audioBlobURL" class="mt-4 p-4 border border-[var(--border-primary)] rounded-lg bg-[var(--bg-tertiary)]">- <p class="text-sm text-[var(--text-secondary)] mb-2 font-medium">Preview your recording:</p>- <audio :src="audioBlobURL" controls class="w-full rounded" :volume="playerVolume" @volumechange="onPlayerVolumeChange"></audio>- <div class="mt-3 flex flex-col sm:flex-row sm:justify-center sm:items-center space-y-2 sm:space-y-0 sm:space-x-2">- <button @click="uploadRecordedAudio" class="w-full sm:w-auto px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">- <i class="fas fa-upload mr-1"></i> Upload Recording- </button>- <button @click="discardRecording" class="w-full sm:w-auto px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 dark:bg-gray-600 dark:text-gray-200 dark:hover:bg-gray-500">- <i class="fas fa-trash mr-1"></i> Discard- </button>- </div>- </div>- <p v-if="!canRecordAudio && currentView === 'upload' && !isRecording && !audioBlobURL" class="mt-4 text-sm text-[var(--text-muted)]">- Audio recording may not be supported or permission is denied.- </p>- <p class="text-xs text-[var(--text-light)] mt-6">Max file size per file: ${ maxFileSizeMB } MB</p>- </div>+ <!-- Global Error Display -->+ <div v-if="globalError"+ class="fixed top-4 right-4 bg-[var(--bg-danger)] text-white p-4 rounded-lg shadow-lg z-50 max-w-md">+ <div class="flex items-start gap-3">+ <i class="fas fa-exclamation-circle text-lg flex-shrink-0 mt-0.5"></i>+ <div class="flex-1">+ <p class="font-medium">Error</p>+ <p class="text-sm opacity-90">${globalError}</p></div>+ <button @click="globalError = null"+ class="text-white hover:text-gray-200 transition-colors">+ <i class="fas fa-times"></i>+ </button></div>+ </div>- {% else %}- <div class="flex-grow flex items-center justify-center">- <div class="text-center max-w-lg p-8 bg-[var(--bg-secondary)] rounded-xl shadow-lg border border-[var(--border-primary)]">- <i class="fas fa-lock text-5xl mb-4 text-[var(--text-accent)]"></i>- <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-4">Welcome to Speakr</h2>- <p class="text-[var(--text-secondary)] mb-6">- Speakr is an audio transcription and summarization app that helps you convert your audio recordings into text and generate summaries.- </p>- <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4">- <a href="{{ url_for('login') }}" class="px-6 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">- <i class="fas fa-sign-in-alt mr-2"></i> Login- </a>- <a href="{{ url_for('register') }}" class="px-6 py-2 text-[var(--text-secondary)] hover:text-[var(--text-accent)] border border-[var(--border-secondary)] rounded-lg">- <i class="fas fa-user-plus mr-2"></i> Register- </a>+ <!-- System Audio Help Modal -->+ <div v-if="showSystemAudioHelp" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">+ <div class="bg-[var(--bg-secondary)] w-full h-full md:h-auto md:max-h-[90vh] md:w-full md:max-w-2xl md:rounded-lg md:shadow-xl flex flex-col">+ <div class="p-4 border-b border-[var(--border-primary)] flex-shrink-0">+ <div class="flex items-center justify-between">+ <h3 class="text-lg font-semibold flex items-center">+ <i class="fas fa-desktop mr-2 text-blue-500"></i>+ System Audio Recording+ </h3>+ <button @click="showSystemAudioHelp = false" class="text-[var(--text-muted)] hover:text-[var(--text-primary)]">+ <i class="fas fa-times"></i>+ </button></div></div>- </div>- {% endif %}- </main>-- <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">- Speakr © ${ new Date().getFullYear() }- <span class="mx-2">|</span>- <a href="https://github.com/murtaza-nasir/speakr" target="_blank" rel="noopener noreferrer" class="hover:text-[var(--text-accent)] transition-colors duration-200">- <i class="fab fa-github mr-1"></i>- GitHub- </a>- </footer>+ <div class="p-6 space-y-6 overflow-y-auto flex-grow">+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <h4 class="font-medium text-[var(--text-primary)] mb-2">How to Record System Audio</h4>+ <p class="text-sm text-[var(--text-muted)]">+ To capture audio from meetings or other apps, you must share your screen or a browser tab.+ </p>+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-3">+ <li>Click "Record System Audio" or "Record Both".</li>+ <li>In the popup, choose <strong>"Entire Screen"</strong> or a <strong>specific browser tab</strong>.</li>+ <li>Make sure to check the box that says <strong>"Share tab audio"</strong> or <strong>"Share system audio"</strong>.</li>+ </ol>+ <p class="text-xs text-amber-600 dark:text-amber-400 mt-3"><i class="fas fa-exclamation-triangle mr-1"></i>Sharing a "Window" will not capture audio.</p>+ </div>- <div v-if="showEditModal" @click="cancelEdit" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col overflow-hidden transform transition-all duration-300 ease-in-out">- <!-- Header with gradient background -->- <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 flex justify-between items-center flex-shrink-0">- <h3 class="text-xl font-bold text-[var(--text-primary)] flex items-center">- <i class="fas fa-edit mr-2 text-[var(--text-accent)]"></i>- Edit Recording Details- </h3>- <button @click="cancelEdit" class="text-[var(--text-light)] hover:text-[var(--text-primary)] transition-colors duration-200 rounded-full h-8 w-8 flex items-center justify-center hover:bg-[var(--bg-tertiary)]">- <i class="fas fa-times"></i>- </button>- </div>-- <!-- Form content with custom scrollbar -->- <div class="p-6 overflow-y-auto custom-scrollbar modal-content flex-grow">- <div v-if="editingRecording" class="space-y-5">- <!-- Title field with icon -->- <div class="form-group">- <label class="flex items-center text-sm font-medium text-[var(--text-secondary)] mb-1.5">- <i class="fas fa-heading text-[var(--text-accent)] mr-2"></i>- Title- </label>- <div class="relative">- <input- v-model="editingRecording.title"- class="pl-3 pr-3 py-2.5 block w-full rounded-lg border border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-2 focus:ring-[var(--ring-focus)] focus:ring-opacity-30 bg-[var(--bg-input)] text-[var(--text-primary)] transition-all duration-200"- placeholder="Enter recording title">- </div>- </div>-- <!-- Participants field with icon -->- <div class="form-group">- <label class="flex items-center text-sm font-medium text-[var(--text-secondary)] mb-1.5">- <i class="fas fa-users text-[var(--text-accent)] mr-2"></i>- Participants- </label>- <div class="relative">- <input- v-model="editingRecording.participants"- class="pl-3 pr-3 py-2.5 block w-full rounded-lg border border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-2 focus:ring-[var(--ring-focus)] focus:ring-opacity-30 bg-[var(--bg-input)] text-[var(--text-primary)] transition-all duration-200"- placeholder="Enter participant names">- </div>- </div>+ <div class="space-y-4">+ <h4 class="font-medium text-[var(--text-primary)]">Troubleshooting</h4>- <!-- Meeting Date field with icon -->- <div class="form-group">- <label class="flex items-center text-sm font-medium text-[var(--text-secondary)] mb-1.5">- <i class="fas fa-calendar-alt text-[var(--text-accent)] mr-2"></i>- Meeting Date- </label>- <div class="relative">- <input- type="date"- v-model="editingRecording.meeting_date"- class="pl-3 pr-3 py-2.5 block w-full rounded-lg border border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-2 focus:ring-[var(--ring-focus)] focus:ring-opacity-30 bg-[var(--bg-input)] text-[var(--text-primary)] transition-all duration-200">- </div>+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <h5 class="font-medium text-[var(--text-primary)] mb-2">Why isn't it working?</h5>+ <p class="text-sm text-[var(--text-muted)]">+ System audio recording requires a secure (HTTPS) connection. If you are developing locally, you may need to enable a browser flag.+ </p></div>-- <!-- Divider -->- <div class="relative py-3">- <div class="absolute inset-0 flex items-center">- <div class="w-full border-t border-[var(--border-primary)]"></div>- </div>- <div class="relative flex justify-center">- <span class="bg-[var(--bg-secondary)] px-4 text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Content</span>- </div>++ <!-- Chrome Solution -->+ <div v-if="browser === 'chrome'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">+ <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">+ <i class="fab fa-chrome mr-2"></i>+ For Chrome on Localhost+ </h5>+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">+ <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">chrome://flags/#unsafely-treat-insecure-origin-as-secure</code></li>+ <li>Add your local URL (e.g., <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">http://localhost:8899</code>)</li>+ <li>Set to <strong>"Enabled"</strong> and relaunch Chrome.</li>+ </ol></div>-- <!-- Summary field with icon -->- <div class="form-group">- <label class="flex items-center text-sm font-medium text-[var(--text-secondary)] mb-1.5">- <i class="fas fa-file-alt text-[var(--text-accent)] mr-2"></i>- Summary- </label>- <div class="relative">- <textarea- v-model="editingRecording.summary"- class="pl-3 pr-3 py-2.5 block w-full rounded-lg border border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-2 focus:ring-[var(--ring-focus)] focus:ring-opacity-30 bg-[var(--bg-input)] text-[var(--text-primary)] transition-all duration-200"- rows="5"- placeholder="Enter summary of the recording"></textarea>- </div>++ <!-- Firefox Solution -->+ <div v-else-if="browser === 'firefox'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">+ <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">+ <i class="fab fa-firefox-browser mr-2"></i>+ For Firefox on Localhost+ </h5>+ <p class="text-sm text-[var(--text-secondary)]">+ System audio recording is not well-supported on Firefox, even with these changes. For best results, please use Chrome.+ </p>+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-2">+ <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">about:config</code></li>+ <li>Search for <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">media.devices.insecure.enabled</code> and set it to `true`.</li>+ <li>Restart Firefox.</li>+ </ol></div>-- <!-- Notes field with icon -->- <div class="form-group">- <label class="flex items-center text-sm font-medium text-[var(--text-secondary)] mb-1.5">- <i class="fas fa-sticky-note text-[var(--text-accent)] mr-2"></i>- Notes- </label>- <div class="relative">- <textarea- v-model="editingRecording.notes"- class="pl-3 pr-3 py-2.5 block w-full rounded-lg border border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-2 focus:ring-[var(--ring-focus)] focus:ring-opacity-30 bg-[var(--bg-input)] text-[var(--text-primary)] transition-all duration-200"- rows="4"- placeholder="Enter additional notes"></textarea>- </div>++ <!-- Other Browsers -->+ <div v-else class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <h5 class="font-medium text-[var(--text-primary)] mb-2">Unsupported Browser</h5>+ <p class="text-sm text-[var(--text-muted)]">+ For the best experience with system audio recording, we recommend using Google Chrome.+ </p></div></div></div>-- <!-- Footer with action buttons -->- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0">- <button- @click="cancelEdit"- class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors duration-200 flex items-center shadow-sm">- <i class="fas fa-times mr-2"></i>- Cancel+ <div class="p-4 border-t border-[var(--border-primary)] flex justify-end flex-shrink-0">+ <button @click="showSystemAudioHelp = false"+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">+ Got it</button>- <button- @click="saveEdit"- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors duration-200 flex items-center shadow-sm">- <i class="fas fa-save mr-2"></i>- Save Changes- </button>- </div>- </div>- </div>-- <div v-if="showDeleteModal" @click="cancelDelete" class="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4">- <div @click.stop class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl max-w-md w-full modal-content">- <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4">Confirm Delete</h3>- <p v-if="recordingToDelete" class="mb-2 text-[var(--text-secondary)]">Are you sure you want to permanently delete the recording titled "<strong>${ recordingToDelete.title }</strong>"?</p>- <p class="text-sm text-[var(--text-danger)] mb-6">This action cannot be undone and will delete the record, transcription, summary, and the audio file.</p>- <div class="flex justify-end space-x-3">- <button @click="cancelDelete" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">Cancel</button>- <button @click="deleteRecording" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">Delete Permanently</button></div></div></div>- <div v-if="(uploadQueue.length > 0 || currentlyProcessingFile) && !progressPopupClosed"- class="progress-popup bg-[var(--bg-secondary)] rounded-lg shadow-xl border border-[var(--border-primary)] overflow-hidden"- :class="{ 'minimized': progressPopupMinimized }">+ <!-- Toast Container -->+ <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>- <div class="flex justify-between items-center p-2 bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)]">- <h4 class="text-sm font-semibold text-[var(--text-secondary)] cursor-pointer" @click="progressPopupMinimized = !progressPopupMinimized">- <i class="fas fa-upload mr-2 text-[var(--text-accent)]"></i>- Upload & Process Progress (${ completedInQueue }/${ totalInQueue } completed)- </h4>- <div class="flex items-center">- <button class="text-[var(--text-muted)] hover:text-[var(--text-secondary)] mr-2" @click="progressPopupMinimized = !progressPopupMinimized">- <i :class="progressPopupMinimized ? 'fa-chevron-up' : 'fa-chevron-down'" class="fas fa-fw"></i>- </button>- <button class="text-[var(--text-muted)] hover:text-[var(--text-danger)]" @click="progressPopupClosed = true" title="Close">- <i class="fas fa-times fa-fw"></i>- </button>+ <!-- Share Modal -->+ <div v-if="showShareModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">+ <div class="p-6 border-b border-[var(--border-primary)]">+ <h3 class="text-lg font-semibold">Share Recording</h3></div>- </div>-- <div class="p-3 max-h-60 overflow-y-auto custom-scrollbar" v-show="!progressPopupMinimized">- <div v-if="currentlyProcessingFile" class="mb-3 pb-3 border-b border-dashed border-[var(--border-secondary)]">- <div class="flex items-center justify-between mb-1">- <p class="text-xs font-medium text-[var(--text-primary)] truncate mr-2" :title="currentlyProcessingFile.file.name">- <i class="fas fa-spinner fa-spin text-[var(--text-accent)] mr-1"></i> Processing: <span class="truncate">${ currentlyProcessingFile.file.name }</span>- </p>- <span class="text-xs text-[var(--text-muted)] flex-shrink-0">${ formatFileSize(currentlyProcessingFile.file.size) }</span>+ <div class="p-6 space-y-4">+ <p class="text-sm text-[var(--text-muted)]">Create a public link to share this recording. Sharing is only available on secure (HTTPS) connections.</p>+ <div v-if="!generatedShareLink">+ <div class="flex items-center mb-2">+ <input type="checkbox" v-model="shareOptions.share_summary" id="share_summary" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <label for="share_summary" class="ml-2 block text-sm text-[var(--text-secondary)]">Share Summary</label>+ </div>+ <div class="flex items-center">+ <input type="checkbox" v-model="shareOptions.share_notes" id="share_notes" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <label for="share_notes" class="ml-2 block text-sm text-[var(--text-secondary)]">Share Notes</label>+ </div></div>- <p class="text-xs text-[var(--text-secondary)] mb-1 italic">${ processingMessage }</p>- <div class="w-full bg-[var(--border-primary)] rounded-full h-1.5">- <div class="bg-[var(--text-accent)] h-1.5 rounded-full transition-all duration-300" :style="{ width: processingProgress + '%' }"></div>+ <div v-if="generatedShareLink" class="mt-4">+ <label class="block text-sm font-medium mb-2">Shareable Link</label>+ <div class="flex items-center gap-2">+ <input :value="generatedShareLink" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg">+ <button @click="copyShareLink" class="px-3 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">+ <i class="fas fa-copy"></i>+ </button>+ </div></div></div>-- <div v-if="queuedFiles.length > 0" class="mb-2">- <p class="text-xs font-semibold text-[var(--text-muted)] mb-1">${ queuedFiles.length } file(s) queued:</p>- <ul class="space-y-1">- <li v-for="item in queuedFiles" :key="item.clientId" class="text-xs text-[var(--text-secondary)] progress-list-item">- <i class="fas fa-clock text-[var(--text-light)] fa-fw"></i>- <span class="truncate" :title="item.file.name">${ item.file.name }</span>- <span class="text-[var(--text-light)] flex-shrink-0">${ formatFileSize(item.file.size) }</span>- </li>- </ul>+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">+ <button @click="closeShareModal" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">+ Cancel+ </button>+ <button @click="createShare" v-if="!generatedShareLink" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">+ Create Link+ </button></div>+ </div>+ </div>- <div v-if="finishedFilesInQueue.length > 0" class="mt-2 pt-2 border-t border-dashed border-[var(--border-secondary)]">- <p class="text-xs font-semibold text-[var(--text-muted)] mb-1">Recently finished:</p>- <ul class="space-y-1">- <li v-for="item in finishedFilesInQueue.slice(-5)" :key="item.clientId" class="text-xs progress-list-item">- <i v-if="item.status === 'completed'" class="fas fa-check-circle text-[var(--text-success-strong)] fa-fw"></i>- <i v-else-if="item.status === 'failed'" class="fas fa-exclamation-triangle text-[var(--text-danger-strong)] fa-fw"></i>- <i v-else class="fas fa-question-circle text-[var(--text-light)] fa-fw"></i>- <span class="truncate text-[var(--text-secondary)]" :title="item.file.name">${ item.file.name }</span>- <span v-if="item.status === 'failed'" class="text-[var(--text-danger)] text-xs italic flex-shrink-0">Failed</span>- <span v-else class="text-[var(--text-light)] flex-shrink-0">${ formatFileSize(item.file.size) }</span>- </li>- </ul>+ <!-- Shares List Modal -->+ <div v-if="showSharesListModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">+ <div class="p-6 border-b border-[var(--border-primary)] flex justify-between items-center">+ <h3 class="text-lg font-semibold">My Shared Transcripts</h3>+ <button @click="closeSharesList" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">+ <i class="fas fa-times"></i>+ </button></div>-- <div v-if="uploadQueue.length > 0 && queuedFiles.length === 0 && !currentlyProcessingFile" class="text-xs text-center text-[var(--text-muted)] py-2">- All uploads processed.+ <div class="p-6 space-y-4 overflow-y-auto">+ <div v-if="isLoadingShares" class="text-center">+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>+ </div>+ <div v-else-if="userShares.length === 0" class="text-center text-[var(--text-muted)]">+ You haven't shared any transcripts yet.+ </div>+ <div v-else class="space-y-3">+ <div v-for="share in userShares" :key="share.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <div class="flex justify-between items-start">+ <div>+ <p class="font-semibold">${share.recording_title}</p>+ <p class="text-sm text-[var(--text-muted)]">Shared on: ${share.created_at}</p>+ </div>+ <button @click="deleteShare(share.id)" class="text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>+ </div>+ <div class="mt-4 flex items-center gap-4">+ <label class="flex items-center text-sm">+ <input type="checkbox" v-model="share.share_summary" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <span class="ml-2">Share Summary</span>+ </label>+ <label class="flex items-center text-sm">+ <input type="checkbox" v-model="share.share_notes" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">+ <span class="ml-2">Share Notes</span>+ </label>+ </div>+ <div class="mt-4">+ <input :value="'{{ request.url_root }}share/' + share.public_id" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">+ </div>+ </div>+ </div></div></div></div>-</div>-- <!-- Toast container for notifications -->- <div class="toast-container" id="toastContainer"></div>-- <!-- App.js is already included in the head section -->++ <!-- Vue.js Application Script -->+ <script src="{{ url_for('static', filename='js/app.js') }}"></script></body></html>diff --git a/templates/login.html b/templates/login.htmlindex f72728f8..a7b080f7 100644--- a/templates/login.html+++ b/templates/login.html@@ -4,104 +4,48 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - Speakr</title>- <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml"><script src="https://cdn.tailwindcss.com"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">- <style>- /* Dark Mode CSS Variables */- :root {- /* Light mode variables */- --bg-primary: #f3f4f6; /* gray-100 */- --bg-secondary: #ffffff; /* white */- --bg-tertiary: #f9fafb; /* gray-50 */- --bg-accent: #dbeafe; /* blue-100 */- --bg-accent-hover: #bfdbfe; /* blue-200 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #1d4ed8; /* blue-700 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #b91c1c; /* red-700 */- --bg-danger-light: #fee2e2; /* red-100 */- --bg-info-light: #dbeafe; /* blue-100 */- --bg-warn-light: #fef3c7; /* amber-100 */- --bg-success-light: #d1fae5; /* green-100 */- --bg-pending-light: #f5f5f4; /* stone-100 */- --bg-input: #ffffff; /* white */+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <script>+ // Function to apply the theme based on localStorage+ function applyTheme() {+ // Apply dark mode+ const savedMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }- --text-primary: #1f2937; /* gray-800 */- --text-secondary: #374151; /* gray-700 */- --text-muted: #6b7280; /* gray-500 */- --text-light: #9ca3af; /* gray-400 */- --text-accent: #1d4ed8; /* blue-700 */- --text-button: #ffffff; /* white */- --text-danger: #b91c1c; /* red-700 */- --text-danger-strong: #991b1b; /* red-800 */- --text-info-strong: #1e40af; /* blue-800 */- --text-warn-strong: #92400e; /* amber-800 */- --text-success-strong: #065f46; /* green-800 */- --text-pending-strong: #44403c; /* stone-700 */+ // Apply color scheme+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const isDark = document.documentElement.classList.contains('dark');+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';++ // Remove all other theme classes+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];+ themeClasses.forEach(theme => {+ document.documentElement.classList.remove(`theme-light-${theme}`);+ document.documentElement.classList.remove(`theme-dark-${theme}`);+ });- --border-primary: #e5e7eb; /* gray-200 */- --border-secondary: #d1d5db; /* gray-300 */- --border-accent: #93c5fd; /* blue-300 */- --border-danger: #f87171; /* red-400 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #bfdbfe; /* blue-200 */+ // Add the correct theme class+ if (savedScheme !== 'blue') {+ document.documentElement.classList.add(themePrefix + savedScheme);+ }}-- .dark {- /* Dark mode variables */- --bg-primary: #111827; /* gray-900 */- --bg-secondary: #1f2937; /* gray-800 */- --bg-tertiary: #374151; /* gray-700 */- --bg-accent: #1e3a8a; /* blue-900 */- --bg-accent-hover: #1e40af; /* blue-800 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #3b82f6; /* blue-500 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #ef4444; /* red-500 */- --bg-danger-light: #7f1d1d; /* red-900 */- --bg-info-light: #1e3a8a; /* blue-900 */- --bg-warn-light: #78350f; /* amber-900 */- --bg-success-light: #064e3b; /* green-900 */- --bg-pending-light: #292524; /* stone-800 */- --bg-input: #374151; /* gray-700 */-- --text-primary: #f3f4f6; /* gray-100 */- --text-secondary: #d1d5db; /* gray-300 */- --text-muted: #9ca3af; /* gray-400 */- --text-light: #6b7280; /* gray-500 */- --text-accent: #60a5fa; /* blue-400 */- --text-button: #ffffff; /* white */- --text-danger: #f87171; /* red-400 */- --text-danger-strong: #fca5a5; /* red-300 */- --text-info-strong: #93c5fd; /* blue-300 */- --text-warn-strong: #fcd34d; /* amber-300 */- --text-success-strong: #6ee7b7; /* green-300 */- --text-pending-strong: #d6d3d1; /* stone-300 */-- --border-primary: #374151; /* gray-700 */- --border-secondary: #4b5563; /* gray-600 */- --border-accent: #1d4ed8; /* blue-700 */- --border-danger: #ef4444; /* red-500 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #1e40af; /* blue-800 */- }-- html {- background-color: var(--bg-primary);- color: var(--text-primary);- transition: background-color 0.3s, color 0.3s;- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;- }- html, body { height: 100%; margin: 0; }- </style>+ applyTheme();+ </script></head><body class="bg-[var(--bg-primary)] text-[var(--text-primary)]"><div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen"><header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>diff --git a/templates/register.html b/templates/register.htmlindex 0a020116..05c6a5d7 100644--- a/templates/register.html+++ b/templates/register.html@@ -4,104 +4,48 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ title }} - Speakr</title>- <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml"><script src="https://cdn.tailwindcss.com"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">- <style>- /* Dark Mode CSS Variables */- :root {- /* Light mode variables */- --bg-primary: #f3f4f6; /* gray-100 */- --bg-secondary: #ffffff; /* white */- --bg-tertiary: #f9fafb; /* gray-50 */- --bg-accent: #dbeafe; /* blue-100 */- --bg-accent-hover: #bfdbfe; /* blue-200 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #1d4ed8; /* blue-700 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #b91c1c; /* red-700 */- --bg-danger-light: #fee2e2; /* red-100 */- --bg-info-light: #dbeafe; /* blue-100 */- --bg-warn-light: #fef3c7; /* amber-100 */- --bg-success-light: #d1fae5; /* green-100 */- --bg-pending-light: #f5f5f4; /* stone-100 */- --bg-input: #ffffff; /* white */+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <script>+ // Function to apply the theme based on localStorage+ function applyTheme() {+ // Apply dark mode+ const savedMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }- --text-primary: #1f2937; /* gray-800 */- --text-secondary: #374151; /* gray-700 */- --text-muted: #6b7280; /* gray-500 */- --text-light: #9ca3af; /* gray-400 */- --text-accent: #1d4ed8; /* blue-700 */- --text-button: #ffffff; /* white */- --text-danger: #b91c1c; /* red-700 */- --text-danger-strong: #991b1b; /* red-800 */- --text-info-strong: #1e40af; /* blue-800 */- --text-warn-strong: #92400e; /* amber-800 */- --text-success-strong: #065f46; /* green-800 */- --text-pending-strong: #44403c; /* stone-700 */+ // Apply color scheme+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const isDark = document.documentElement.classList.contains('dark');+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';++ // Remove all other theme classes+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];+ themeClasses.forEach(theme => {+ document.documentElement.classList.remove(`theme-light-${theme}`);+ document.documentElement.classList.remove(`theme-dark-${theme}`);+ });- --border-primary: #e5e7eb; /* gray-200 */- --border-secondary: #d1d5db; /* gray-300 */- --border-accent: #93c5fd; /* blue-300 */- --border-danger: #f87171; /* red-400 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #bfdbfe; /* blue-200 */+ // Add the correct theme class+ if (savedScheme !== 'blue') {+ document.documentElement.classList.add(themePrefix + savedScheme);+ }}-- .dark {- /* Dark mode variables */- --bg-primary: #111827; /* gray-900 */- --bg-secondary: #1f2937; /* gray-800 */- --bg-tertiary: #374151; /* gray-700 */- --bg-accent: #1e3a8a; /* blue-900 */- --bg-accent-hover: #1e40af; /* blue-800 */- --bg-button: #2563eb; /* blue-600 */- --bg-button-hover: #3b82f6; /* blue-500 */- --bg-danger: #dc2626; /* red-600 */- --bg-danger-hover: #ef4444; /* red-500 */- --bg-danger-light: #7f1d1d; /* red-900 */- --bg-info-light: #1e3a8a; /* blue-900 */- --bg-warn-light: #78350f; /* amber-900 */- --bg-success-light: #064e3b; /* green-900 */- --bg-pending-light: #292524; /* stone-800 */- --bg-input: #374151; /* gray-700 */-- --text-primary: #f3f4f6; /* gray-100 */- --text-secondary: #d1d5db; /* gray-300 */- --text-muted: #9ca3af; /* gray-400 */- --text-light: #6b7280; /* gray-500 */- --text-accent: #60a5fa; /* blue-400 */- --text-button: #ffffff; /* white */- --text-danger: #f87171; /* red-400 */- --text-danger-strong: #fca5a5; /* red-300 */- --text-info-strong: #93c5fd; /* blue-300 */- --text-warn-strong: #fcd34d; /* amber-300 */- --text-success-strong: #6ee7b7; /* green-300 */- --text-pending-strong: #d6d3d1; /* stone-300 */-- --border-primary: #374151; /* gray-700 */- --border-secondary: #4b5563; /* gray-600 */- --border-accent: #1d4ed8; /* blue-700 */- --border-danger: #ef4444; /* red-500 */- --border-focus: #3b82f6; /* blue-500 */- --ring-focus: #1e40af; /* blue-800 */- }-- html {- background-color: var(--bg-primary);- color: var(--text-primary);- transition: background-color 0.3s, color 0.3s;- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;- }- html, body { height: 100%; margin: 0; }- </style>+ applyTheme();+ </script></head><body class="bg-[var(--bg-primary)] text-[var(--text-primary)]"><div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen"><header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>diff --git a/templates/share.html b/templates/share.htmlnew file mode 100644index 00000000..a4a3158a--- /dev/null+++ b/templates/share.html@@ -0,0 +1,470 @@+<!DOCTYPE html>+<html lang="en" class="h-full">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Shared Recording - {{ recording.title }}</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">+ <script>+ tailwind.config = {+ darkMode: 'class',+ theme: {+ extend: {+ maxHeight: {+ '85vh': '85vh',+ '90vh': '90vh'+ },+ colors: {+ primary: 'var(--bg-primary)',+ secondary: 'var(--bg-secondary)',+ accent: 'var(--bg-accent)'+ }+ }+ }+ }++ // Function to apply the theme based on localStorage and system preference+ function applyTheme() {+ // Apply dark mode+ const savedMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }++ // Apply color scheme+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const isDark = document.documentElement.classList.contains('dark');+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';++ // Remove all other theme classes+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];+ themeClasses.forEach(theme => {+ document.documentElement.classList.remove(`theme-light-${theme}`);+ document.documentElement.classList.remove(`theme-dark-${theme}`);+ });++ // Add the correct theme class+ if (savedScheme !== 'blue') {+ document.documentElement.classList.add(themePrefix + savedScheme);+ }+ }+ applyTheme();+ </script>+</head>+<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">+ <div id="app" class="h-full flex flex-col" data-recording='{{ recording|tojson|safe }}'>+ <!-- Header -->+ <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">+ <div class="flex items-center gap-3">+ <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr" class="w-8 h-8">+ <div>+ <h1 class="text-xl font-bold text-[var(--text-primary)]">${ recording.title }</h1>+ <p class="text-sm text-[var(--text-muted)]">Shared Recording</p>+ </div>+ </div>+ <div class="flex items-center gap-2">+ <button @click="toggleDarkMode"+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"+ title="Toggle theme">+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>+ </button>+ </div>+ </header>++ <!-- Main Content -->+ <main class="flex-1 flex flex-col overflow-hidden">+ <!-- Audio Player - Fixed at top -->+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">+ <div class="max-w-4xl mx-auto">+ <div class="audio-player-container">+ <audio controls class="w-full" :src="'/share/audio/' + recording.public_id" ref="audioPlayer"></audio>+ </div>+ </div>+ </div>++ <!-- Tab Navigation - Fixed below audio player -->+ <div class="bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex-shrink-0">+ <div class="max-w-4xl mx-auto">+ <div class="flex">+ <button @click="activeTab = 'transcription'"+ :class="[+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',+ activeTab === 'transcription'+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'+ ]">+ <i class="fas fa-file-text mr-2"></i>Transcription+ </button>+ {% if recording.summary %}+ <button @click="activeTab = 'summary'"+ :class="[+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',+ activeTab === 'summary'+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'+ ]">+ <i class="fas fa-file-alt mr-2"></i>Summary+ </button>+ {% endif %}+ {% if recording.notes %}+ <button @click="activeTab = 'notes'"+ :class="[+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',+ activeTab === 'notes'+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'+ ]">+ <i class="fas fa-sticky-note mr-2"></i>Notes+ </button>+ {% endif %}+ </div>+ </div>+ </div>++ <!-- Tab Content - Fixed height container -->+ <div class="flex-1 flex flex-col overflow-hidden">+ <div class="max-w-4xl mx-auto p-4 flex-1 flex flex-col overflow-hidden">+ <!-- Transcription View -->+ <div v-show="activeTab === 'transcription'" class="flex-1 flex flex-col overflow-hidden">+ <!-- Transcription Controls -->+ <div class="flex items-center justify-between mb-4 flex-shrink-0">+ <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">+ <button @click="transcriptView = 'simple'"+ :class="['toggle-button', transcriptView === 'simple' ? 'active' : '']">+ <i class="fas fa-list mr-1"></i>Simple+ </button>+ <button @click="transcriptView = 'bubble'"+ :class="['toggle-button', transcriptView === 'bubble' ? 'active' : '']">+ <i class="fas fa-comments mr-1"></i>Bubble+ </button>+ </div>+ <button @click="copyTranscript" class="copy-btn">+ <i class="fas fa-copy mr-1"></i>Copy+ </button>+ </div>++ <!-- Speaker Legend (only for bubble view) -->+ <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptView === 'bubble'"+ :class="['speaker-legend', legendExpanded ? 'expanded' : '', 'flex-shrink-0', 'mb-4']">+ <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">+ <div class="speaker-legend-title">+ <i class="fas fa-users"></i>+ Speakers+ <span class="speaker-count-indicator">(${processedTranscription.speakers.length})</span>+ </div>+ <i class="fas fa-chevron-down speaker-legend-toggle"></i>+ </div>+ <div class="speaker-legend-content">+ <div v-for="(speaker, index) in processedTranscription.speakers"+ :key="index"+ :class="['speaker-legend-item', speaker.color]">+ <span class="speaker-name">${speaker.name}</span>+ </div>+ </div>+ </div>++ <!-- Transcription Content - Scrollable Box -->+ <div class="flex-1 overflow-y-auto transcription-box" @click="handleTranscriptClick">+ <!-- Simple View -->+ <div v-if="transcriptView === 'simple'" class="transcription-simple-view">+ <div v-for="segment in processedTranscription.simpleSegments"+ :key="segment.startTime || Math.random()"+ class="speaker-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors mb-2"+ :data-start-time="segment.startTime"+ @click="seekAudio(segment.startTime)"+ style="margin-bottom: 0.5rem !important;">+ <div v-if="segment.showSpeaker" :class="['speaker-tablet', segment.color]">+ ${segment.speaker}+ </div>+ <div class="speaker-text">+ ${segment.sentence}+ </div>+ </div>+ </div>++ <!-- Bubble View -->+ <div v-else-if="transcriptView === 'bubble'" class="transcription-with-speakers">+ <div v-for="(row, rowIndex) in processedTranscription.bubbleRows"+ :key="rowIndex"+ :class="['bubble-row', row.isMe ? 'speaker-me' : '']">+ <div v-for="bubble in row.bubbles"+ :key="bubble.startTime || Math.random()"+ :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '', 'cursor-pointer']"+ :data-start-time="bubble.startTime"+ @click="seekAudio(bubble.startTime)">+ <div class="speaker-bubble-content">+ ${bubble.sentence}+ </div>+ </div>+ </div>+ </div>++ <!-- Plain Text View (for non-JSON transcriptions) -->+ <div v-if="!processedTranscription.isJson" class="whitespace-pre-wrap cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors">+ ${processedTranscription.content}+ </div>+ </div>+ </div>++ <!-- Summary View -->+ {% if recording.summary %}+ <div v-show="activeTab === 'summary'" class="flex-1 flex flex-col overflow-hidden">+ <div class="flex items-center justify-end mb-4 flex-shrink-0">+ <button @click="copySummary" class="copy-btn">+ <i class="fas fa-copy mr-1"></i>Copy+ </button>+ </div>+ <div class="flex-1 overflow-y-auto summary-box">+ {{ recording.summary|safe }}+ </div>+ </div>+ {% endif %}++ <!-- Notes View -->+ {% if recording.notes %}+ <div v-show="activeTab === 'notes'" class="flex-1 flex flex-col overflow-hidden">+ <div class="flex items-center justify-end mb-4 flex-shrink-0">+ <button @click="copyNotes" class="copy-btn">+ <i class="fas fa-copy mr-1"></i>Copy+ </button>+ </div>+ <div class="flex-1 overflow-y-auto notes-box">+ {{ recording.notes|safe }}+ </div>+ </div>+ {% endif %}+ </div>+ </div>+ </main>++ <!-- Footer -->+ <footer class="bg-[var(--bg-secondary)] border-t border-[var(--border-primary)] py-4 px-4 flex-shrink-0">+ <div class="max-w-4xl mx-auto flex flex-col sm:flex-row items-center justify-between gap-3 text-sm text-[var(--text-muted)]">+ <div class="flex items-center gap-2">+ <span>© 2025 Speakr</span>+ <span class="hidden sm:inline">•</span>+ <span class="text-xs">Powered by advanced AI transcription</span>+ </div>+ <div class="flex items-center gap-2">+ <span class="text-xs">Built with</span>+ <a href="https://github.com/murtaza-nasir/speakr"+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex items-center gap-1 text-[var(--text-accent)] hover:text-[var(--text-primary)] transition-colors font-medium">+ <i class="fab fa-github text-sm"></i>+ <span>Speakr</span>+ <i class="fas fa-external-link-alt text-xs opacity-70"></i>+ </a>+ </div>+ </div>+ </footer>++ <!-- Toast Container -->+ <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>+ </div>++ <script>+ const { createApp, ref, computed } = Vue;++ const app = createApp({+ setup() {+ const appElement = document.querySelector('#app');+ const recordingData = JSON.parse(appElement.dataset.recording);+ const recording = ref(recordingData);+ const activeTab = ref('transcription');+ const transcriptView = ref('simple');+ const audioPlayer = ref(null);+ const legendExpanded = ref(false);+ const isDarkMode = ref(document.documentElement.classList.contains('dark'));++ const processedTranscription = computed(() => {+ if (!recording.value?.transcription) {+ return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };+ }++ const transcription = recording.value.transcription;+ let transcriptionData;++ try {+ transcriptionData = JSON.parse(transcription);+ } catch (e) {+ transcriptionData = null;+ }++ if (transcriptionData && Array.isArray(transcriptionData)) {+ const wasDiarized = transcriptionData.some(segment => segment.speaker);++ if (!wasDiarized) {+ const segments = transcriptionData.map(segment => ({+ sentence: segment.sentence,+ startTime: segment.start_time,+ }));+ return {+ hasDialogue: false,+ isJson: true,+ content: segments.map(s => s.sentence).join('\n'),+ simpleSegments: segments,+ speakers: [],+ bubbleRows: []+ };+ }++ const speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];+ const speakerColors = {};+ speakers.forEach((speaker, index) => {+ speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;+ });++ const simpleSegments = transcriptionData.map(segment => ({+ speakerId: segment.speaker,+ speaker: segment.speaker,+ sentence: segment.sentence,+ startTime: segment.start_time || segment.startTime,+ endTime: segment.end_time || segment.endTime,+ color: speakerColors[segment.speaker] || 'speaker-color-1'+ }));++ const processedSimpleSegments = [];+ let lastSpeaker = null;+ simpleSegments.forEach(segment => {+ processedSimpleSegments.push({+ ...segment,+ showSpeaker: segment.speaker !== lastSpeaker+ });+ lastSpeaker = segment.speaker;+ });++ const bubbleRows = [];+ let lastBubbleSpeaker = null;+ simpleSegments.forEach(segment => {+ if (bubbleRows.length === 0 || segment.speaker !== lastBubbleSpeaker) {+ bubbleRows.push({+ speaker: segment.speaker,+ color: segment.color,+ isMe: segment.speaker && (typeof segment.speaker === 'string') && segment.speaker.toLowerCase().includes('me'),+ bubbles: []+ });+ lastBubbleSpeaker = segment.speaker;+ }+ bubbleRows[bubbleRows.length - 1].bubbles.push({+ sentence: segment.sentence,+ startTime: segment.startTime || segment.start_time,+ color: segment.color+ });+ });++ return {+ hasDialogue: true,+ isJson: true,+ segments: simpleSegments,+ simpleSegments: processedSimpleSegments,+ bubbleRows: bubbleRows,+ speakers: speakers.map(speaker => ({+ name: speaker,+ color: speakerColors[speaker]+ }))+ };+ }+ return { hasDialogue: false, content: transcription, speakers: [], simpleSegments: [], bubbleRows: [] };+ });++ function seekAudio(startTime) {+ if (startTime && audioPlayer.value) {+ audioPlayer.value.currentTime = parseFloat(startTime);+ audioPlayer.value.play();+ }+ }++ function handleTranscriptClick(event) {+ const startTime = event.target.dataset.startTime;+ if (startTime && audioPlayer.value) {+ audioPlayer.value.currentTime = parseFloat(startTime);+ audioPlayer.value.play();+ }+ }++ function copyTranscript() {+ let textToCopy = '';+ if (processedTranscription.value.isJson) {+ textToCopy = processedTranscription.value.segments.map(s => `[${s.speaker}]: ${s.sentence}`).join('\n');+ } else {+ textToCopy = recording.value.transcription;+ }+ navigator.clipboard.writeText(textToCopy).then(() => {+ showToast('Transcription copied to clipboard!');+ });+ }++ function copySummary() {+ navigator.clipboard.writeText(recording.value.summary).then(() => {+ showToast('Summary copied to clipboard!');+ });+ }++ function copyNotes() {+ navigator.clipboard.writeText(recording.value.notes).then(() => {+ showToast('Notes copied to clipboard!');+ });+ }++ function toggleDarkMode() {+ const newDarkMode = !isDarkMode.value;+ isDarkMode.value = newDarkMode;++ if (newDarkMode) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }++ localStorage.setItem('darkMode', newDarkMode.toString());+ }++ function showToast(message) {+ const container = document.getElementById('toastContainer');+ const toast = document.createElement('div');+ toast.className = 'toast bg-[var(--bg-success)] text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2';+ toast.innerHTML = `<i class="fas fa-check"></i>${message}`;++ container.appendChild(toast);++ // Trigger animation+ setTimeout(() => toast.classList.add('show'), 10);++ // Remove after 3 seconds+ setTimeout(() => {+ toast.classList.remove('show');+ setTimeout(() => container.removeChild(toast), 300);+ }, 3000);+ }++ return {+ recording,+ activeTab,+ transcriptView,+ audioPlayer,+ processedTranscription,+ legendExpanded,+ isDarkMode,+ seekAudio,+ handleTranscriptClick,+ copyTranscript,+ copySummary,+ copyNotes,+ toggleDarkMode+ };+ }+ });++ app.config.compilerOptions.delimiters = ['${', '}'];+ app.mount('#app');+ </script>+</body>+</html>diff --git a/test_json_fix.py b/test_json_fix.pynew file mode 100644index 00000000..be7645ae--- /dev/null+++ b/test_json_fix.py@@ -0,0 +1,58 @@+import json+import sys+import os++# Add the current directory to the path to import app+sys.path.append(os.path.dirname(os.path.abspath(__file__)))++from app import auto_close_json, safe_json_loads++def run_tests():+ """Runs a series of tests for the JSON fixing functions."""++ test_cases_auto_close = {+ "Unterminated string": ('{"title": "Test", "summary": "This is a test', '{"title": "Test", "summary": "This is a test"}'),+ "Missing closing brace": ('{"title": "Test", "summary": "This is a test"}', '{"title": "Test", "summary": "This is a test"}'),+ "Missing closing bracket": ('[{"item": 1}, {"item": 2}', '[{"item": 1}, {"item": 2}]'),+ "Nested unterminated": ('{"data": {"items": [1, 2', '{"data": {"items": [1, 2]}}'),+ "String at the end": ('{"key": "value', '{"key": "value"}'),+ "Empty string": ('', ''),+ "Already valid": ('{"a": 1}', '{"a": 1}'),+ "Complex nested object": ('{"a": {"b": {"c": [1, 2, {"d": "e' , '{"a": {"b": {"c": [1, 2, {"d": "e"}]}}}')+ }++ print("--- Testing auto_close_json ---")+ for name, (input_str, expected_str) in test_cases_auto_close.items():+ result = auto_close_json(input_str)+ print(f"Test: {name}")+ print(f" Input: '{input_str}'")+ print(f" Output: '{result}'")+ print(f" Expected: '{expected_str}'")+ assert result == expected_str, f"Failed: {name}"+ print(" Result: PASSED\n")++ test_cases_safe_loads = {+ "Unterminated string": '{"title": "Test", "summary": "This is a test',+ "Markdown with unterminated JSON": '```json\n{"title": "Test", "summary": "This is a test\n```',+ "Missing closing brace": '{"title": "Test", "summary": "This is a test"}',+ "Valid JSON": '{"title": "Complete", "summary": "This is a complete JSON."}',+ "JSON with escaped quotes": '{"title": "Escaped", "summary": "This is a \\"test\\" with quotes."}',+ "Invalid JSON": 'this is not json',+ }++ print("\n--- Testing safe_json_loads ---")+ for name, input_str in test_cases_safe_loads.items():+ result = safe_json_loads(input_str)+ print(f"Test: {name}")+ print(f" Input: '{input_str}'")+ print(f" Output: {result}")+ if name == "Invalid JSON":+ assert result is None, f"Failed: {name}"+ print(" Result: PASSED (Correctly returned None)\n")+ else:+ assert isinstance(result, dict), f"Failed: {name}"+ print(" Result: PASSED\n")++if __name__ == "__main__":+ run_tests()+ print("All tests completed successfully!")diff --git a/test_json_preprocessing.py b/test_json_preprocessing.pynew file mode 100644index 00000000..bb07cae7--- /dev/null+++ b/test_json_preprocessing.py@@ -0,0 +1,291 @@+#!/usr/bin/env python3+"""+Test suite for JSON preprocessing functionality in Speakr app.+Tests the safe_json_loads function with various malformed JSON scenarios.+"""++import sys+import os+import json+import unittest+from unittest.mock import Mock++# Add the app directory to the path so we can import from app.py+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++# Mock the Flask app and logger for testing+class MockApp:+ def __init__(self):+ self.logger = Mock()++# Set up the mock app before importing+app = MockApp()++# Import the functions we want to test+from app import safe_json_loads, preprocess_json_escapes, extract_json_object++class TestJSONPreprocessing(unittest.TestCase):+ """Test cases for JSON preprocessing functionality."""++ def test_valid_json(self):+ """Test that valid JSON is parsed correctly."""+ valid_json = '{"title": "Test Meeting", "summary": "This is a test summary"}'+ result = safe_json_loads(valid_json)+ expected = {"title": "Test Meeting", "summary": "This is a test summary"}+ self.assertEqual(result, expected)++ def test_json_with_markdown_code_blocks(self):+ """Test JSON wrapped in markdown code blocks."""+ markdown_json = '''```json+{+ "title": "Meeting Notes",+ "summary": "Key points discussed"+}+```'''+ result = safe_json_loads(markdown_json)+ expected = {"title": "Meeting Notes", "summary": "Key points discussed"}+ self.assertEqual(result, expected)++ def test_json_with_unescaped_quotes(self):+ """Test JSON with unescaped quotes in string values."""+ malformed_json = '{"title": "John said "Hello world" to everyone", "summary": "Meeting summary"}'+ result = safe_json_loads(malformed_json)+ expected = {"title": 'John said "Hello world" to everyone', "summary": "Meeting summary"}+ self.assertEqual(result, expected)++ def test_json_with_mixed_quotes(self):+ """Test JSON with mixed quote scenarios."""+ malformed_json = '{"title": "Alice\'s "big idea" presentation", "summary": "She said "this will change everything""}'+ result = safe_json_loads(malformed_json)+ self.assertIsInstance(result, dict)+ self.assertIn("title", result)+ self.assertIn("summary", result)++ def test_json_with_newlines_and_special_chars(self):+ """Test JSON with newlines and special characters."""+ malformed_json = '''{"title": "Complex Meeting", "summary": "Discussion about:\n- Point 1\n- Point 2 with "quotes"\n- Point 3"}'''+ result = safe_json_loads(malformed_json)+ self.assertIsInstance(result, dict)+ self.assertIn("title", result)+ self.assertIn("summary", result)++ def test_empty_or_invalid_input(self):+ """Test handling of empty or invalid input."""+ # Empty string+ result = safe_json_loads("", {"default": "value"})+ self.assertEqual(result, {"default": "value"})++ # None input+ result = safe_json_loads(None, {"default": "value"})+ self.assertEqual(result, {"default": "value"})++ # Non-string input+ result = safe_json_loads(123, {"default": "value"})+ self.assertEqual(result, {"default": "value"})++ def test_completely_malformed_json(self):+ """Test completely malformed JSON that can't be fixed."""+ malformed_json = '{"title": "Test", "summary": unclosed string and missing quotes}'+ result = safe_json_loads(malformed_json, {"error": "fallback"})+ self.assertEqual(result, {"error": "fallback"})++ def test_json_with_nested_quotes(self):+ """Test JSON with deeply nested quote scenarios."""+ malformed_json = '{"title": "Meeting about "Project Alpha" and "Project Beta"", "summary": "Both projects involve "cutting-edge" technology"}'+ result = safe_json_loads(malformed_json)+ self.assertIsInstance(result, dict)+ # Should have successfully parsed something+ self.assertTrue(len(result) > 0)++ def test_json_array_format(self):+ """Test JSON array format (for transcription data)."""+ json_array = '[{"speaker": "John", "sentence": "Hello everyone"}, {"speaker": "Jane", "sentence": "Good morning"}]'+ result = safe_json_loads(json_array)+ expected = [{"speaker": "John", "sentence": "Hello everyone"}, {"speaker": "Jane", "sentence": "Good morning"}]+ self.assertEqual(result, expected)++ def test_preprocess_json_escapes_function(self):+ """Test the preprocess_json_escapes function directly."""+ input_json = '{"title": "John said "Hello" to Mary", "summary": "Simple test"}'+ processed = preprocess_json_escapes(input_json)+ # Should be valid JSON after preprocessing+ result = json.loads(processed)+ self.assertIsInstance(result, dict)+ self.assertIn("title", result)+ self.assertIn("summary", result)++ def test_extract_json_object_function(self):+ """Test the extract_json_object function directly."""+ # Test with extra text around JSON object+ text_with_json = 'Here is some text {"title": "Test", "summary": "Content"} and more text'+ extracted = extract_json_object(text_with_json)+ result = json.loads(extracted)+ expected = {"title": "Test", "summary": "Content"}+ self.assertEqual(result, expected)++ # Test with JSON array+ text_with_array = 'Some text [{"item": "one"}, {"item": "two"}] more text'+ extracted = extract_json_object(text_with_array)+ result = json.loads(extracted)+ expected = [{"item": "one"}, {"item": "two"}]+ self.assertEqual(result, expected)++ def test_real_world_llm_response_scenarios(self):+ """Test real-world scenarios that might come from LLM responses."""++ # Scenario 1: LLM response with explanation text+ llm_response1 = '''Here's the JSON response you requested:++```json+{+ "title": "Q3 Planning Meeting",+ "summary": "We discussed the "new initiative" and John's "breakthrough idea" for next quarter."+}+```++This should help with your transcription needs.'''++ result1 = safe_json_loads(llm_response1)+ self.assertIsInstance(result1, dict)+ self.assertIn("title", result1)+ self.assertIn("summary", result1)++ # Scenario 2: LLM response with unescaped quotes and no code blocks+ llm_response2 = '{"title": "Team Standup", "summary": "Alice mentioned "the deadline is tight" and Bob said "we need more resources""}'++ result2 = safe_json_loads(llm_response2)+ self.assertIsInstance(result2, dict)+ self.assertIn("title", result2)+ self.assertIn("summary", result2)++ # Scenario 3: LLM response with speaker identification+ llm_response3 = '''{"SPEAKER_00": "John Smith", "SPEAKER_01": "Jane "The Expert" Doe", "SPEAKER_02": "Bob"}'''++ result3 = safe_json_loads(llm_response3)+ self.assertIsInstance(result3, dict)+ self.assertTrue(len(result3) >= 2) # Should have parsed at least some speakers++ def test_fallback_strategies(self):+ """Test that different parsing strategies work as fallbacks."""++ # Test ast.literal_eval fallback for simple cases+ simple_dict = "{'title': 'Simple', 'summary': 'Test'}"+ result = safe_json_loads(simple_dict)+ expected = {"title": "Simple", "summary": "Test"}+ self.assertEqual(result, expected)++ # Test regex extraction fallback+ messy_response = 'Some text before {"title": "Extracted", "summary": "From regex"} some text after'+ result = safe_json_loads(messy_response)+ expected = {"title": "Extracted", "summary": "From regex"}+ self.assertEqual(result, expected)++ def test_performance_with_large_content(self):+ """Test performance with larger JSON content."""+ large_summary = "This is a very long summary. " * 100 # Create a long string+ large_json = f'{{"title": "Large Content Test", "summary": "{large_summary}"}}'++ result = safe_json_loads(large_json)+ self.assertIsInstance(result, dict)+ self.assertIn("title", result)+ self.assertIn("summary", result)+ self.assertEqual(result["title"], "Large Content Test")++def run_comprehensive_test():+ """Run a comprehensive test with various malformed JSON examples."""+ print("🧪 Running comprehensive JSON preprocessing tests...\n")++ test_cases = [+ {+ "name": "Valid JSON",+ "input": '{"title": "Test", "summary": "Valid JSON"}',+ "should_succeed": True+ },+ {+ "name": "Unescaped quotes in title",+ "input": '{"title": "Meeting about "Project X"", "summary": "Discussion summary"}',+ "should_succeed": True+ },+ {+ "name": "Multiple unescaped quotes",+ "input": '{"title": "John said "Hello" and Mary replied "Hi there"", "summary": "Conversation log"}',+ "should_succeed": True+ },+ {+ "name": "Markdown code block",+ "input": '```json\n{"title": "Wrapped", "summary": "In code block"}\n```',+ "should_succeed": True+ },+ {+ "name": "Mixed quotes and apostrophes",+ "input": '{"title": "Alice\'s "big idea" presentation", "summary": "She said it\'s "revolutionary""}',+ "should_succeed": True+ },+ {+ "name": "JSON with newlines",+ "input": '{"title": "Multi-line", "summary": "Line 1\\nLine 2 with \\"quotes\\"\\nLine 3"}',+ "should_succeed": True+ },+ {+ "name": "Completely malformed",+ "input": '{"title": "Test", "summary": this is not valid json at all}',+ "should_succeed": False+ },+ {+ "name": "Empty string",+ "input": "",+ "should_succeed": False+ }+ ]++ passed = 0+ failed = 0++ for i, test_case in enumerate(test_cases, 1):+ print(f"Test {i}: {test_case['name']}")+ print(f"Input: {test_case['input'][:100]}{'...' if len(test_case['input']) > 100 else ''}")++ try:+ result = safe_json_loads(test_case['input'], {"error": "fallback"})++ if test_case['should_succeed']:+ if result != {"error": "fallback"} and isinstance(result, dict):+ print("✅ PASSED - Successfully parsed JSON")+ passed += 1+ else:+ print("❌ FAILED - Expected successful parsing but got fallback")+ failed += 1+ else:+ if result == {"error": "fallback"}:+ print("✅ PASSED - Correctly returned fallback for malformed JSON")+ passed += 1+ else:+ print("❌ FAILED - Expected fallback but got parsed result")+ failed += 1++ except Exception as e:+ print(f"❌ FAILED - Exception occurred: {e}")+ failed += 1++ print("-" * 50)++ print(f"\n📊 Test Results: {passed} passed, {failed} failed")+ return failed == 0++if __name__ == "__main__":+ print("🚀 Starting JSON Preprocessing Tests for Speakr App\n")++ # Run the comprehensive manual test+ manual_success = run_comprehensive_test()++ print("\n" + "="*60)+ print("🔬 Running Unit Tests")+ print("="*60)++ # Run the unit tests+ unittest.main(argv=[''], exit=False, verbosity=2)++ if manual_success:+ print("\n🎉 All tests completed! JSON preprocessing should handle LLM response issues gracefully.")+ else:+ print("\n⚠️ Some tests failed. Please review the implementation.")diff --git a/test_json_standalone.py b/test_json_standalone.pynew file mode 100644index 00000000..c08827bd--- /dev/null+++ b/test_json_standalone.py@@ -0,0 +1,340 @@+#!/usr/bin/env python3+"""+Standalone test for JSON preprocessing functionality.+Tests the safe_json_loads function with various malformed JSON scenarios.+"""++import json+import re+import ast+from unittest.mock import Mock++# Mock logger for testing+class MockLogger:+ def warning(self, msg): print(f"WARNING: {msg}")+ def info(self, msg): print(f"INFO: {msg}")+ def debug(self, msg): print(f"DEBUG: {msg}")+ def error(self, msg): print(f"ERROR: {msg}")++# Create mock app with logger+class MockApp:+ logger = MockLogger()++app = MockApp()++def safe_json_loads(json_string, fallback_value=None):+ """+ Safely parse JSON with preprocessing to handle common LLM JSON formatting issues.++ Args:+ json_string (str): The JSON string to parse+ fallback_value: Value to return if parsing fails (default: None)++ Returns:+ Parsed JSON object or fallback_value if parsing fails+ """+ if not json_string or not isinstance(json_string, str):+ app.logger.warning(f"Invalid JSON input: {type(json_string)} - {json_string}")+ return fallback_value++ # Step 1: Clean the input string+ cleaned_json = json_string.strip()++ # Step 2: Extract JSON from markdown code blocks if present+ json_match = re.search(r'```(?:json)?\s*(.*?)\s*```', cleaned_json, re.DOTALL)+ if json_match:+ cleaned_json = json_match.group(1).strip()++ # Step 3: Try multiple parsing strategies+ parsing_strategies = [+ # Strategy 1: Direct parsing (for well-formed JSON)+ lambda x: json.loads(x),++ # Strategy 2: Fix common escape issues+ lambda x: json.loads(preprocess_json_escapes(x)),++ # Strategy 3: Use ast.literal_eval as fallback for simple cases+ lambda x: ast.literal_eval(x) if x.startswith(('{', '[')) else None,++ # Strategy 4: Extract JSON object/array using regex+ lambda x: json.loads(extract_json_object(x)),+ ]++ for i, strategy in enumerate(parsing_strategies):+ try:+ result = strategy(cleaned_json)+ if result is not None:+ if i > 0: # Log if we had to use a fallback strategy+ app.logger.info(f"JSON parsed successfully using strategy {i+1}")+ return result+ except (json.JSONDecodeError, ValueError, SyntaxError) as e:+ if i == 0: # Only log the first failure to avoid spam+ app.logger.debug(f"JSON parsing strategy {i+1} failed: {e}")+ continue++ # All strategies failed+ app.logger.error(f"All JSON parsing strategies failed for: {cleaned_json[:200]}...")+ return fallback_value++def preprocess_json_escapes(json_string):+ """+ Preprocess JSON string to fix common escape issues from LLM responses.+ Uses a more sophisticated approach to handle nested quotes properly.+ """+ if not json_string:+ return json_string++ result = []+ i = 0+ in_string = False+ escape_next = False+ expecting_value = False # Track if we're expecting a value (after :)++ while i < len(json_string):+ char = json_string[i]++ if escape_next:+ # This character is escaped, add it as-is+ result.append(char)+ escape_next = False+ elif char == '\\':+ # This is an escape character+ result.append(char)+ escape_next = True+ elif char == ':' and not in_string:+ # We found a colon, next string will be a value+ result.append(char)+ expecting_value = True+ elif char == ',' and not in_string:+ # We found a comma, reset expecting_value+ result.append(char)+ expecting_value = False+ elif char == '"':+ if not in_string:+ # Starting a string+ in_string = True+ result.append(char)+ else:+ # We're in a string, check if this quote should be escaped+ # Look ahead to see if this is the end of the string value+ j = i + 1+ while j < len(json_string) and json_string[j].isspace():+ j += 1++ # For keys (not expecting_value), only end on colon+ # For values (expecting_value), end on comma, closing brace, or closing bracket+ if expecting_value:+ end_chars = ',}]'+ else:+ end_chars = ':'++ if j < len(json_string) and json_string[j] in end_chars:+ # This is the end of the string+ in_string = False+ result.append(char)+ if not expecting_value:+ # We just finished a key, next will be expecting value+ expecting_value = True+ else:+ # This is an inner quote that should be escaped+ result.append('\\"')+ else:+ result.append(char)++ i += 1++ return ''.join(result)++def extract_json_object(text):+ """+ Extract the first complete JSON object or array from text using regex.+ """+ # Look for JSON object+ obj_match = re.search(r'\{.*\}', text, re.DOTALL)+ if obj_match:+ return obj_match.group(0)++ # Look for JSON array+ arr_match = re.search(r'\[.*\]', text, re.DOTALL)+ if arr_match:+ return arr_match.group(0)++ # Return original if no JSON structure found+ return text++def run_comprehensive_test():+ """Run a comprehensive test with various malformed JSON examples."""+ print("🧪 Running comprehensive JSON preprocessing tests...\n")++ test_cases = [+ {+ "name": "Valid JSON",+ "input": '{"title": "Test", "summary": "Valid JSON"}',+ "should_succeed": True+ },+ {+ "name": "Unescaped quotes in title",+ "input": '{"title": "Meeting about "Project X"", "summary": "Discussion summary"}',+ "should_succeed": True+ },+ {+ "name": "Multiple unescaped quotes",+ "input": '{"title": "John said "Hello" and Mary replied "Hi there"", "summary": "Conversation log"}',+ "should_succeed": True+ },+ {+ "name": "Markdown code block",+ "input": '```json\n{"title": "Wrapped", "summary": "In code block"}\n```',+ "should_succeed": True+ },+ {+ "name": "Mixed quotes and apostrophes",+ "input": '{"title": "Alice\'s "big idea" presentation", "summary": "She said it\'s "revolutionary""}',+ "should_succeed": True+ },+ {+ "name": "JSON with newlines",+ "input": '{"title": "Multi-line", "summary": "Line 1\\nLine 2 with \\"quotes\\"\\nLine 3"}',+ "should_succeed": True+ },+ {+ "name": "LLM response with explanation",+ "input": '''Here's the JSON:+```json+{+ "title": "Q3 Planning",+ "summary": "We discussed the "new initiative" for next quarter."+}+```+Hope this helps!''',+ "should_succeed": True+ },+ {+ "name": "Speaker identification with quotes",+ "input": '{"SPEAKER_00": "John Smith", "SPEAKER_01": "Jane "The Expert" Doe", "SPEAKER_02": "Bob"}',+ "should_succeed": True+ },+ {+ "name": "Completely malformed",+ "input": '{"title": "Test", "summary": this is not valid json at all}',+ "should_succeed": False+ },+ {+ "name": "Empty string",+ "input": "",+ "should_succeed": False+ }+ ]++ passed = 0+ failed = 0++ for i, test_case in enumerate(test_cases, 1):+ print(f"Test {i}: {test_case['name']}")+ print(f"Input: {test_case['input'][:100]}{'...' if len(test_case['input']) > 100 else ''}")++ try:+ result = safe_json_loads(test_case['input'], {"error": "fallback"})++ if test_case['should_succeed']:+ if result != {"error": "fallback"} and isinstance(result, (dict, list)):+ print("✅ PASSED - Successfully parsed JSON")+ print(f" Result: {result}")+ passed += 1+ else:+ print("❌ FAILED - Expected successful parsing but got fallback")+ failed += 1+ else:+ if result == {"error": "fallback"}:+ print("✅ PASSED - Correctly returned fallback for malformed JSON")+ passed += 1+ else:+ print("❌ FAILED - Expected fallback but got parsed result")+ print(f" Unexpected result: {result}")+ failed += 1++ except Exception as e:+ print(f"❌ FAILED - Exception occurred: {e}")+ failed += 1++ print("-" * 50)++ print(f"\n📊 Test Results: {passed} passed, {failed} failed")+ return failed == 0++def test_preprocessing_function():+ """Test the preprocessing function directly."""+ print("\n🔧 Testing preprocessing function directly...\n")++ test_input = '{"title": "Meeting about "Project X"", "summary": "Discussion summary"}'+ print(f"Original: {test_input}")++ processed = preprocess_json_escapes(test_input)+ print(f"Processed: {processed}")++ try:+ result = json.loads(processed)+ print(f"✅ Successfully parsed: {result}")+ except json.JSONDecodeError as e:+ print(f"❌ Still failed: {e}")++def test_specific_scenarios():+ """Test specific real-world scenarios."""+ print("\n🎯 Testing specific LLM response scenarios...\n")++ # Test case from the original issue+ gemini_response = '''{"title": "Meeting about "Project Phoenix" and budget allocation", "summary": "The team discussed John's "breakthrough idea" and Mary said "this will change everything" during the Q3 planning session."}'''++ print("Testing Gemini-style response with unescaped quotes:")+ print(f"Input: {gemini_response}")++ # Test preprocessing directly+ processed = preprocess_json_escapes(gemini_response)+ print(f"Processed: {processed}")++ result = safe_json_loads(gemini_response)+ if isinstance(result, dict) and "title" in result and "summary" in result:+ print("✅ SUCCESS - Parsed Gemini response correctly!")+ print(f"Title: {result['title']}")+ print(f"Summary: {result['summary'][:100]}...")+ else:+ print("❌ FAILED - Could not parse Gemini response")+ print(f"Result: {result}")++ print("-" * 50)++ # Test speaker identification scenario+ speaker_response = '''{"SPEAKER_00": "John "The Manager" Smith", "SPEAKER_01": "Alice Johnson", "SPEAKER_02": "Bob "Tech Lead" Wilson"}'''++ print("Testing speaker identification with quotes in names:")+ print(f"Input: {speaker_response}")++ # Test preprocessing directly+ processed = preprocess_json_escapes(speaker_response)+ print(f"Processed: {processed}")++ result = safe_json_loads(speaker_response)+ if isinstance(result, dict) and len(result) >= 3:+ print("✅ SUCCESS - Parsed speaker identification correctly!")+ for speaker, name in result.items():+ print(f" {speaker}: {name}")+ else:+ print("❌ FAILED - Could not parse speaker identification")+ print(f"Result: {result}")++if __name__ == "__main__":+ print("🚀 Starting Standalone JSON Preprocessing Tests\n")++ # Test preprocessing function directly+ test_preprocessing_function()++ # Run the comprehensive test+ success = run_comprehensive_test()++ # Test specific scenarios+ test_specific_scenarios()++ if success:+ print("\n🎉 All tests completed successfully! JSON preprocessing should handle LLM response issues gracefully.")+ else:+ print("\n⚠️ Some tests failed. The implementation may need refinement.")