Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add video retention, configurable concurrent uploads, and v0.8.11-alpha docs
Murtaza Nasire32618589cae
diff --git a/README.md b/README.mdindex 7fa24f83..388eeafe 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@<a href="https://www.gnu.org/licenses/agpl-3.0"><img alt="AGPL v3" src="https://img.shields.io/badge/License-AGPL_v3-blue.svg"></a><a href="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml"><img alt="Docker Build" src="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml/badge.svg"></a><a href="https://hub.docker.com/r/learnedmachine/speakr"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/learnedmachine/speakr"></a>- <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.8.8-brightgreen.svg"></a>+ <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.8.11--alpha-brightgreen.svg"></a></p><p align="center">@@ -162,7 +162,20 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:- [Troubleshooting](https://murtaza-nasir.github.io/speakr/troubleshooting) - Common issues and solutions- [FAQ](https://murtaza-nasir.github.io/speakr/faq) - Frequently asked questions-## Latest Release (v0.8.8)+## Latest Release (v0.8.11-alpha)++**Video Retention, Parallel Uploads & Duplicate Detection**++- **Video Retention** - New `VIDEO_RETENTION=true` option preserves video streams for in-browser playback. When enabled, uploaded video files keep their video track and render with a native `<video>` player alongside the transcript. Audio is extracted to a temp file for transcription and cleaned up automatically. HTTP Range requests enable seeking without downloading the full file.+- **Parallel Uploads** - Multiple files upload concurrently with individual progress bars, making batch uploads significantly faster. Configurable via `MAX_CONCURRENT_UPLOADS` (default: 3)+- **Duplicate Detection** - SHA-256 file hashing detects duplicate uploads with warning toasts and a clickable copies indicator in the sidebar and header+- **Volume Controls** - Volume slider popups and mute visual indicators on all audio/video players+- **Speaker Enhancements** - Split button UI, apply suggested names, name sanitization, JSON schema option, new speaker API endpoints+- **Localization** - Complete translations for folders, API tokens, recording recovery, events, and speakers management++**Bug Fixes** - ASR_DIARIZE=false being ignored, bulk delete cascade, file monitor stability, speaker snippet creation, null transcription bug, clean_llm_response being too aggressive++### Previous Release (v0.8.8)**Lightweight Docker Image**@@ -334,6 +347,8 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:- ✅ Token usage tracking and per-user budgets (v0.7.2)- ✅ Connector-based transcription architecture with auto-detection (v0.8.0)- ✅ Comprehensive REST API with Swagger UI documentation (v0.8.0)+- ✅ Video retention with in-browser video playback (v0.8.11)+- ✅ Parallel uploads with duplicate detection (v0.8.11)### Near-term- Quick language switching for transcriptiondiff --git a/VERSION b/VERSIONindex d761d3e2..9e4993ed 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-v0.8.9-alpha+v0.8.11-alphadiff --git a/config/env.asr.example b/config/env.asr.exampleindex 4b81276e..2a437626 100644--- a/config/env.asr.example+++ b/config/env.asr.example@@ -228,6 +228,16 @@ ENABLE_INCOGNITO_MODE=false# Make incognito mode the default for in-app recordings (toggle starts ON)INCOGNITO_MODE_DEFAULT=false+# --- Video Retention ---+# When enabled, uploaded video files keep their video stream for in-browser playback+# The audio is extracted to a temp file for transcription, then cleaned up+# Default: false (video uploads extract audio only, video stream is discarded)+VIDEO_RETENTION=false++# --- Concurrent Uploads ---+# Maximum number of simultaneous file uploads (default: 3)+MAX_CONCURRENT_UPLOADS=3+# --- Background Processing Queues ---# Separate queues for transcription (slow) and summary (fast) jobs# This prevents slow ASR jobs from blocking quick summary generationdiff --git a/config/env.transcription.example b/config/env.transcription.exampleindex 5fb40286..01edea8c 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -235,6 +235,16 @@ USERS_CAN_DELETE=true# should not outlive the recordings it was derived from.# DELETE_ORPHANED_SPEAKERS=false+# --- Video Retention ---+# When enabled, uploaded video files keep their video stream for in-browser playback+# The audio is extracted to a temp file for transcription, then cleaned up+# Default: false (video uploads extract audio only, video stream is discarded)+VIDEO_RETENTION=false++# --- Concurrent Uploads ---+# Maximum number of simultaneous file uploads (default: 3)+MAX_CONCURRENT_UPLOADS=3+# =============================================================================# BACKGROUND PROCESSING# =============================================================================diff --git a/config/env.whisper.example b/config/env.whisper.exampleindex 790e4739..79a51f05 100644--- a/config/env.whisper.example+++ b/config/env.whisper.example@@ -225,6 +225,16 @@ ENABLE_INCOGNITO_MODE=false# Make incognito mode the default for in-app recordings (toggle starts ON)INCOGNITO_MODE_DEFAULT=false+# --- Video Retention ---+# When enabled, uploaded video files keep their video stream for in-browser playback+# The audio is extracted to a temp file for transcription, then cleaned up+# Default: false (video uploads extract audio only, video stream is discarded)+VIDEO_RETENTION=false++# --- Concurrent Uploads ---+# Maximum number of simultaneous file uploads (default: 3)+MAX_CONCURRENT_UPLOADS=3+# --- Background Processing Queues ---# Separate queues for transcription (slow) and summary (fast) jobs# This prevents slow ASR jobs from blocking quick summary generationdiff --git a/config/env.whisperx.example b/config/env.whisperx.exampleindex b0a564e1..2198be8b 100644--- a/config/env.whisperx.example+++ b/config/env.whisperx.example@@ -210,6 +210,16 @@ ENABLE_PUBLIC_SHARING=true# Note: Admins can control public sharing permissions per-user in the admin dashboard# even when ENABLE_PUBLIC_SHARING is true+# --- Video Retention ---+# When enabled, uploaded video files keep their video stream for in-browser playback+# The audio is extracted to a temp file for transcription, then cleaned up+# Default: false (video uploads extract audio only, video stream is discarded)+VIDEO_RETENTION=false++# --- Concurrent Uploads ---+# Maximum number of simultaneous file uploads (default: 3)+MAX_CONCURRENT_UPLOADS=3+# --- Background Processing Queues ---# Separate queues for transcription (slow) and summary (fast) jobs# This prevents slow ASR jobs from blocking quick summary generationdiff --git a/docs/admin-guide/system-settings.md b/docs/admin-guide/system-settings.mdindex a7ed9775..055028f9 100644--- a/docs/admin-guide/system-settings.md+++ b/docs/admin-guide/system-settings.md@@ -125,6 +125,14 @@ Jobs are persisted to the database and survive application restarts. If Speakr r**SKIP_EMAIL_DOMAIN_CHECK**: When `true`, bypasses DNS validation of email domains when creating admin users via the setup script. Useful for development or when DNS lookups are restricted. Default: `false`.+### Video Retention++**VIDEO_RETENTION**: When enabled, uploaded video files keep their video stream for in-browser playback instead of extracting audio and discarding the video. The audio is extracted to a temporary file for transcription only, then cleaned up after processing. The video renders with a native `<video>` player alongside the transcript, with full seeking support via HTTP Range requests. All player controls (play/pause, seek, speed, volume) work identically. Ideal for presentations, lectures, and screen recordings. Default: `false`.++### Concurrent Uploads++**MAX_CONCURRENT_UPLOADS**: Controls how many files can be uploaded simultaneously when batch uploading. Higher values speed up batch uploads but use more bandwidth and server resources. Default: `3`.+### Audio CompressionSpeakr can automatically compress lossless audio uploads (WAV, AIFF) to save storage space. This happens transparently on upload - the original file is replaced with the compressed version.@@ -162,6 +170,12 @@ AUDIO_COMPRESS_UPLOADS=trueAUDIO_CODEC=mp3AUDIO_BITRATE=128k+# Video retention (keep video files for playback)+VIDEO_RETENTION=false++# Concurrent uploads (default: 3)+MAX_CONCURRENT_UPLOADS=3+# Processing queueJOB_QUEUE_WORKERS=2JOB_MAX_RETRIES=3diff --git a/docs/features.md b/docs/features.mdindex 5b5dbc1a..e746bd45 100644--- a/docs/features.md+++ b/docs/features.md@@ -209,9 +209,13 @@ Install Speakr as a progressive web app for a native-like experience on any deviReduce eye strain with a full dark mode implementation that affects every interface element. The theme preference persists across sessions and devices, automatically applying your choice whenever you log in.+### Video Retention++When enabled (`VIDEO_RETENTION=true`), uploaded video files preserve their video stream for in-browser playback. Instead of extracting audio and discarding the video, Speakr keeps the original file and renders it with a native `<video>` player alongside the transcript. Audio is extracted to a temporary file for transcription only, then cleaned up automatically. All existing player controls (play/pause, seek, speed, volume) work identically with video since HTML5 `<video>` and `<audio>` share the same media API. HTTP Range requests enable efficient seeking without downloading the entire file. This feature is ideal for presentations, lectures, and screen recordings where the visual context adds value to the transcript. Default: `false` (current behavior preserved — video uploads extract audio only).+### Playback Speed Control-Adjust audio playback speed from 0.5x to 3x on all audio players throughout the application. This is useful for quickly reviewing long recordings or slowing down complex content. Your speed preference is saved to localStorage and persists across sessions.+Adjust audio playback speed from 0.5x to 3x on all audio/video players throughout the application. This is useful for quickly reviewing long recordings or slowing down complex content. Your speed preference is saved to localStorage and persists across sessions.### Incognito Modediff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.mdindex b8737cdd..1c37ac8c 100644--- a/docs/getting-started/installation.md+++ b/docs/getting-started/installation.md@@ -286,6 +286,26 @@ Supported codecs by default: `pcm_s16le`, `pcm_s24le`, `pcm_f32le`, `mp3`, `flac!!! tip "Storage Savings Example"A 500MB WAV recording compressed to MP3 at 128k becomes roughly 50MB - a 90% reduction. For lossless preservation, FLAC typically achieves 50-70% reduction while maintaining perfect audio quality.+#### Video Retention++By default, when users upload video files, Speakr extracts the audio and discards the video stream. If you want to preserve video for in-browser playback alongside the transcript, enable video retention:++```bash+VIDEO_RETENTION=true+```++When enabled, the original video file is kept and served with a native `<video>` player. Audio is extracted to a temporary file for transcription only, then cleaned up automatically. All player controls (seek, speed, volume) work identically. This is particularly useful for presentations, lectures, and screen recordings where the visual context adds value. Storage overhead is modest — video streams are typically only 10-20% of the total file size for presentation-style content.++#### Concurrent Upload Limit++Control how many files upload simultaneously when batch uploading:++```bash+MAX_CONCURRENT_UPLOADS=3 # default+```++Higher values speed up batch uploads but use more bandwidth and server resources.+#### Inquire Mode for Semantic SearchInquire Mode transforms Speakr from a simple transcription tool into a knowledge base of all your recordings. When enabled, you can search across all your transcriptions using natural language questions:diff --git a/docs/index.md b/docs/index.mdindex e4293159..c87c7095 100644--- a/docs/index.md+++ b/docs/index.md@@ -6,15 +6,14 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,<img src="assets/images/screenshots/Main view.png" alt="Main Interface" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);"></div>-!!! info "Latest Release: v0.8.6 - Folders & Automation"- **Organize recordings into folders with custom prompts, auto speaker labeling, and per-user auto-summarization**+!!! info "Latest Release: v0.8.11-alpha - Video Retention, Parallel Uploads & Duplicate Detection"+ **Video playback, concurrent uploads, and file deduplication**- - **Folders Organization** - Group recordings into folders with custom prompts and ASR settings per folder- - **Auto Speaker Labeling** - Automatic speaker identification using voice embedding matching- - **Per-User Auto-Summarization** - User-configurable automatic summary generation- - **Azure OpenAI Connector** - Experimental transcription connector (community testing welcome)-- See the [v0.8.0 release notes](#version-080) for the full connector architecture and REST API features.+ - **Video Retention** - Keep video streams for in-browser `<video>` playback alongside transcripts (`VIDEO_RETENTION=true`)+ - **Parallel Uploads** - Batch uploads run concurrently with individual progress bars (`MAX_CONCURRENT_UPLOADS`, default: 3)+ - **Duplicate Detection** - SHA-256 hashing warns on duplicate uploads with clickable copies indicator+ - **Volume Controls** - Volume slider popups and mute indicators on all players+ - **Speaker Enhancements** - Split button UI, apply suggested names, new speaker API endpoints## Quick Navigation@@ -147,6 +146,15 @@ Learn more about [audio synchronization features](user-guide/transcripts.md#audi## Latest Updates+!!! info "Version 0.8.11-alpha - Video Retention, Parallel Uploads & Duplicate Detection"+ - **Video Retention** - New `VIDEO_RETENTION=true` option preserves video streams for in-browser playback with native `<video>` player, HTTP Range seeking, and automatic temp audio cleanup+ - **Parallel Uploads** - Concurrent uploads with individual progress bars for faster batch processing (`MAX_CONCURRENT_UPLOADS`, default: 3)+ - **Duplicate Detection** - SHA-256 file hashing with warning toasts and clickable copies indicator in sidebar/header+ - **Volume Controls** - Volume slider popups and mute visual indicators on all audio/video players+ - **Speaker Enhancements** - Split button UI, apply suggested names, name sanitization, JSON schema option, new speaker API endpoints+ - **Localization** - Complete translations for folders, API tokens, recording recovery, events, and speakers management+ - **Bug Fixes** - ASR_DIARIZE=false ignored, bulk delete cascade, file monitor stability, speaker snippets, null transcription, clean_llm_response too aggressive+!!! info "Version 0.8.7 - Export Templates & Localization"- **Customizable Export Templates** - Create markdown templates for exports with variables (`{{title}}`, `{{summary}}`, `{{notes}}`) and conditionals for optional sections- **Localized Labels** - Use `{{label.metadata}}`, `{{label.summary}}` etc. for automatically translated labels based on user's UI languagediff --git a/src/api/recordings.py b/src/api/recordings.pyindex 574ce457..97cdda98 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -48,6 +48,7 @@ ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() =DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording') # 'audio_only' or 'full_recording'USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'+VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'@@ -1950,31 +1951,36 @@ def upload_file():current_app.logger.warning(f"Failed to probe {original_filename}: {e}. Will attempt conversion.")codec_info = None- # Use shared conversion utility - handles ALL conversion needs (codec conversion + compression)- try:- result = convert_if_needed(- filepath,- original_filename=original_filename,- codec_info=codec_info,- needs_chunking=needs_chunking_for_processing,- is_asr_endpoint=USE_ASR_ENDPOINT,- delete_original=True,- connector_specs=connector_specs # Pass connector specs for codec restrictions- )- filepath = result.output_path-- # Log what happened- if result.was_converted:- current_app.logger.info(f"File converted: {result.original_codec} -> {result.final_codec}")- if result.was_compressed:- current_app.logger.info(f"File compressed: {result.size_reduction_percent:.1f}% size reduction")-- except FFmpegNotFoundError as e:- current_app.logger.error(f"FFmpeg not found: {e}")- return jsonify({'error': 'Audio conversion tool (FFmpeg) not found on server.'}), 500- except FFmpegError as e:- current_app.logger.error(f"FFmpeg conversion failed for {filepath}: {e}")- return jsonify({'error': f'Failed to convert audio file: {str(e)}'}), 500+ # Video retention: skip conversion for videos, processing pipeline handles extraction+ has_video = codec_info.get('has_video', False) if codec_info else False+ if VIDEO_RETENTION and has_video:+ current_app.logger.info(f"Video retention: keeping original video, skipping conversion")+ else:+ # Use shared conversion utility - handles ALL conversion needs (codec conversion + compression)+ try:+ result = convert_if_needed(+ filepath,+ original_filename=original_filename,+ codec_info=codec_info,+ needs_chunking=needs_chunking_for_processing,+ is_asr_endpoint=USE_ASR_ENDPOINT,+ delete_original=True,+ connector_specs=connector_specs # Pass connector specs for codec restrictions+ )+ filepath = result.output_path++ # Log what happened+ if result.was_converted:+ current_app.logger.info(f"File converted: {result.original_codec} -> {result.final_codec}")+ if result.was_compressed:+ current_app.logger.info(f"File compressed: {result.size_reduction_percent:.1f}% size reduction")++ except FFmpegNotFoundError as e:+ current_app.logger.error(f"FFmpeg not found: {e}")+ return jsonify({'error': 'Audio conversion tool (FFmpeg) not found on server.'}), 500+ except FFmpegError as e:+ current_app.logger.error(f"FFmpeg conversion failed for {filepath}: {e}")+ return jsonify({'error': f'Failed to convert audio file: {str(e)}'}), 500# Get final file size (of original or converted file)final_file_size = os.path.getsize(filepath)@@ -3017,9 +3023,9 @@ def get_audio(recording_id):filename = "".join(c for c in filename if c.isalnum() or c in (' ', '-', '_')).strip()ext = os.path.splitext(recording.audio_path)[1] or '.mp3'filename = f"{filename}{ext}"- return send_file(recording.audio_path, as_attachment=True, download_name=filename)+ return send_file(recording.audio_path, as_attachment=True, download_name=filename, mimetype=recording.mime_type, conditional=True)- return send_file(recording.audio_path)+ return send_file(recording.audio_path, mimetype=recording.mime_type, conditional=True)except Exception as e:current_app.logger.error(f"Error serving audio for recording {recording_id}: {e}", exc_info=True)return jsonify({'error': 'An unexpected error occurred.'}), 500diff --git a/src/api/shares.py b/src/api/shares.pyindex 50f88af5..010dca1f 100644--- a/src/api/shares.py+++ b/src/api/shares.py@@ -159,7 +159,7 @@ def get_shared_audio(public_id):if not os.path.exists(recording.audio_path):current_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)+ return send_file(recording.audio_path, conditional=True)except Exception as e:current_app.logger.error(f"Error serving shared audio for public_id {public_id}: {e}", exc_info=True)return jsonify({'error': 'An unexpected error occurred.'}), 500diff --git a/src/api/system.py b/src/api/system.pyindex aee3d2db..5a2fe87c 100644--- a/src/api/system.py+++ b/src/api/system.py@@ -35,6 +35,8 @@ SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() =ENABLE_AUTO_EXPORT = os.environ.get('ENABLE_AUTO_EXPORT', 'false').lower() == 'true'ENABLE_INCOGNITO_MODE = os.environ.get('ENABLE_INCOGNITO_MODE', 'false').lower() == 'true'INCOGNITO_MODE_DEFAULT = os.environ.get('INCOGNITO_MODE_DEFAULT', 'false').lower() == 'true'+VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'+MAX_CONCURRENT_UPLOADS = int(os.environ.get('MAX_CONCURRENT_UPLOADS', '3'))# Import chunking service (will be set from app)chunking_service = None@@ -249,6 +251,8 @@ def get_config():'incognito_mode_default': INCOGNITO_MODE_DEFAULT,'enable_folders': SystemSetting.get_setting('enable_folders', False) == True,'enable_auto_export': ENABLE_AUTO_EXPORT,+ 'video_retention': VIDEO_RETENTION,+ 'max_concurrent_uploads': MAX_CONCURRENT_UPLOADS,**chunking_info})except Exception as e:diff --git a/src/app.py b/src/app.pyindex 7ede4d73..0e0bed3c 100644--- a/src/app.py+++ b/src/app.py@@ -85,6 +85,9 @@ SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() =# Public sharing configurationENABLE_PUBLIC_SHARING = os.environ.get('ENABLE_PUBLIC_SHARING', 'true').lower() == 'true'+# Video retention - when enabled, video files keep their video stream for playback+VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'+# Log embedding status on startupif ENABLE_INQUIRE_MODE and EMBEDDINGS_AVAILABLE:print("✅ Inquire Mode: Full semantic search enabled (embeddings available)")@@ -122,6 +125,12 @@ if ENABLE_PUBLIC_SHARING:else:print("🔒 Public sharing: Disabled (public share links are not allowed)")+# Log video retention status+if VIDEO_RETENTION:+ print("✅ Video retention: Enabled (video files preserve video stream for playback)")+else:+ print("ℹ️ Video retention: Disabled (video uploads extract audio only)")+# Configure logginglog_level = os.environ.get('LOG_LEVEL', 'INFO').upper()handler = logging.StreamHandler(sys.stdout)diff --git a/src/file_monitor.py b/src/file_monitor.pyindex f5d5f86c..5df25dc1 100644--- a/src/file_monitor.py+++ b/src/file_monitor.py@@ -20,6 +20,9 @@ from src.utils.ffprobe import get_codec_info, get_creation_date, FFProbeErrorfrom src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundErrorfrom src.utils.audio_conversion import convert_if_needed+# Video retention - when enabled, video files keep their video stream for playback+VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'+# Flask app components will be imported inside functions to avoid circular importsclass FileMonitor:@@ -335,32 +338,40 @@ class FileMonitor:except Exception as e:self.logger.warning(f"Could not get connector specs: {e}")- # Convert/compress file if necessary - convert_if_needed handles ALL conversion needs- try:- result = convert_if_needed(- str(destination_path),- original_filename=original_filename,- codec_info=codec_info,- needs_chunking=False,- is_asr_endpoint=False,- delete_original=True, # Clean up original after conversion- connector_specs=connector_specs # Pass connector specs for codec restrictions- )- final_path = Path(result.output_path)-- # Log what happened- if result.was_converted:- self.logger.info(f"File converted: {result.original_codec} -> {result.final_codec}")- if result.was_compressed:- self.logger.info(f"File compressed: {result.size_reduction_percent:.1f}% size reduction")-- except FFmpegNotFoundError as e:- self.logger.error(f"FFmpeg not found: {e}")- raise- except FFmpegError as e:- self.logger.error(f"FFmpeg conversion failed: {e}")- raise-+ # Check if this is a video file (for video retention logic)+ has_video = codec_info.get('has_video', False) if codec_info else False++ # Video retention: skip conversion for videos, processing pipeline handles extraction+ if VIDEO_RETENTION and has_video:+ self.logger.info(f"Video retention: keeping original video, skipping conversion")+ final_path = destination_path+ else:+ # Convert/compress file if necessary - convert_if_needed handles ALL conversion needs+ try:+ result = convert_if_needed(+ str(destination_path),+ original_filename=original_filename,+ codec_info=codec_info,+ needs_chunking=False,+ is_asr_endpoint=False,+ delete_original=True, # Clean up original after conversion+ connector_specs=connector_specs # Pass connector specs for codec restrictions+ )+ final_path = Path(result.output_path)++ # Log what happened+ if result.was_converted:+ self.logger.info(f"File converted: {result.original_codec} -> {result.final_codec}")+ if result.was_compressed:+ self.logger.info(f"File compressed: {result.size_reduction_percent:.1f}% size reduction")++ except FFmpegNotFoundError as e:+ self.logger.error(f"FFmpeg not found: {e}")+ raise+ except FFmpegError as e:+ self.logger.error(f"FFmpeg conversion failed: {e}")+ raise+# Compute file hash for duplicate detectionfile_hash = Nonetry:@@ -410,7 +421,7 @@ class FileMonitor:db.session.add(recording)db.session.commit()-+self.logger.info(f"Created recording record with ID: {recording.id} for user: {user.username}")# Queue for background processingdiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex a3b691a4..a4c37496 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -41,6 +41,9 @@ from src.services.transcription_tracking import transcription_tracker# Configuration for internal sharingENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'+# Video retention - when enabled, video files keep their video stream for playback+VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'+def apply_team_tag_auto_shares(recording_id):"""@@ -1467,6 +1470,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_fileactual_filepath = filepathactual_content_type = mime_type or mimetypes.guess_type(original_filename)[0] or 'application/octet-stream'actual_filename = original_filename+ audio_filepath = None # Track temp audio extracted from video (for cleanup)# Use codec detection to check if file is a videotry:@@ -1485,23 +1489,46 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file)if is_video:- current_app.logger.info(f"Video container detected, extracting audio...")- try:- audio_filepath, audio_mime_type = extract_audio_from_video(filepath)- actual_filepath = audio_filepath- actual_content_type = audio_mime_type- actual_filename = os.path.basename(audio_filepath)-- recording.audio_path = audio_filepath- recording.mime_type = audio_mime_type- db.session.commit()- current_app.logger.info(f"Audio extracted: {audio_filepath}")- except Exception as e:- current_app.logger.error(f"Failed to extract audio from video: {str(e)}")- recording.status = 'FAILED'- recording.error_msg = f"Audio extraction failed: {str(e)}"- db.session.commit()- raise # Re-raise so job queue marks the job as failed+ if VIDEO_RETENTION:+ # Video retention: keep original video, extract audio to temp for transcription only+ current_app.logger.info(f"Video container detected, retaining video and extracting audio to temp...")+ try:+ audio_filepath, audio_mime_type = extract_audio_from_video(filepath, cleanup_original=False)+ # Use extracted audio for transcription processing+ actual_filepath = audio_filepath+ actual_content_type = audio_mime_type+ actual_filename = os.path.basename(audio_filepath)++ # Keep original video file as the stored media+ recording.audio_path = filepath+ recording.mime_type = mimetypes.guess_type(filepath)[0] or 'video/mp4'+ db.session.commit()+ current_app.logger.info(f"Video retained at: {filepath}, temp audio extracted: {audio_filepath}")+ except Exception as e:+ current_app.logger.error(f"Failed to extract audio from video: {str(e)}")+ recording.status = 'FAILED'+ recording.error_msg = f"Audio extraction failed: {str(e)}"+ db.session.commit()+ raise+ else:+ # Default: extract audio, delete original video+ current_app.logger.info(f"Video container detected, extracting audio...")+ try:+ audio_filepath, audio_mime_type = extract_audio_from_video(filepath)+ actual_filepath = audio_filepath+ actual_content_type = audio_mime_type+ actual_filename = os.path.basename(audio_filepath)++ recording.audio_path = audio_filepath+ recording.mime_type = audio_mime_type+ db.session.commit()+ current_app.logger.info(f"Audio extracted: {audio_filepath}")+ except Exception as e:+ current_app.logger.error(f"Failed to extract audio from video: {str(e)}")+ recording.status = 'FAILED'+ recording.error_msg = f"Audio extraction failed: {str(e)}"+ db.session.commit()+ raise # Re-raise so job queue marks the job as failed# Validate and convert audio format if needed using unified conversion utility# This respects:@@ -1685,6 +1712,15 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_fileexcept OSError:pass # Best effort cleanup+ # Clean up temp audio extracted from video when video retention is enabled+ if is_video and VIDEO_RETENTION and audio_filepath and audio_filepath != filepath:+ try:+ if os.path.exists(audio_filepath):+ os.remove(audio_filepath)+ current_app.logger.info(f"Cleaned up temp audio from video retention: {audio_filepath}")+ except OSError:+ pass # Best effort cleanup+# Calculate and save transcription durationtranscription_end_time = time.time()recording.transcription_duration_seconds = int(transcription_end_time - transcription_start_time)@@ -1696,7 +1732,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file# Get actual audio duration (not processing time)audio_duration = Noneif chunking_service:- audio_duration = chunking_service.get_audio_duration(filepath)+ audio_duration = chunking_service.get_audio_duration(recording.audio_path)if audio_duration and audio_duration > 0:# Get model name from connector if availablediff --git a/src/utils/audio_conversion.py b/src/utils/audio_conversion.pyindex 331e449b..b13a9d9d 100644--- a/src/utils/audio_conversion.py+++ b/src/utils/audio_conversion.py@@ -208,16 +208,16 @@ def convert_if_needed(copy_stream=False)final_codec = video_target_codec-+final_size = os.path.getsize(output_filepath)reduction = ((original_size - final_size) / original_size * 100) if original_size > 0 else 0-+logger.info(f"Successfully extracted audio from {original_filename}: "f"{original_size/1024/1024:.1f}MB -> {final_size/1024/1024:.1f}MB "f"({reduction:.1f}% reduction)")-+return ConversionResult(output_path=output_filepath,mime_type=mime_type,diff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 20f1b198..68dc2cf4 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -311,6 +311,7 @@ document.addEventListener('DOMContentLoaded', async () => {const chunkingMode = ref('size');const chunkingLimit = ref(20);const chunkingLimitDisplay = ref('20MB');+ const maxConcurrentUploads = ref(3);const recordingDisclaimer = ref('');const showRecordingDisclaimerModal = ref(false);const pendingRecordingMode = ref(null);@@ -643,7 +644,7 @@ document.addEventListener('DOMContentLoaded', async () => {uploadQueue, allJobs, currentlyProcessingFile, processingProgress, processingMessage,isProcessingActive, pollInterval, progressPopupMinimized, progressPopupClosed,maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, chunkingLimitDisplay,- recordingDisclaimer, showRecordingDisclaimerModal, pendingRecordingMode,+ maxConcurrentUploads, recordingDisclaimer, showRecordingDisclaimerModal, pendingRecordingMode,showAdvancedOptions, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,availableTags, selectedTagIds, uploadTagSearchFilter,availableFolders, selectedFolderId, foldersEnabled, filterFolder,@@ -2238,6 +2239,7 @@ document.addEventListener('DOMContentLoaded', async () => {showUsernamesInUI.value = config.show_usernames_in_ui === true;enableIncognitoMode.value = config.enable_incognito_mode === true;foldersEnabled.value = config.enable_folders === true;+ maxConcurrentUploads.value = config.max_concurrent_uploads || 3;// Restore saved folder selection from localStorageif (foldersEnabled.value) {diff --git a/static/js/modules/composables/audioPlayer.js b/static/js/modules/composables/audioPlayer.jsindex 951d333d..6a949d76 100644--- a/static/js/modules/composables/audioPlayer.js+++ b/static/js/modules/composables/audioPlayer.js@@ -134,7 +134,9 @@ export function useAudioPlayer(ref, computed) {*/let getAudioElement = () => {return document.querySelector('audio[ref="audioPlayerElement"]') ||- document.querySelector('audio');+ document.querySelector('video[ref="audioPlayerElement"]') ||+ document.querySelector('audio') ||+ document.querySelector('video');};/**diff --git a/static/js/modules/composables/speakers.js b/static/js/modules/composables/speakers.jsindex 87f980f1..9ab2f0ed 100644--- a/static/js/modules/composables/speakers.js+++ b/static/js/modules/composables/speakers.js@@ -47,8 +47,8 @@ export function useSpeakers(state, utils, processedTranscription) {// Helper to pause outer audio player when opening modals with their own playerconst pauseOuterAudioPlayer = () => {// Find the audio player in the right panel (not in a modal)- const outerAudio = document.querySelector('#rightMainColumn audio') ||- document.querySelector('.detail-view audio:not(.fixed audio)');+ const outerAudio = document.querySelector('#rightMainColumn audio') || document.querySelector('#rightMainColumn video') ||+ document.querySelector('.detail-view audio:not(.fixed audio)') || document.querySelector('.detail-view video:not(.fixed video)');if (outerAudio && !outerAudio.paused) {outerAudio.pause();}@@ -168,7 +168,7 @@ export function useSpeakers(state, utils, processedTranscription) {const closeSpeakerModal = () => {// Pause any playing modal audio before closing- const modalAudio = document.querySelector('.fixed.z-50 audio');+ const modalAudio = document.querySelector('.fixed.z-50 audio') || document.querySelector('.fixed.z-50 video');if (modalAudio) {modalAudio.pause();}diff --git a/static/js/modules/composables/transcription.js b/static/js/modules/composables/transcription.jsindex d3cf5f20..6ac52ad6 100644--- a/static/js/modules/composables/transcription.js+++ b/static/js/modules/composables/transcription.js@@ -58,8 +58,8 @@ export function useTranscription(state, utils) {// Helper to pause outer audio player when opening modals with their own playerconst pauseOuterAudioPlayer = () => {- const outerAudio = document.querySelector('#rightMainColumn audio') ||- document.querySelector('.detail-view audio:not(.fixed audio)');+ const outerAudio = document.querySelector('#rightMainColumn audio') || document.querySelector('#rightMainColumn video') ||+ document.querySelector('.detail-view audio:not(.fixed audio)') || document.querySelector('.detail-view video:not(.fixed video)');if (outerAudio && !outerAudio.paused) {outerAudio.pause();}@@ -99,7 +99,7 @@ export function useTranscription(state, utils) {const closeAsrEditorModal = () => {// Pause any playing modal audio before closing- const modalAudio = document.querySelector('.fixed.z-50 audio');+ const modalAudio = document.querySelector('.fixed.z-50 audio') || document.querySelector('.fixed.z-50 video');if (modalAudio) {modalAudio.pause();}@@ -303,8 +303,8 @@ export function useTranscription(state, utils) {const seekToSegmentTime = (time) => {// Find audio elements and use the one in a visible modal (z-50)- const audioElements = document.querySelectorAll('.fixed.z-50 audio');- const audioElement = audioElements.length > 0 ? audioElements[audioElements.length - 1] : null;+ const mediaElements = document.querySelectorAll('.fixed.z-50 audio, .fixed.z-50 video');+ const audioElement = mediaElements.length > 0 ? mediaElements[mediaElements.length - 1] : null;if (audioElement) {audioElement.currentTime = time;audioElement.play();diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex 367e88b4..341d09d8 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -813,13 +813,13 @@ export function useUI(state, utils, processedTranscription) {const seekAudio = (time, context = 'main') => {let audioPlayer = null;if (context === 'modal') {- audioPlayer = document.querySelector('audio.speaker-modal-transcript');+ audioPlayer = document.querySelector('audio.speaker-modal-transcript') || document.querySelector('video.speaker-modal-transcript');} else {- audioPlayer = document.querySelector('.main-content-area audio');+ audioPlayer = document.querySelector('.main-content-area audio') || document.querySelector('.main-content-area video');}if (!audioPlayer) {- audioPlayer = document.querySelector('audio');+ audioPlayer = document.querySelector('audio') || document.querySelector('video');}if (audioPlayer && isFinite(time)) {@@ -856,16 +856,18 @@ export function useUI(state, utils, processedTranscription) {// --- Custom Audio Player Controls ---const getAudioElement = () => {- // First check for audio in visible modals (z-50 class) - these take priority- const modalAudio = document.querySelector('.fixed.z-50 audio');- if (modalAudio) {- return modalAudio;+ // First check for audio/video in visible modals (z-50 class) - these take priority+ const modalMedia = document.querySelector('.fixed.z-50 audio') || document.querySelector('.fixed.z-50 video');+ if (modalMedia) {+ return modalMedia;}// Fall back to main player in right column (desktop) or detail view (mobile)return document.querySelector('#rightMainColumn audio') ||+ document.querySelector('#rightMainColumn video') ||document.querySelector('.detail-view audio') ||- document.querySelector('audio[ref="audioPlayerElement"]') ||- document.querySelector('audio');+ document.querySelector('.detail-view video') ||+ document.querySelector('audio') ||+ document.querySelector('video');};const toggleAudioPlayback = () => {@@ -1060,10 +1062,9 @@ export function useUI(state, utils, processedTranscription) {playbackRate.value = rate;localStorage.setItem('playbackRate', rate);- // Apply to all audio elements- const audioElements = document.querySelectorAll('audio');- audioElements.forEach(audio => {- audio.playbackRate = rate;+ // Apply to all audio and video elements+ document.querySelectorAll('audio, video').forEach(el => {+ el.playbackRate = rate;});};@@ -1080,6 +1081,7 @@ export function useUI(state, utils, processedTranscription) {// Apply to modal audio elementsconst modalAudio = document.querySelector('.speaker-modal-transcript')?.closest('.fixed')?.querySelector('audio') ||+ document.querySelector('.speaker-modal-transcript')?.closest('.fixed')?.querySelector('video') ||document.querySelector('[ref="speakerModalAudioRef"]') ||document.querySelector('[ref="asrEditorAudioRef"]');if (modalAudio) {diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 39f50f36..33c54b9a 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -32,7 +32,7 @@ export function useUpload(state, utils) {const {uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,isProcessingActive, pollInterval, progressPopupMinimized, progressPopupClosed,- maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit,+ maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, maxConcurrentUploads,recordings, selectedRecording, totalRecordings, globalError,selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,useAsrEndpoint, connectorSupportsDiarization, asrLanguage, asrMinSpeakers, asrMaxSpeakers,@@ -269,14 +269,13 @@ export function useUpload(state, utils) {};// --- Parallel Upload System ---- // Concurrency limiter: max 3 simultaneous uploads- const MAX_CONCURRENT_UPLOADS = 3;+ // Concurrency limiter: configurable via MAX_CONCURRENT_UPLOADS env var (default 3)let activeUploadCount = 0;const pendingUploadQueue = []; // Functions waiting for a slotconst acquireUploadSlot = () => {return new Promise(resolve => {- if (activeUploadCount < MAX_CONCURRENT_UPLOADS) {+ if (activeUploadCount < (maxConcurrentUploads?.value || 3)) {activeUploadCount++;resolve();} else {@@ -494,7 +493,7 @@ export function useUpload(state, utils) {}isProcessingActive.value = true;- console.log(`Starting parallel upload of ${readyItems.length} file(s) (max ${MAX_CONCURRENT_UPLOADS} concurrent)...`);+ console.log(`Starting parallel upload of ${readyItems.length} file(s) (max ${maxConcurrentUploads?.value || 3} concurrent)...`);// Fire off all uploads concurrently (semaphore handles limiting)const uploadPromises = readyItems.map(item => uploadSingleFile(item));diff --git a/static/js/modules/state/upload.js b/static/js/modules/state/upload.jsindex e4633e02..c7932218 100644--- a/static/js/modules/state/upload.js+++ b/static/js/modules/state/upload.js@@ -17,6 +17,7 @@ export function createUploadState(ref, computed) {const chunkingMode = ref('size');const chunkingLimit = ref(20);const chunkingLimitDisplay = ref('20MB');+ const maxConcurrentUploads = ref(3);const recordingDisclaimer = ref('');const showRecordingDisclaimerModal = ref(false);const pendingRecordingMode = ref(null);@@ -50,6 +51,7 @@ export function createUploadState(ref, computed) {chunkingMode,chunkingLimit,chunkingLimitDisplay,+ maxConcurrentUploads,recordingDisclaimer,showRecordingDisclaimerModal,pendingRecordingMode,diff --git a/static/locales/de.json b/static/locales/de.jsonindex 301e511a..1ab0cfa9 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1147,7 +1147,8 @@"willAutoSummarize": "Wird nach der Transkription automatisch zusammengefasst","duplicateDetected": "Diese Datei scheint ein Duplikat von \"{{existingName}}\" zu sein (hochgeladen am {{existingDate}})","duplicateFile": "Doppelte Datei",- "copies": "Kopien dieser Datei"+ "copies": "Kopien dieser Datei",+ "videoRetained": "Video für Wiedergabe beibehalten"},"uploadProgress": {"title": "Upload-Fortschritt"diff --git a/static/locales/en.json b/static/locales/en.jsonindex 7fe9b036..8f0026a0 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1198,7 +1198,8 @@"willAutoSummarize": "Will auto-summarize after transcription","duplicateDetected": "This file appears to be a duplicate of \"{{existingName}}\" (uploaded {{existingDate}})","duplicateFile": "Duplicate file",- "copies": "copies of this file"+ "copies": "copies of this file",+ "videoRetained": "Video preserved for playback"},"uploadProgress": {"title": "Upload Progress"diff --git a/static/locales/es.json b/static/locales/es.jsonindex 17e8f5f2..3ecc6ade 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1147,7 +1147,8 @@"willAutoSummarize": "Se resumirá automáticamente después de la transcripción","duplicateDetected": "Este archivo parece ser un duplicado de \"{{existingName}}\" (subido el {{existingDate}})","duplicateFile": "Archivo duplicado",- "copies": "copias de este archivo"+ "copies": "copias de este archivo",+ "videoRetained": "Video conservado para reproducción"},"uploadProgress": {"title": "Progreso de Carga"diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 7f8467b4..37f37f00 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1141,7 +1141,8 @@"willAutoSummarize": "Résumé automatique après la transcription","duplicateDetected": "Ce fichier semble être un doublon de \"{{existingName}}\" (importé le {{existingDate}})","duplicateFile": "Fichier en double",- "copies": "copies de ce fichier"+ "copies": "copies de ce fichier",+ "videoRetained": "Vidéo conservée pour la lecture"},"uploadProgress": {"title": "Progression du Téléchargement"diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 33cd6714..871226ae 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1163,7 +1163,8 @@"willAutoSummarize": "Автоматически создаст резюме после транскрибирования","duplicateDetected": "Этот файл является дубликатом \"{{existingName}}\" (загружен {{existingDate}})","duplicateFile": "Дубликат файла",- "copies": "копий этого файла"+ "copies": "копий этого файла",+ "videoRetained": "Видео сохранено для воспроизведения"},"uploadProgress": {"title": "Прогресс загрузки"diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 437647e6..b4d1df2a 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1276,7 +1276,8 @@"willAutoSummarize": "转录后将自动生成摘要","duplicateDetected": "此文件似乎与 \"{{existingName}}\" 重复(上传于 {{existingDate}})","duplicateFile": "重复文件",- "copies": "份此文件的副本"+ "copies": "份此文件的副本",+ "videoRetained": "视频已保留供播放"},"uploadProgress": {"title": "上传进度"diff --git a/templates/components/detail/audio-player.html b/templates/components/detail/audio-player.htmlindex 2d847fb6..1d02aa10 100644--- a/templates/components/detail/audio-player.html+++ b/templates/components/detail/audio-player.html@@ -14,8 +14,9 @@</div><!-- Custom Audio Player --><div v-else>- <!-- Hidden audio element -->- <audio ref="audioPlayerElement"+ <!-- Video/Audio element (video when mime_type starts with video/) -->+ <component :is="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'video' : 'audio'"+ ref="audioPlayerElement":src="'/audio/' + selectedRecording.id":volume="playerVolume"@play="handleAudioPlayPause"@@ -26,8 +27,9 @@@ended="handleAudioEnded"@waiting="handleAudioWaiting"@canplay="handleAudioCanPlay"- class="hidden">- </audio>+ @click="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') && toggleAudioPlayback()"+ :class="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'w-full rounded-lg mb-2 cursor-pointer' : 'hidden'">+ </component><!-- Progress Bar (draggable, touch support) --><div class="w-full h-4 rounded-full cursor-pointer relative mb-2 group flex items-center"diff --git a/templates/components/detail/desktop-right-panel.html b/templates/components/detail/desktop-right-panel.htmlindex 4b77bfe7..a5f43c18 100644--- a/templates/components/detail/desktop-right-panel.html+++ b/templates/components/detail/desktop-right-panel.html@@ -16,8 +16,9 @@</div><!-- Custom Audio Player Card --><div v-else class="bg-[var(--bg-tertiary)] rounded-xl p-4 shadow-sm border border-[var(--border-primary)] overflow-hidden">- <!-- Hidden audio element -->- <audio ref="audioPlayerElement"+ <!-- Video/Audio element (video when mime_type starts with video/) -->+ <component :is="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'video' : 'audio'"+ ref="audioPlayerElement":src="'/audio/' + selectedRecording.id":volume="playerVolume"@play="handleAudioPlayPause"@@ -28,8 +29,9 @@@ended="handleAudioEnded"@waiting="handleAudioWaiting"@canplay="handleAudioCanPlay"- class="hidden">- </audio>+ @click="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') && toggleAudioPlayback()"+ :class="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'w-full rounded-lg mb-3 cursor-pointer' : 'hidden'">+ </component><!-- Progress Bar (now on top, full width, draggable) --><div class="w-full h-4 rounded-full cursor-pointer relative mb-3 group flex items-center"diff --git a/templates/modals/speaker-modal.html b/templates/modals/speaker-modal.htmlindex fb7c29d8..02d1fe0b 100644--- a/templates/modals/speaker-modal.html+++ b/templates/modals/speaker-modal.html@@ -142,9 +142,11 @@<i class="fas fa-user-secret"></i><span>Audio not stored in incognito mode</span></div>- <!-- Custom Audio Player (Independent from main player) -->- <div v-else class="flex items-center gap-2">- <audio ref="speakerModalAudioRef" class="hidden"+ <!-- Custom Audio/Video Player (Independent from main player) -->+ <div v-else>+ <component :is="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'video' : 'audio'"+ ref="speakerModalAudioRef"+ :class="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'w-full rounded-lg mb-2' : 'hidden'":key="'speaker-modal-' + selectedRecording.id":src="'/audio/' + selectedRecording.id":volume="playerVolume"@@ -153,7 +155,8 @@@timeupdate="handleModalAudioTimeUpdate"@loadedmetadata="handleModalAudioLoadedMetadata"@ended="modalAudioIsPlaying = false">- </audio>+ </component>+ <div class="flex items-center gap-2"><!-- Play/Pause --><button @click="$refs.speakerModalAudioRef?.paused ? $refs.speakerModalAudioRef.play() : $refs.speakerModalAudioRef.pause()"class="w-8 h-8 flex items-center justify-center rounded-full bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] text-white transition-all flex-shrink-0 shadow-sm"@@ -204,6 +207,7 @@</button></div></div>+ </div><!-- Transcript Section (Virtual Scrolling for performance) --><div ref="speakerModalTranscriptRef"diff --git a/templates/share.html b/templates/share.htmlindex 787e0e6b..5dc7a0c5 100644--- a/templates/share.html+++ b/templates/share.html@@ -107,9 +107,11 @@<i class="fas fa-info-circle"></i><span>Audio file has been archived and is no longer available for playback.</span></div>- <!-- Custom Audio Player -->- <div v-else class="flex items-center gap-3">- <audio ref="audioPlayer" class="hidden"+ <!-- Custom Audio/Video Player -->+ <div v-else>+ <component :is="recording.mime_type && recording.mime_type.startsWith('video/') ? 'video' : 'audio'"+ ref="audioPlayer"+ :class="recording.mime_type && recording.mime_type.startsWith('video/') ? 'w-full rounded-lg mb-3' : 'hidden'":src="'/share/audio/' + recording.public_id"@play="handleAudioPlayPause"@pause="handleAudioPlayPause"@@ -117,7 +119,8 @@@loadedmetadata="handleAudioLoadedMetadata"@durationchange="handleAudioDurationChange"@ended="handleAudioEnded">- </audio>+ </component>+ <div class="flex items-center gap-3"><!-- Play/Pause --><button @click="toggleAudioPlayback"class="w-10 h-10 flex items-center justify-center rounded-full bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] text-white transition-all flex-shrink-0 shadow-sm"@@ -167,6 +170,7 @@class="volume-slider w-20 h-1.5 rounded-full cursor-pointer"></div></div>+ </div></div></div>diff --git a/tests/test_video_retention.py b/tests/test_video_retention.pynew file mode 100644index 00000000..5428d57b--- /dev/null+++ b/tests/test_video_retention.py@@ -0,0 +1,370 @@+"""+Test suite for the VIDEO_RETENTION feature.++Tests code paths, configuration, and template correctness for video retention.+Does NOT require a running server or real video files - uses static analysis+and mocking where possible.++Run with: python tests/test_video_retention.py+"""++import os+import re+import sys+import json+import unittest+from unittest.mock import patch, MagicMock+from pathlib import Path++# Find project root+TEST_DIR = os.path.dirname(os.path.abspath(__file__))+PROJECT_ROOT = os.path.dirname(TEST_DIR)+sys.path.insert(0, PROJECT_ROOT)+++class TestVideoRetentionConfig(unittest.TestCase):+ """Test that VIDEO_RETENTION env var is read correctly everywhere."""++ ALL_FILES = [+ 'src/app.py',+ 'src/tasks/processing.py',+ 'src/api/system.py',+ 'src/api/recordings.py',+ 'src/file_monitor.py',+ ]++ def _read_file(self, rel_path):+ with open(os.path.join(PROJECT_ROOT, rel_path), 'r') as f:+ return f.read()++ def test_env_var_read_in_all_entry_points(self):+ """VIDEO_RETENTION env var is read in all files that need it."""+ for rel_path in self.ALL_FILES:+ content = self._read_file(rel_path)+ self.assertIn("VIDEO_RETENTION", content, f"VIDEO_RETENTION missing from {rel_path}")++ def test_exposed_in_api_config(self):+ """VIDEO_RETENTION is exposed in the /api/config response."""+ content = self._read_file('src/api/system.py')+ self.assertIn("'video_retention': VIDEO_RETENTION", content)++ def test_default_is_false(self):+ """All VIDEO_RETENTION reads default to 'false'."""+ for rel_path in self.ALL_FILES:+ content = self._read_file(rel_path)+ match = re.search(r"VIDEO_RETENTION\s*=\s*os\.environ\.get\('VIDEO_RETENTION',\s*'(\w+)'\)", content)+ if match:+ self.assertEqual(match.group(1), 'false', f"Default should be 'false' in {rel_path}")+++class TestProcessingPipelineVideoRetention(unittest.TestCase):+ """Test processing.py video retention code paths via static analysis."""++ @classmethod+ def setUpClass(cls):+ with open(os.path.join(PROJECT_ROOT, 'src/tasks/processing.py'), 'r') as f:+ cls.content = f.read()++ def test_video_retention_true_keeps_original(self):+ """When VIDEO_RETENTION=True, recording.audio_path is set to original filepath."""+ # The VIDEO_RETENTION=True branch should set recording.audio_path = filepath+ self.assertIn('recording.audio_path = filepath', self.content)++ def test_video_retention_true_extracts_without_cleanup(self):+ """When VIDEO_RETENTION=True, extract_audio_from_video is called with cleanup_original=False."""+ self.assertIn('extract_audio_from_video(filepath, cleanup_original=False)', self.content)++ def test_video_retention_false_extracts_with_cleanup(self):+ """When VIDEO_RETENTION=False, extract_audio_from_video is called with default cleanup."""+ self.assertIn('extract_audio_from_video(filepath)', self.content)++ def test_temp_audio_cleanup_after_transcription(self):+ """Temp audio from video retention is cleaned up after transcription."""+ self.assertIn('is_video and VIDEO_RETENTION and audio_filepath', self.content)+ self.assertIn('Cleaned up temp audio from video retention', self.content)++ def test_audio_filepath_initialized_to_none(self):+ """audio_filepath is initialized to None before the is_video check."""+ # Find the initialization line+ self.assertIn('audio_filepath = None', self.content)++ def test_video_mime_type_set_for_retention(self):+ """When retaining video, mime_type reflects actual video type."""+ self.assertIn("mimetypes.guess_type(filepath)[0] or 'video/mp4'", self.content)++ def test_duration_uses_recording_audio_path(self):+ """Duration lookup uses recording.audio_path (always valid), not filepath."""+ self.assertIn('chunking_service.get_audio_duration(recording.audio_path)', self.content)+ # Should NOT use bare filepath for duration (pre-existing bug was fixed)+ self.assertNotIn('chunking_service.get_audio_duration(filepath)', self.content)+++class TestUploadHandlerVideoRetention(unittest.TestCase):+ """Test recordings.py upload handler video retention code paths."""++ @classmethod+ def setUpClass(cls):+ with open(os.path.join(PROJECT_ROOT, 'src/api/recordings.py'), 'r') as f:+ cls.content = f.read()++ def test_upload_handler_skips_conversion_for_video_retention(self):+ """Upload handler skips convert_if_needed for videos when retention is on."""+ self.assertIn('VIDEO_RETENTION and has_video', self.content)+ self.assertIn('skipping conversion', self.content)++ def test_upload_handler_has_video_from_codec_info(self):+ """Upload handler reads has_video from codec_info probe."""+ self.assertIn("has_video = codec_info.get('has_video', False)", self.content)++ def test_convert_if_needed_still_in_else_branch(self):+ """convert_if_needed still runs for non-video files or when retention is off."""+ self.assertIn('convert_if_needed(', self.content)++ def test_processing_pipeline_still_converts_audio(self):+ """Processing pipeline runs convert_if_needed on extracted audio (the safety net)."""+ proc_content = open(os.path.join(PROJECT_ROOT, 'src/tasks/processing.py')).read()+ # After the video extraction block, convert_if_needed runs on actual_filepath+ self.assertIn('conversion_result = convert_if_needed(\n'+ ' filepath=actual_filepath,', proc_content)+++class TestFileMonitorVideoRetention(unittest.TestCase):+ """Test file_monitor.py video retention code paths."""++ @classmethod+ def setUpClass(cls):+ with open(os.path.join(PROJECT_ROOT, 'src/file_monitor.py'), 'r') as f:+ cls.content = f.read()++ def test_video_retention_skips_conversion(self):+ """When VIDEO_RETENTION=True and has_video=True, convert_if_needed is skipped."""+ # Should have the guard: if VIDEO_RETENTION and has_video: ... skip conversion+ self.assertIn('VIDEO_RETENTION and has_video', self.content)+ self.assertIn('skipping conversion', self.content)++ def test_no_double_extraction(self):+ """File monitor does NOT call convert_if_needed for videos when retention is on."""+ # The convert_if_needed call should be in the else branch+ lines = self.content.split('\n')+ in_retention_skip_block = False+ found_convert_in_else = False++ for i, line in enumerate(lines):+ if 'VIDEO_RETENTION and has_video' in line and 'if' in line:+ in_retention_skip_block = True+ elif in_retention_skip_block and 'else:' in line:+ in_retention_skip_block = False+ found_convert_in_else = True+ elif in_retention_skip_block and 'convert_if_needed' in line:+ self.fail(f"convert_if_needed called inside VIDEO_RETENTION skip block at line {i+1}")++ self.assertTrue(found_convert_in_else, "Should have else branch after video retention skip")++ def test_no_video_retention_param_in_convert_call(self):+ """convert_if_needed should NOT receive a video_retention parameter."""+ # Ensure the old video_retention parameter isn't being passed+ self.assertNotIn('video_retention=VIDEO_RETENTION', self.content)+++class TestAudioConversionNotModified(unittest.TestCase):+ """Verify audio_conversion.py was fully reverted (no video_retention parameter)."""++ @classmethod+ def setUpClass(cls):+ with open(os.path.join(PROJECT_ROOT, 'src/utils/audio_conversion.py'), 'r') as f:+ cls.content = f.read()++ def test_no_video_retention_parameter(self):+ """convert_if_needed should not have a video_retention parameter."""+ self.assertNotIn('video_retention', self.content)++ def test_no_should_delete_original(self):+ """No should_delete_original variable should exist."""+ self.assertNotIn('should_delete_original', self.content)+++class TestSendFileConditional(unittest.TestCase):+ """Test that send_file calls use conditional=True for range request support."""++ def _read_file(self, rel_path):+ with open(os.path.join(PROJECT_ROOT, rel_path), 'r') as f:+ return f.read()++ def test_recordings_streaming_has_conditional(self):+ """Streaming send_file in recordings.py has conditional=True."""+ content = self._read_file('src/api/recordings.py')+ # Find the non-download send_file call+ self.assertIn('send_file(recording.audio_path, conditional=True)', content)++ def test_recordings_download_has_conditional(self):+ """Download send_file in recordings.py has conditional=True."""+ content = self._read_file('src/api/recordings.py')+ self.assertIn('as_attachment=True, download_name=filename, conditional=True', content)++ def test_shares_has_conditional(self):+ """send_file in shares.py has conditional=True."""+ content = self._read_file('src/api/shares.py')+ self.assertIn('send_file(recording.audio_path, conditional=True)', content)+++class TestFrontendTemplates(unittest.TestCase):+ """Test that frontend templates correctly switch between video and audio."""++ TEMPLATE_FILES = [+ 'templates/components/detail/desktop-right-panel.html',+ 'templates/components/detail/audio-player.html',+ 'templates/modals/speaker-modal.html',+ 'templates/share.html',+ ]++ def _read_template(self, rel_path):+ with open(os.path.join(PROJECT_ROOT, rel_path), 'r') as f:+ return f.read()++ def test_all_templates_use_dynamic_component(self):+ """All player templates use <component :is> for video/audio switching."""+ for tmpl in self.TEMPLATE_FILES:+ content = self._read_template(tmpl)+ self.assertIn("<component :is=", content, f"Missing dynamic component in {tmpl}")+ self.assertIn("startsWith('video/')", content, f"Missing video/ check in {tmpl}")+ self.assertIn("</component>", content, f"Missing </component> in {tmpl}")++ def test_no_bare_audio_elements_in_main_players(self):+ """Main player templates should not have bare <audio elements (replaced by component)."""+ for tmpl in self.TEMPLATE_FILES:+ content = self._read_template(tmpl)+ # Count <audio and <component :is occurrences+ audio_count = content.count('<audio ')+ component_count = content.count('<component :is=')++ # Each template should have component :is but no bare <audio for the main player+ self.assertGreater(component_count, 0, f"No <component :is> in {tmpl}")+ # Desktop right panel and audio player should have 0 bare audio tags+ if 'desktop-right-panel' in tmpl or 'audio-player' in tmpl:+ self.assertEqual(audio_count, 0, f"Unexpected bare <audio> in {tmpl}")++ def test_video_element_gets_visible_styling(self):+ """When mime_type is video/, the element should be visible (not hidden)."""+ for tmpl in self.TEMPLATE_FILES:+ content = self._read_template(tmpl)+ # Should have conditional class that shows video and hides audio+ self.assertIn("'w-full rounded-lg", content, f"Missing video styling in {tmpl}")+ self.assertIn("'hidden'", content, f"Missing hidden fallback for audio in {tmpl}")++ def test_template_div_balance(self):+ """Verify player-specific templates have balanced div tags."""+ # Only check templates we fully control (not share.html which has pre-existing imbalance)+ balanced_templates = [+ 'templates/components/detail/desktop-right-panel.html',+ 'templates/components/detail/audio-player.html',+ 'templates/modals/speaker-modal.html',+ ]+ for tmpl in balanced_templates:+ content = self._read_template(tmpl)+ opens = content.count('<div')+ closes = content.count('</div>')+ self.assertEqual(opens, closes, f"Unbalanced divs in {tmpl}: {opens} opens, {closes} closes")+++class TestLocalization(unittest.TestCase):+ """Test that video retention localization keys exist in all locale files."""++ LOCALE_DIR = os.path.join(PROJECT_ROOT, 'static', 'locales')++ def test_video_retained_key_in_all_locales(self):+ """upload.videoRetained key exists in all locale files."""+ locale_files = [f for f in os.listdir(self.LOCALE_DIR) if f.endswith('.json')]+ self.assertGreater(len(locale_files), 0, "No locale files found")++ for locale_file in locale_files:+ filepath = os.path.join(self.LOCALE_DIR, locale_file)+ with open(filepath, 'r', encoding='utf-8') as f:+ data = json.load(f)++ self.assertIn('upload', data, f"No 'upload' section in {locale_file}")+ self.assertIn('videoRetained', data['upload'],+ f"Missing 'videoRetained' key in upload section of {locale_file}")+ self.assertIsInstance(data['upload']['videoRetained'], str,+ f"'videoRetained' should be a string in {locale_file}")+ self.assertGreater(len(data['upload']['videoRetained']), 0,+ f"'videoRetained' is empty in {locale_file}")++ def test_locale_files_are_valid_json(self):+ """All locale files are valid JSON."""+ locale_files = [f for f in os.listdir(self.LOCALE_DIR) if f.endswith('.json')]+ for locale_file in locale_files:+ filepath = os.path.join(self.LOCALE_DIR, locale_file)+ try:+ with open(filepath, 'r', encoding='utf-8') as f:+ json.load(f)+ except json.JSONDecodeError as e:+ self.fail(f"Invalid JSON in {locale_file}: {e}")+++class TestVideoRetentionMatrix(unittest.TestCase):+ """+ Test the complete 2x2 matrix of (VIDEO_RETENTION x is_video) scenarios+ by analyzing the code flow statically.+ """++ def _read_file(self, rel_path):+ with open(os.path.join(PROJECT_ROOT, rel_path), 'r') as f:+ return f.read()++ def test_processing_has_both_branches(self):+ """processing.py has both VIDEO_RETENTION=True and False branches for video."""+ content = self._read_file('src/tasks/processing.py')+ # Should have if VIDEO_RETENTION: ... else: ... inside if is_video:+ self.assertIn('if VIDEO_RETENTION:', content)+ # After the retention block, should have else for the default behavior+ lines = content.split('\n')+ found_retention_if = False+ found_else_after = False+ for line in lines:+ if 'if VIDEO_RETENTION:' in line:+ found_retention_if = True+ elif found_retention_if and line.strip().startswith('else:'):+ found_else_after = True+ break+ self.assertTrue(found_else_after, "Missing else branch after VIDEO_RETENTION check in processing.py")++ def test_file_monitor_has_both_branches(self):+ """file_monitor.py has both video retention skip and normal conversion paths."""+ content = self._read_file('src/file_monitor.py')+ self.assertIn('VIDEO_RETENTION and has_video', content)+ # convert_if_needed should still exist in the else path+ self.assertIn('convert_if_needed(', content)++ def test_incognito_not_affected(self):+ """Incognito processing path should NOT reference VIDEO_RETENTION."""+ content = self._read_file('src/tasks/processing.py')+ # Find the incognito section (marked with [Incognito])+ incognito_section = content[content.find('[Incognito]'):]+ # VIDEO_RETENTION should not appear in incognito section+ # (incognito always strips video per the plan)+ self.assertNotIn('VIDEO_RETENTION', incognito_section,+ "VIDEO_RETENTION should not be referenced in incognito processing")++ def test_all_three_entry_points_skip_for_video_retention(self):+ """All entry points (upload, file monitor, processing) handle VIDEO_RETENTION."""+ for rel_path, marker in [+ ('src/api/recordings.py', 'VIDEO_RETENTION and has_video'),+ ('src/file_monitor.py', 'VIDEO_RETENTION and has_video'),+ ('src/tasks/processing.py', 'if VIDEO_RETENTION:'),+ ]:+ content = self._read_file(rel_path)+ self.assertIn(marker, content, f"Missing video retention guard in {rel_path}")++ def test_convert_if_needed_always_runs_on_transcription_audio(self):+ """Processing pipeline always runs convert_if_needed on audio before transcription."""+ content = self._read_file('src/tasks/processing.py')+ # The convert_if_needed call on actual_filepath happens AFTER the video+ # extraction block, regardless of VIDEO_RETENTION setting+ video_block_pos = content.find('if is_video:')+ convert_pos = content.find('convert_if_needed(\n filepath=actual_filepath,')+ self.assertGreater(convert_pos, video_block_pos,+ "convert_if_needed must run after video extraction block")+++if __name__ == '__main__':+ unittest.main(verbosity=2)