Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add per-upload Keep audio only override and larger size limit for audio-only video uploads, with admin setting max_audio_only_video_size_mb (default 4x max_file_size_mb) and a post-extraction size guard against oversized stored audio

Murtaza Nasir84e01058d8fb
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index 682a9169..30f5cc0c 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -150,6 +150,7 @@ Upload a recording as multipart form-data and immediately queue transcription.
| `max_speakers` | integer | no | Max speaker count |
| `tag_ids[0]`, `tag_ids[1]`, ... | integer | no | Tag IDs (multi) |
| `tag_id` | integer | no | Single tag ID (legacy) |
+| `keep_audio_only` | boolean | no | If `true`, the server discards the video stream and stores only the extracted audio. Lets you upload videos larger than `max_file_size_mb`, up to `max_audio_only_video_size_mb`, as long as the extracted audio fits the regular limit. When `VIDEO_RETENTION` is off at the server, this is implicit for video uploads. |
**Response:**
diff --git a/src/api/admin.py b/src/api/admin.py
index 28c4a15e..f9787576 100644
--- a/src/api/admin.py
+++ b/src/api/admin.py
@@ -725,12 +725,21 @@ def admin_update_setting():
try:
setting = SystemSetting.set_setting(key, value, description, setting_type)
- # Update Flask's MAX_CONTENT_LENGTH immediately when file size limit changes
- if key == 'max_file_size_mb' and value:
+ # Recompute the Werkzeug ceiling whenever either upload limit
+ # changes. The WSGI ceiling must be the higher of the two so that
+ # audio-only video uploads can exceed max_file_size_mb.
+ if key in ('max_file_size_mb', 'max_audio_only_video_size_mb') and value:
try:
- new_limit = int(value) * 1024 * 1024
- current_app.config['MAX_CONTENT_LENGTH'] = new_limit
- current_app.logger.info(f"Updated MAX_CONTENT_LENGTH to {value}MB")
+ regular_mb = int(SystemSetting.get_setting('max_file_size_mb', 250))
+ audio_only_mb = int(
+ SystemSetting.get_setting('max_audio_only_video_size_mb', regular_mb * 4)
+ )
+ ceiling_mb = max(regular_mb, audio_only_mb)
+ current_app.config['MAX_CONTENT_LENGTH'] = ceiling_mb * 1024 * 1024
+ current_app.logger.info(
+ f"Updated MAX_CONTENT_LENGTH to {ceiling_mb}MB "
+ f"(regular={regular_mb}, audio_only={audio_only_mb})"
+ )
except (ValueError, TypeError):
pass
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 76d7a48c..b6c07ca7 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -328,7 +328,8 @@ OPENAPI_SPEC = {
"folder_id": {"type": "integer"},
"tag_id": {"type": "integer"},
"tag_ids[0]": {"type": "integer"},
- "tag_ids[1]": {"type": "integer"}
+ "tag_ids[1]": {"type": "integer"},
+ "keep_audio_only": {"type": "boolean", "description": "If true, the server discards the video stream and stores only the extracted audio. Allows uploads up to max_audio_only_video_size_mb (vs max_file_size_mb) for video files, as long as the extracted audio still fits the regular limit."}
}
}
}
diff --git a/src/api/recordings.py b/src/api/recordings.py
index c5c9de00..1a9b1813 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2188,11 +2188,42 @@ def upload_file():
safe_filename = secure_filename(original_filename)
filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{safe_filename}")
+ # Per-upload override for VIDEO_RETENTION. When True, the
+ # processing pipeline extracts audio and discards the video stream
+ # regardless of the server's VIDEO_RETENTION env var. Also signals
+ # that this upload is allowed to exceed max_file_size_mb because
+ # only the extracted audio needs to fit that limit. Sent by the
+ # frontend either explicitly (toggle) or implicitly when
+ # VIDEO_RETENTION is off and the queued file is video.
+ keep_audio_only_flag = request.form.get('keep_audio_only', 'false').lower() == 'true'
+ effective_audio_only = keep_audio_only_flag or not VIDEO_RETENTION
+
+ # Detect "this looks like a video" by extension up front so the
+ # size-gate can pick the right limit before reading any bytes.
+ # ffprobe runs later and is authoritative for the keep-video
+ # decision; the extension list here is a pre-save heuristic.
+ _VIDEO_EXTS = {'.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v', '.wmv', '.flv', '.ts', '.mts'}
+ _ext_lower = os.path.splitext(original_filename)[1].lower()
+ is_likely_video_by_ext = _ext_lower in _VIDEO_EXTS
+
# Get original file size
file.seek(0, os.SEEK_END)
original_file_size = file.tell()
file.seek(0)
+ # Resolve effective size limit. Audio-only video uploads use a
+ # separate, larger limit because only the extracted audio is
+ # stored. Regular limit applies to everything else.
+ regular_limit_mb = int(SystemSetting.get_setting('max_file_size_mb', 250))
+ audio_only_limit_mb = int(
+ SystemSetting.get_setting('max_audio_only_video_size_mb', regular_limit_mb * 4)
+ )
+ if effective_audio_only and is_likely_video_by_ext:
+ effective_limit_mb = audio_only_limit_mb
+ else:
+ effective_limit_mb = regular_limit_mb
+ effective_limit_bytes = effective_limit_mb * 1024 * 1024
+
# Check size limit before saving - only enforce if chunking is disabled or connector handles it
max_content_length = current_app.config.get('MAX_CONTENT_LENGTH')
@@ -2222,7 +2253,14 @@ def upload_file():
else:
current_app.logger.info(f"Duration-based chunking enabled ({chunking_config.limit_value}s, source={chunking_config.source}) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
- if should_enforce_size_limit and max_content_length and original_file_size > max_content_length:
+ # Two ceilings to consider. The Werkzeug `max_content_length` is
+ # the WSGI hard cap; the smaller `effective_limit_bytes` is the
+ # per-request policy cap (which differs between regular and
+ # audio-only-video uploads). Reject if EITHER fires.
+ if should_enforce_size_limit and (
+ (max_content_length and original_file_size > max_content_length)
+ or original_file_size > effective_limit_bytes
+ ):
raise RequestEntityTooLarge()
file.save(filepath)
@@ -2290,7 +2328,14 @@ def upload_file():
f"Probe failed but file extension '{file_ext}' indicates video — "
f"treating as video for {'VIDEO_PASSTHROUGH_ASR' if VIDEO_PASSTHROUGH_ASR else 'VIDEO_RETENTION'}"
)
- if (VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR) and has_video:
+ # Per-upload `keep_audio_only` overrides VIDEO_RETENTION for this
+ # request. VIDEO_PASSTHROUGH_ASR is an admin escape hatch that
+ # sends video directly to the ASR endpoint — left untouched here.
+ keep_video_for_this_upload = (
+ ((VIDEO_RETENTION and not keep_audio_only_flag) or VIDEO_PASSTHROUGH_ASR)
+ and has_video
+ )
+ if keep_video_for_this_upload:
current_app.logger.info(f"Video {'passthrough' if VIDEO_PASSTHROUGH_ASR else 'retention'}: keeping original video, skipping conversion")
else:
# Use shared conversion utility - handles ALL conversion needs (codec conversion + compression)
@@ -2322,6 +2367,37 @@ def upload_file():
# Get final file size (of original or converted file)
final_file_size = os.path.getsize(filepath)
+ # Post-extraction size guard. When the upload exceeded the regular
+ # max_file_size_mb under the "audio-only video" exception, the
+ # stored file (after audio extraction) must still fit the regular
+ # limit. If it does not, the user picked a video whose audio track
+ # alone is enormous; reject the upload, clean up, and let them know.
+ if (
+ effective_audio_only
+ and is_likely_video_by_ext
+ and original_file_size > regular_limit_mb * 1024 * 1024
+ and final_file_size > regular_limit_mb * 1024 * 1024
+ ):
+ try:
+ if os.path.exists(filepath):
+ os.remove(filepath)
+ except OSError:
+ pass
+ current_app.logger.warning(
+ f"Audio-only extraction left {final_file_size/1024/1024:.1f}MB of audio, "
+ f"which exceeds regular limit {regular_limit_mb}MB. Rejecting upload."
+ )
+ return jsonify({
+ 'error': (
+ f'The extracted audio is {final_file_size / 1024 / 1024:.0f} MB, '
+ f'larger than the {regular_limit_mb} MB stored-file limit. '
+ f'Try a lower-bitrate video or shorten the recording.'
+ ),
+ 'max_size_mb': float(regular_limit_mb),
+ 'extracted_audio_mb': round(final_file_size / 1024 / 1024, 1),
+ 'audio_only_mode': True,
+ }), 413
+
# (file_hash and duplicate_warning already computed above, before conversion)
# Determine MIME type of the final file
@@ -2517,6 +2593,11 @@ def upload_file():
processing_source='upload', # Track that this was manually uploaded
file_hash=file_hash,
prompt_variables=prompt_variables,
+ # Per-upload override: record the effective audio-only flag so
+ # the processing task knows whether to drop the video stream
+ # regardless of the server's VIDEO_RETENTION setting. True when
+ # the user explicitly toggled it or when VIDEO_RETENTION is off.
+ keep_audio_only=effective_audio_only,
)
db.session.add(recording)
db.session.commit()
@@ -2588,11 +2669,26 @@ def upload_file():
return jsonify(response_data), 202
except RequestEntityTooLarge:
- max_size_mb = current_app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)
- current_app.logger.warning(f"Upload failed: File too large (>{max_size_mb}MB)")
+ # Report the effective limit that fired (regular vs audio-only)
+ # so the frontend can show the right message. effective_limit_mb
+ # is set at the top of the function before the size check.
+ try:
+ limit_mb = float(effective_limit_mb)
+ except (NameError, TypeError, ValueError):
+ limit_mb = float(current_app.config['MAX_CONTENT_LENGTH']) / (1024 * 1024)
+ audio_only_mode = False
+ try:
+ audio_only_mode = bool(effective_audio_only) and bool(is_likely_video_by_ext)
+ except NameError:
+ pass
+ current_app.logger.warning(
+ f"Upload failed: File too large (>{limit_mb}MB, audio_only={audio_only_mode})"
+ )
return jsonify({
- 'error': f'File too large. Maximum size is {max_size_mb:.0f} MB.',
- 'max_size_mb': max_size_mb
+ 'error': f'File too large. Maximum size is {limit_mb:.0f} MB.',
+ 'max_size_mb': limit_mb,
+ 'effective_limit_mb': limit_mb,
+ 'audio_only_mode': audio_only_mode,
}), 413
except Exception as e:
db.session.rollback()
diff --git a/src/api/system.py b/src/api/system.py
index 141ac6c4..144b0cf2 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -198,6 +198,15 @@ def get_config():
try:
# Get configurable file size limit
max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
+ # Audio-only video uploads: only the extracted audio is stored, so
+ # the upload itself can be larger than max_file_size_mb. Used by
+ # the frontend pre-check when "Keep audio only" is on (explicitly
+ # via toggle when VIDEO_RETENTION=true, or implicitly when
+ # VIDEO_RETENTION=false).
+ max_audio_only_video_size_mb = SystemSetting.get_setting(
+ 'max_audio_only_video_size_mb',
+ int(max_file_size_mb) * 4 if max_file_size_mb else 1000,
+ )
# Get chunking configuration (supports both legacy and new formats)
chunking_info = {}
@@ -291,6 +300,7 @@ def get_config():
'enable_folders': SystemSetting.get_setting('enable_folders', False) == True,
'enable_auto_export': ENABLE_AUTO_EXPORT,
'video_retention': VIDEO_RETENTION,
+ 'max_audio_only_video_size_mb': max_audio_only_video_size_mb,
'max_concurrent_uploads': MAX_CONCURRENT_UPLOADS,
'user_transcription_language': user_transcription_language,
'user_summary_prompt': user_summary_prompt,
diff --git a/src/config/startup.py b/src/config/startup.py
index b6140356..e0ec2afe 100644
--- a/src/config/startup.py
+++ b/src/config/startup.py
@@ -183,10 +183,22 @@ def run_startup_tasks(app):
from src.models import SystemSetting
with app.app_context():
- # Set dynamic MAX_CONTENT_LENGTH based on database setting
- max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
- app.config['MAX_CONTENT_LENGTH'] = max_file_size_mb * 1024 * 1024
- app.logger.info(f"Set MAX_CONTENT_LENGTH to {max_file_size_mb}MB from database setting")
+ # Set dynamic MAX_CONTENT_LENGTH from DB settings. The Werkzeug
+ # ceiling is the higher of the two limits because audio-only video
+ # uploads can exceed max_file_size_mb (only the extracted audio
+ # has to fit that). The view-level handler re-checks each request
+ # against the right effective limit.
+ max_file_size_mb = int(SystemSetting.get_setting('max_file_size_mb', 250))
+ max_audio_only_video_mb = int(
+ SystemSetting.get_setting('max_audio_only_video_size_mb', max_file_size_mb * 4)
+ )
+ wsgi_ceiling_mb = max(max_file_size_mb, max_audio_only_video_mb)
+ app.config['MAX_CONTENT_LENGTH'] = wsgi_ceiling_mb * 1024 * 1024
+ app.logger.info(
+ f"Set MAX_CONTENT_LENGTH to {wsgi_ceiling_mb}MB "
+ f"(max_file_size_mb={max_file_size_mb}, "
+ f"max_audio_only_video_size_mb={max_audio_only_video_mb})"
+ )
# Initialize job queue for background processing
initialize_job_queue(app)
diff --git a/src/init_db.py b/src/init_db.py
index 563a43a0..c10015d9 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -162,6 +162,8 @@ def initialize_database(app):
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")
+ if add_column_if_not_exists(engine, 'recording', 'keep_audio_only', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added keep_audio_only column to recording table")
# Add columns to recording_tags for order tracking
if add_column_if_not_exists(engine, 'recording_tags', 'added_at', 'DATETIME'):
@@ -590,6 +592,23 @@ def initialize_database(app):
setting_type='integer'
)
app.logger.info("Initialized default max_file_size_mb setting")
+
+ if not SystemSetting.query.filter_by(key='max_audio_only_video_size_mb').first():
+ # Default to 4x the regular limit so a default deployment lets
+ # ~1 GB videos through when only the extracted audio will be
+ # kept. The actual transcribed/stored audio is still bounded by
+ # max_file_size_mb via the post-extraction size guard.
+ try:
+ base_mb = int(SystemSetting.get_setting('max_file_size_mb', '250'))
+ except (TypeError, ValueError):
+ base_mb = 250
+ SystemSetting.set_setting(
+ key='max_audio_only_video_size_mb',
+ value=str(base_mb * 4),
+ description='Maximum file size for video uploads in audio-only mode. Only the extracted audio is stored, so the upload itself can be much larger than max_file_size_mb.',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default max_audio_only_video_size_mb setting")
if not SystemSetting.query.filter_by(key='asr_timeout_seconds').first():
SystemSetting.set_setting(
diff --git a/src/models/recording.py b/src/models/recording.py
index 6c4bd767..bbd6ce5e 100644
--- a/src/models/recording.py
+++ b/src/models/recording.py
@@ -43,6 +43,13 @@ class Recording(db.Model):
error_message = db.Column(db.Text, nullable=True) # Store detailed error messages
file_hash = db.Column(db.String(64), nullable=True) # SHA-256 hash for duplicate detection
+ # Per-upload override for VIDEO_RETENTION. When True, the processing
+ # pipeline extracts audio and discards the video stream even if the
+ # server's VIDEO_RETENTION is on. Also signals that the upload was
+ # allowed to exceed max_file_size_mb because only the extracted audio
+ # has to fit that limit. See docs/admin-guide/configuration.md.
+ keep_audio_only = db.Column(db.Boolean, default=False, nullable=False)
+
# Auto-deletion and archival fields
audio_deleted_at = db.Column(db.DateTime, nullable=True) # When audio file was deleted (null = not deleted)
deletion_exempt = db.Column(db.Boolean, default=False) # Manual exemption from auto-deletion
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 1ae4313d..cbefc51b 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1551,6 +1551,12 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
current_app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
return
+ # Per-upload override: if keep_audio_only is set on the recording,
+ # treat VIDEO_RETENTION as off for this run regardless of the env
+ # var. Set at upload time (web or v1 API) and persists with the
+ # recording so re-processing/reprocess honours it too.
+ effective_video_retention = VIDEO_RETENTION and not getattr(recording, 'keep_audio_only', False)
+
try:
current_app.logger.info(f"Starting connector-based transcription for recording {recording_id}...")
recording.status = 'PROCESSING'
@@ -1608,12 +1614,12 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
# Video passthrough: send original video directly to ASR without audio extraction
current_app.logger.info(f"Video passthrough: sending original video to ASR (no audio extraction)")
actual_filepath = filepath # Send video as-is to connector
- if VIDEO_RETENTION:
+ if effective_video_retention:
# Also keep the video for playback
recording.audio_path = filepath
recording.mime_type = mimetypes.guess_type(filepath)[0] or 'video/mp4'
db.session.commit()
- elif VIDEO_RETENTION:
+ elif effective_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:
@@ -1855,7 +1861,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
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:
+ if is_video and effective_video_retention and audio_filepath and audio_filepath != filepath:
try:
if os.path.exists(audio_filepath):
os.remove(audio_filepath)
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 4f6f9f5a..1174593b 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -381,6 +381,20 @@ document.addEventListener('DOMContentLoaded', async () => {
const incognitoRecording = ref(null);
const incognitoProcessing = ref(false);
+ // --- Video / Audio-Only Upload State ---
+ // Server config: whether VIDEO_RETENTION is enabled. Controls
+ // toggle visibility (when on, the toggle is shown for video
+ // files; when off, the system always extracts audio and the
+ // toggle stays hidden — the larger size limit applies
+ // implicitly to video files).
+ const videoRetentionEnabled = ref(false);
+ // Per-upload override (toggle in the upload form). Sent as
+ // form field `keep_audio_only=true` when on, recorded on the
+ // Recording row, consumed by the processing pipeline.
+ const keepAudioOnly = ref(false);
+ // Server config: cap for audio-only-mode video uploads, in MB.
+ const maxAudioOnlyVideoSizeMB = ref(1000);
+
// --- Bulk Selection State ---
const selectionMode = ref(false);
const selectedRecordingIds = ref(new Set());
@@ -796,6 +810,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// Incognito Mode
enableIncognitoMode, incognitoMode, incognitoRecording, incognitoProcessing,
+ videoRetentionEnabled, keepAudioOnly, maxAudioOnlyVideoSizeMB,
// Bulk Selection
selectionMode, selectedRecordingIds, bulkActionInProgress,
@@ -2503,6 +2518,17 @@ document.addEventListener('DOMContentLoaded', async () => {
enableIncognitoMode.value = config.enable_incognito_mode === true;
foldersEnabled.value = config.enable_folders === true;
maxConcurrentUploads.value = config.max_concurrent_uploads || 3;
+ // Video / audio-only upload config. videoRetention from
+ // the server controls whether the "Keep audio only"
+ // toggle is shown; max_audio_only_video_size_mb sets
+ // the larger limit applied to video uploads in
+ // audio-only mode.
+ videoRetentionEnabled.value = config.video_retention === true;
+ if (typeof config.max_audio_only_video_size_mb === 'number') {
+ maxAudioOnlyVideoSizeMB.value = config.max_audio_only_video_size_mb;
+ } else if (config.max_audio_only_video_size_mb) {
+ maxAudioOnlyVideoSizeMB.value = parseInt(config.max_audio_only_video_size_mb, 10) || 1000;
+ }
// Per-upload transcription model dropdown options
// (issue #266). Only set when admin configured at least
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index f68490e2..6b256031 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -47,6 +47,8 @@ export function useUpload(state, utils) {
availableFolders, selectedFolderId,
// Incognito mode state
incognitoMode, incognitoRecording, incognitoProcessing,
+ // Video / audio-only upload state
+ videoRetentionEnabled, keepAudioOnly, maxAudioOnlyVideoSizeMB,
// View state
currentView,
// Upload disclaimer state
@@ -192,9 +194,25 @@ export function useUpload(state, utils) {
);
if (isAudioFile) {
- // Only check general file size limit
- if (fileObject.size > maxFileSizeMB.value * 1024 * 1024) {
- setGlobalError(t('upload.fileExceedsMaxSize', { name: fileObject.name, size: maxFileSizeMB.value }));
+ // Per-file effective size limit. A video file uploaded in
+ // audio-only mode (toggle on, or VIDEO_RETENTION off at
+ // the server) uses the larger limit, since only the
+ // extracted audio is stored. Everything else uses the
+ // regular limit.
+ const isVideoExt = /\.(mp4|mov|mkv|avi|webm|m4v|wmv|flv|ts|mts)$/i.test(fileObject.name);
+ const audioOnlyForThisFile = (
+ (videoRetentionEnabled && videoRetentionEnabled.value)
+ ? (keepAudioOnly && keepAudioOnly.value)
+ : true
+ );
+ const effectiveLimitMB = (isVideoExt && audioOnlyForThisFile && maxAudioOnlyVideoSizeMB)
+ ? maxAudioOnlyVideoSizeMB.value
+ : maxFileSizeMB.value;
+ if (fileObject.size > effectiveLimitMB * 1024 * 1024) {
+ const errKey = (isVideoExt && audioOnlyForThisFile)
+ ? 'upload.videoExceedsAudioOnlyMaxSize'
+ : 'upload.fileExceedsMaxSize';
+ setGlobalError(t(errKey, { name: fileObject.name, size: effectiveLimitMB }));
continue;
}
@@ -417,6 +435,22 @@ export function useUpload(state, utils) {
}
}
+ // Per-upload "keep audio only" override. True when the user
+ // toggled it explicitly (only visible when VIDEO_RETENTION is
+ // on at the server) OR implicitly when VIDEO_RETENTION is
+ // off AND the file is a video — in both cases the upload is
+ // allowed up to the larger audio-only video limit and the
+ // server discards the video stream.
+ const isVideoExt = /\.(mp4|mov|mkv|avi|webm|m4v|wmv|flv|ts|mts)$/i.test(fileItem.file.name);
+ const keepAudioOnlyForThisFile = (
+ (videoRetentionEnabled && videoRetentionEnabled.value)
+ ? !!(keepAudioOnly && keepAudioOnly.value)
+ : isVideoExt
+ );
+ if (keepAudioOnlyForThisFile) {
+ formData.append('keep_audio_only', 'true');
+ }
+
// Use XMLHttpRequest for per-file upload progress
const data = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
diff --git a/static/locales/de.json b/static/locales/de.json
index 644ab516..3b429097 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Rechtlicher Hinweis, der Benutzern vor Beginn der Aufnahme angezeigt wird. Unterstützt Markdown-Formatierung. Leer lassen zum Deaktivieren.",
"uploadDisclaimerDesc": "Rechtlicher Hinweis, der vor dem Hochladen von Dateien angezeigt wird. Unterstützt Markdown. Leer lassen zum Deaktivieren.",
"customBannerDesc": "Benutzerdefiniertes Banner oben auf der Seite. Unterstützt Markdown. Leer lassen zum Deaktivieren.",
- "transcriptLengthLimitDesc": "Maximale Anzahl von Zeichen, die vom Transkript an das LLM für Zusammenfassung und Chat gesendet werden. Verwenden Sie -1 für kein Limit."
+ "transcriptLengthLimitDesc": "Maximale Anzahl von Zeichen, die vom Transkript an das LLM für Zusammenfassung und Chat gesendet werden. Verwenden Sie -1 für kein Limit.",
+ "maxAudioOnlyVideoSizeDesc": "Maximale Dateigröße (in MB) für Video-Uploads im Nur-Audio-Modus. Nur das extrahierte Audio wird gespeichert, daher kann der Upload selbst größer als das normale Limit sein."
},
"storageUsed": "GENUTZTER SPEICHER",
"summarizationInstructions": "Zusammenfassungsanweisungen",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "{{count}} Datei(en) hochladen",
"uploadProgress": "Upload-Fortschritt",
"videoRetained": "Video für Wiedergabe beibehalten",
- "willAutoSummarize": "Wird nach der Transkription automatisch zusammengefasst"
+ "willAutoSummarize": "Wird nach der Transkription automatisch zusammengefasst",
+ "keepAudioOnly": "Nur Audio behalten",
+ "keepAudioOnlyHelp": "Verwirft den Videostream für diesen Upload. Ermöglicht das Hochladen größerer Videos als das normale Limit, solange das extrahierte Audio in das normale Limit passt.",
+ "videoAudioOnlyAuto": "Der Videostream wird nicht beibehalten.",
+ "videoExceedsAudioOnlyMaxSize": "Video „{{name}}“ überschreitet das Audio-only-Limit von {{size}} MB und wurde übersprungen."
},
"uploadProgress": {
"title": "Upload-Fortschritt"
diff --git a/static/locales/en.json b/static/locales/en.json
index 612b11f2..598b3912 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Legal disclaimer shown to users before recording starts. Supports Markdown formatting. Leave empty to disable.",
"uploadDisclaimerDesc": "Legal disclaimer shown before file uploads. Supports Markdown. Leave empty to disable.",
"customBannerDesc": "Custom banner shown at the top of the page. Supports Markdown. Leave empty to disable.",
- "transcriptLengthLimitDesc": "Maximum number of characters to send from transcript to LLM for summarization and chat. Use -1 for no limit."
+ "transcriptLengthLimitDesc": "Maximum number of characters to send from transcript to LLM for summarization and chat. Use -1 for no limit.",
+ "maxAudioOnlyVideoSizeDesc": "Maximum file size (in MB) for video uploads in audio-only mode. Only the extracted audio is stored, so the upload itself can be larger than the regular file-size limit."
},
"storageUsed": "STORAGE USED",
"summarizationInstructions": "Summarization Instructions",
@@ -1539,7 +1540,11 @@
"uploadNFiles": "Upload {{count}} File(s)",
"uploadProgress": "Upload Progress",
"videoRetained": "Video preserved for playback",
- "willAutoSummarize": "Will auto-summarize after transcription"
+ "willAutoSummarize": "Will auto-summarize after transcription",
+ "keepAudioOnly": "Keep audio only",
+ "keepAudioOnlyHelp": "Drop the video stream from this upload. Lets you upload videos larger than the regular size limit, as long as the extracted audio fits.",
+ "videoAudioOnlyAuto": "Video stream will not be kept.",
+ "videoExceedsAudioOnlyMaxSize": "Video \"{{name}}\" exceeds the audio-only maximum of {{size}} MB and was skipped."
},
"uploadProgress": {
"title": "Upload Progress"
diff --git a/static/locales/es.json b/static/locales/es.json
index 43f91d24..64c5326d 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Aviso legal mostrado a los usuarios antes de comenzar la grabación. Admite formato Markdown. Dejar vacío para desactivar.",
"uploadDisclaimerDesc": "Aviso legal mostrado antes de subir archivos. Admite Markdown. Dejar vacío para desactivar.",
"customBannerDesc": "Banner personalizado mostrado en la parte superior de la página. Admite Markdown. Dejar vacío para desactivar.",
- "transcriptLengthLimitDesc": "Número máximo de caracteres a enviar desde la transcripción al LLM para resumen y chat. Use -1 para sin límite."
+ "transcriptLengthLimitDesc": "Número máximo de caracteres a enviar desde la transcripción al LLM para resumen y chat. Use -1 para sin límite.",
+ "maxAudioOnlyVideoSizeDesc": "Tamaño máximo (en MB) para subidas de vídeo en modo solo audio. Solo se almacena el audio extraído, por lo que la subida en sí puede ser mayor que el límite habitual."
},
"storageUsed": "ALMACENAMIENTO USADO",
"summarizationInstructions": "Instrucciones de Resumen",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "Upload {{count}} File(s)",
"uploadProgress": "Progreso de Carga",
"videoRetained": "Video conservado para reproducción",
- "willAutoSummarize": "Se resumirá automáticamente después de la transcripción"
+ "willAutoSummarize": "Se resumirá automáticamente después de la transcripción",
+ "keepAudioOnly": "Conservar solo el audio",
+ "keepAudioOnlyHelp": "Descarta el flujo de vídeo de esta subida. Permite cargar vídeos más grandes que el límite habitual, siempre que el audio extraído no lo supere.",
+ "videoAudioOnlyAuto": "El flujo de vídeo no se conservará.",
+ "videoExceedsAudioOnlyMaxSize": "El vídeo «{{name}}» supera el máximo de solo audio de {{size}} MB y se omitió."
},
"uploadProgress": {
"title": "Progreso de Carga"
diff --git a/static/locales/fr.json b/static/locales/fr.json
index ec83537f..051561a6 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Avis légal affiché aux utilisateurs avant le début de l'enregistrement. Prend en charge le formatage Markdown. Laisser vide pour désactiver.",
"uploadDisclaimerDesc": "Avis légal affiché avant le téléchargement de fichiers. Prend en charge Markdown. Laisser vide pour désactiver.",
"customBannerDesc": "Bannière personnalisée affichée en haut de la page. Prend en charge Markdown. Laisser vide pour désactiver.",
- "transcriptLengthLimitDesc": "Nombre maximal de caractères à envoyer de la transcription au LLM pour le résumé et le chat. Utilisez -1 pour aucune limite."
+ "transcriptLengthLimitDesc": "Nombre maximal de caractères à envoyer de la transcription au LLM pour le résumé et le chat. Utilisez -1 pour aucune limite.",
+ "maxAudioOnlyVideoSizeDesc": "Taille maximale (en Mo) des envois vidéo en mode audio uniquement. Seul l’audio extrait est conservé, donc l’envoi lui-même peut dépasser la limite habituelle."
},
"storageUsed": "STOCKAGE UTILISÉ",
"summarizationInstructions": "Instructions de Résumé",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "Upload {{count}} File(s)",
"uploadProgress": "Progression du Téléchargement",
"videoRetained": "Vidéo conservée pour la lecture",
- "willAutoSummarize": "Résumé automatique après la transcription"
+ "willAutoSummarize": "Résumé automatique après la transcription",
+ "keepAudioOnly": "Conserver uniquement l’audio",
+ "keepAudioOnlyHelp": "Supprime le flux vidéo de cet envoi. Permet d’envoyer des vidéos plus grandes que la limite habituelle, tant que l’audio extrait y tient.",
+ "videoAudioOnlyAuto": "Le flux vidéo ne sera pas conservé.",
+ "videoExceedsAudioOnlyMaxSize": "La vidéo « {{name}} » dépasse le maximum audio uniquement de {{size}} Mo et a été ignorée."
},
"uploadProgress": {
"title": "Progression du Téléchargement"
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 2845d590..4e75282b 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Aviso legal mostrado aos usuários antes do início da gravação. Suporta formatação Markdown. Deixe em branco para desabilitar.",
"uploadDisclaimerDesc": "Aviso legal mostrado antes dos uploads de arquivo. Suporta Markdown. Deixe em branco para desabilitar.",
"customBannerDesc": "Banner personalizado mostrado no topo da página. Suporta Markdown. Deixe em branco para desabilitar.",
- "transcriptLengthLimitDesc": "Número máximo de caracteres para enviar da transcrição ao LLM para resumo e chat. Use -1 para nenhum limite."
+ "transcriptLengthLimitDesc": "Número máximo de caracteres para enviar da transcrição ao LLM para resumo e chat. Use -1 para nenhum limite.",
+ "maxAudioOnlyVideoSizeDesc": "Tamanho máximo (em MB) para envios de vídeo em modo apenas-áudio. Apenas o áudio extraído é armazenado, portanto o envio em si pode ser maior que o limite habitual."
},
"storageUsed": "ARMAZENAMENTO USADO",
"summarizationInstructions": "Instruções de Resumo",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "Enviar {{count}} Arquivo(s)",
"uploadProgress": "Progresso do Envio",
"videoRetained": "Vídeo preservado para reprodução",
- "willAutoSummarize": "Será resumido automaticamente após a transcrição"
+ "willAutoSummarize": "Será resumido automaticamente após a transcrição",
+ "keepAudioOnly": "Manter apenas o áudio",
+ "keepAudioOnlyHelp": "Descartar o fluxo de vídeo neste envio. Permite enviar vídeos maiores que o limite habitual, contanto que o áudio extraído caiba no limite.",
+ "videoAudioOnlyAuto": "O fluxo de vídeo não será mantido.",
+ "videoExceedsAudioOnlyMaxSize": "O vídeo “{{name}}” excede o máximo apenas-áudio de {{size}} MB e foi ignorado."
},
"uploadProgress": {
"title": "Progresso do Envio"
diff --git a/static/locales/ru.json b/static/locales/ru.json
index ecc30cca..6464f167 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "Юридическое предупреждение, показываемое пользователям перед началом записи. Поддерживает форматирование Markdown. Оставьте пустым, чтобы отключить.",
"uploadDisclaimerDesc": "Юридическое предупреждение, показываемое перед загрузкой файлов. Поддерживает Markdown. Оставьте пустым, чтобы отключить.",
"customBannerDesc": "Пользовательский баннер в верхней части страницы. Поддерживает Markdown. Оставьте пустым, чтобы отключить.",
- "transcriptLengthLimitDesc": "Максимальное количество символов транскрипта для отправки в LLM для резюмирования и чата. Используйте -1 для отсутствия ограничений."
+ "transcriptLengthLimitDesc": "Максимальное количество символов транскрипта для отправки в LLM для резюмирования и чата. Используйте -1 для отсутствия ограничений.",
+ "maxAudioOnlyVideoSizeDesc": "Максимальный размер (в МБ) для загрузки видео в режиме только-аудио. Сохраняется только извлечённый звук, поэтому сама загрузка может превышать обычный лимит."
},
"storageUsed": "ИСПОЛЬЗОВАНО ХРАНИЛИЩА",
"summarizationInstructions": "Инструкции для резюмирования",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "Upload {{count}} File(s)",
"uploadProgress": "Прогресс загрузки",
"videoRetained": "Видео сохранено для воспроизведения",
- "willAutoSummarize": "Автоматически создаст резюме после транскрибирования"
+ "willAutoSummarize": "Автоматически создаст резюме после транскрибирования",
+ "keepAudioOnly": "Сохранить только аудио",
+ "keepAudioOnlyHelp": "Отбросить видеопоток в этой загрузке. Позволяет загружать видео больше обычного лимита, если извлечённый звук вписывается.",
+ "videoAudioOnlyAuto": "Видеопоток сохранён не будет.",
+ "videoExceedsAudioOnlyMaxSize": "Видео «{{name}}» превышает лимит только для аудио в {{size}} МБ и было пропущено."
},
"uploadProgress": {
"title": "Прогресс загрузки"
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 07348abf..3dec6140 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -237,7 +237,8 @@
"recordingDisclaimerDesc": "录音开始前向用户显示的法律免责声明。支持 Markdown 格式。留空以禁用。",
"uploadDisclaimerDesc": "文件上传前显示的法律免责声明。支持 Markdown。留空以禁用。",
"customBannerDesc": "页面顶部显示的自定义横幅。支持 Markdown。留空以禁用。",
- "transcriptLengthLimitDesc": "从转录发送到 LLM 进行摘要和聊天的最大字符数。使用 -1 表示无限制。"
+ "transcriptLengthLimitDesc": "从转录发送到 LLM 进行摘要和聊天的最大字符数。使用 -1 表示无限制。",
+ "maxAudioOnlyVideoSizeDesc": "仅音频模式下视频上传的最大文件大小(MB)。仅保留提取出的音频,因此上传文件本身可以大于常规限制。"
},
"storageUsed": "已用存储",
"summarizationInstructions": "摘要说明",
@@ -1530,7 +1531,11 @@
"uploadNFiles": "Upload {{count}} File(s)",
"uploadProgress": "上传进度",
"videoRetained": "视频已保留供播放",
- "willAutoSummarize": "转录后将自动生成摘要"
+ "willAutoSummarize": "转录后将自动生成摘要",
+ "keepAudioOnly": "仅保留音频",
+ "keepAudioOnlyHelp": "在本次上传中丢弃视频流。只要提取出的音频未超过常规限制,就可以上传体积远大于常规限制的视频。",
+ "videoAudioOnlyAuto": "不会保留视频流。",
+ "videoExceedsAudioOnlyMaxSize": "视频 “{{name}}” 超出仅音频上限 {{size}} MB,已跳过。"
},
"uploadProgress": {
"title": "上传进度"
diff --git a/templates/admin.html b/templates/admin.html
index 292b0b12..79325b03 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -2219,6 +2219,7 @@ Summarization Instructions:
const settingOrder = [
'transcript_length_limit',
'max_file_size_mb',
+ 'max_audio_only_video_size_mb',
'asr_timeout_seconds',
'admin_default_summary_prompt',
'recording_disclaimer',
@@ -2536,6 +2537,7 @@ Summarization Instructions:
const descriptionKeys = {
'transcript_length_limit': 'adminDashboard.settings.transcriptLengthLimitDesc',
'max_file_size_mb': 'adminDashboard.settings.maxFileSizeDesc',
+ 'max_audio_only_video_size_mb': 'adminDashboard.settings.maxAudioOnlyVideoSizeDesc',
'asr_timeout_seconds': 'adminDashboard.settings.asrTimeoutDesc',
'admin_default_summary_prompt': 'adminDashboard.settings.defaultSummaryPromptDesc',
'recording_disclaimer': 'adminDashboard.settings.recordingDisclaimerDesc',
diff --git a/templates/components/upload-view.html b/templates/components/upload-view.html
index 134d29b2..5918505d 100644
--- a/templates/components/upload-view.html
+++ b/templates/components/upload-view.html
@@ -29,17 +29,28 @@
</div>
<div class="space-y-1 max-h-32 overflow-y-auto">
<div v-for="item in pendingQueueFiles" :key="item.clientId"
- class="flex items-center justify-between px-2 py-1.5 bg-[var(--bg-tertiary)] rounded border border-[var(--border-secondary)]">
- <div class="flex items-center gap-1.5 min-w-0 flex-1">
- <i class="fas fa-file-audio text-[var(--text-muted)] text-xs"></i>
- <span class="text-xs text-[var(--text-primary)] truncate">${item.file.name}</span>
- <span class="text-[10px] text-[var(--text-muted)] flex-shrink-0">(${formatFileSize(item.file.size)})</span>
+ class="flex flex-col gap-0.5 px-2 py-1.5 bg-[var(--bg-tertiary)] rounded border border-[var(--border-secondary)]">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-1.5 min-w-0 flex-1">
+ <i class="fas fa-file-audio text-[var(--text-muted)] text-xs"></i>
+ <span class="text-xs text-[var(--text-primary)] truncate">${item.file.name}</span>
+ <span class="text-[10px] text-[var(--text-muted)] flex-shrink-0">(${formatFileSize(item.file.size)})</span>
+ </div>
+ <button @click="removeFromQueue(item.clientId)"
+ class="ml-1.5 p-0.5 text-[var(--text-muted)] hover:text-red-500 transition-colors flex-shrink-0"
+ title="Remove from queue">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+ </div>
+ <!-- Inline hint when VIDEO_RETENTION is off at the
+ server. Shows on each video file so users
+ aren't surprised the video stream is dropped
+ and that the larger size limit applies. -->
+ <div v-if="!videoRetentionEnabled && /\.(mp4|mov|mkv|avi|webm|m4v|wmv|flv|ts|mts)$/i.test(item.file.name)"
+ class="flex items-center gap-1 pl-5 text-[10px] text-emerald-700 dark:text-emerald-400">
+ <i class="fas fa-volume-up"></i>
+ <span>${ t('upload.videoAudioOnlyAuto') }</span>
</div>
- <button @click="removeFromQueue(item.clientId)"
- class="ml-1.5 p-0.5 text-[var(--text-muted)] hover:text-red-500 transition-colors flex-shrink-0"
- title="Remove from queue">
- <i class="fas fa-times text-xs"></i>
- </button>
</div>
</div>
@@ -85,6 +96,50 @@
</button>
</div>
+ <!-- Keep audio only toggle. Shown only when VIDEO_RETENTION
+ is enabled at the server AND the queue contains at
+ least one video file. When off, videos in the queue
+ get the larger audio-only size limit automatically
+ (the hint on each video row makes that visible). -->
+ <div v-if="videoRetentionEnabled && uploadQueue.some(item => item.file && /\.(mp4|mov|mkv|avi|webm|m4v|wmv|flv|ts|mts)$/i.test(item.file.name))"
+ class="mt-3">
+ <button @click="keepAudioOnly = !keepAudioOnly"
+ :class="[
+ 'w-full flex items-center justify-between px-3 py-2.5 rounded-lg border transition-all duration-200',
+ keepAudioOnly
+ ? 'bg-gradient-to-r from-emerald-500/10 to-teal-500/10 border-emerald-400/50 dark:border-emerald-500/50'
+ : 'bg-[var(--bg-tertiary)] border-[var(--border-secondary)] hover:border-[var(--border-focus)]'
+ ]">
+ <div class="flex items-center gap-3">
+ <div :class="[
+ 'w-8 h-8 rounded-full flex items-center justify-center transition-all',
+ keepAudioOnly
+ ? 'bg-gradient-to-br from-emerald-500 to-teal-600 text-white'
+ : 'bg-[var(--bg-secondary)] text-[var(--text-muted)]'
+ ]">
+ <i class="fas fa-volume-up text-sm"></i>
+ </div>
+ <div class="text-left">
+ <span :class="['text-sm font-medium', keepAudioOnly ? 'text-emerald-700 dark:text-emerald-300' : 'text-[var(--text-secondary)]']">
+ ${ t('upload.keepAudioOnly') }
+ </span>
+ <p class="text-[10px] text-[var(--text-muted)] leading-tight mt-0.5">
+ ${ t('upload.keepAudioOnlyHelp') }
+ </p>
+ </div>
+ </div>
+ <div :class="[
+ 'w-10 h-5 rounded-full relative transition-all duration-200 flex-shrink-0',
+ keepAudioOnly ? 'bg-gradient-to-r from-emerald-500 to-teal-500' : 'bg-[var(--bg-secondary)]'
+ ]">
+ <div :class="[
+ 'absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-all duration-200',
+ keepAudioOnly ? 'left-5' : 'left-0.5'
+ ]"></div>
+ </div>
+ </button>
+ </div>
+
<!-- Upload Buttons -->
<div class="mt-2 space-y-2">
<!-- Normal Upload Button (when not in incognito mode or feature disabled) -->
diff --git a/tests/test_video_passthrough.py b/tests/test_video_passthrough.py
index eb2c133b..aeec7363 100644
--- a/tests/test_video_passthrough.py
+++ b/tests/test_video_passthrough.py
@@ -134,10 +134,10 @@ class TestProcessingMainPath(unittest.TestCase):
after_video = PROCESSING_MAIN[video_block_start:]
passthrough_pos = after_video.find('if VIDEO_PASSTHROUGH_ASR:')
- retention_pos = after_video.find('elif VIDEO_RETENTION:')
+ retention_pos = after_video.find('elif effective_video_retention:')
self.assertNotEqual(passthrough_pos, -1, "Missing VIDEO_PASSTHROUGH_ASR check in is_video block")
- self.assertNotEqual(retention_pos, -1, "Missing elif VIDEO_RETENTION check")
+ self.assertNotEqual(retention_pos, -1, "Missing elif effective_video_retention check")
self.assertLess(passthrough_pos, retention_pos,
"VIDEO_PASSTHROUGH_ASR should be checked before VIDEO_RETENTION")
@@ -146,7 +146,7 @@ class TestProcessingMainPath(unittest.TestCase):
video_block = PROCESSING_MAIN[PROCESSING_MAIN.find('if is_video:'):]
# Find the passthrough branch (from `if VIDEO_PASSTHROUGH_ASR:` to `elif VIDEO_RETENTION:`)
pt_start = video_block.find('if VIDEO_PASSTHROUGH_ASR:')
- pt_end = video_block.find('elif VIDEO_RETENTION:')
+ pt_end = video_block.find('elif effective_video_retention:')
passthrough_block = video_block[pt_start:pt_end]
self.assertNotIn('extract_audio_from_video', passthrough_block,
"Passthrough branch should NOT extract audio")
@@ -155,7 +155,7 @@ class TestProcessingMainPath(unittest.TestCase):
"""Passthrough sets actual_filepath = filepath (the original video)."""
video_block = PROCESSING_MAIN[PROCESSING_MAIN.find('if is_video:'):]
pt_start = video_block.find('if VIDEO_PASSTHROUGH_ASR:')
- pt_end = video_block.find('elif VIDEO_RETENTION:')
+ pt_end = video_block.find('elif effective_video_retention:')
passthrough_block = video_block[pt_start:pt_end]
self.assertIn('actual_filepath = filepath', passthrough_block)
@@ -163,9 +163,9 @@ class TestProcessingMainPath(unittest.TestCase):
"""When both passthrough and retention are on, recording.audio_path is set."""
video_block = PROCESSING_MAIN[PROCESSING_MAIN.find('if is_video:'):]
pt_start = video_block.find('if VIDEO_PASSTHROUGH_ASR:')
- pt_end = video_block.find('elif VIDEO_RETENTION:')
+ pt_end = video_block.find('elif effective_video_retention:')
passthrough_block = video_block[pt_start:pt_end]
- self.assertIn('if VIDEO_RETENTION:', passthrough_block,
+ self.assertIn('if effective_video_retention:', passthrough_block,
"Passthrough branch should conditionally handle retention")
self.assertIn('recording.audio_path = filepath', passthrough_block)
self.assertIn("mimetypes.guess_type(filepath)", passthrough_block)
@@ -215,7 +215,7 @@ class TestRetentionNotBroken(unittest.TestCase):
def test_retention_branch_still_extracts_audio(self):
"""elif VIDEO_RETENTION branch still calls extract_audio_from_video."""
video_block = PROCESSING_MAIN[PROCESSING_MAIN.find('if is_video:'):]
- ret_start = video_block.find('elif VIDEO_RETENTION:')
+ ret_start = video_block.find('elif effective_video_retention:')
# Find next else: at the same indent level
after_ret = video_block[ret_start:]
else_pos = after_ret.find('\n else:')
@@ -230,8 +230,11 @@ class TestRetentionNotBroken(unittest.TestCase):
self.assertIn('extract_audio_from_video(filepath)', video_block)
def test_temp_audio_cleanup_still_present(self):
- """Temp audio from retention is still cleaned up after transcription."""
- self.assertIn('is_video and VIDEO_RETENTION and audio_filepath', PROCESSING_MAIN)
+ """Temp audio from retention is still cleaned up after transcription.
+ After the per-upload keep_audio_only override landed, the cleanup
+ branch checks effective_video_retention (env var AND per-recording
+ flag) rather than VIDEO_RETENTION directly."""
+ self.assertIn('is_video and effective_video_retention and audio_filepath', PROCESSING_MAIN)
self.assertIn('Cleaned up temp audio from video retention', PROCESSING_MAIN)
@@ -285,11 +288,25 @@ class TestUploadHandlerPassthrough(unittest.TestCase):
"""Test recordings.py upload handler respects VIDEO_PASSTHROUGH_ASR."""
def test_skip_conversion_for_passthrough_video(self):
- """Upload handler skips conversion when passthrough or retention + video."""
- self.assertIn('VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR) and has_video', RECORDINGS)
+ """Upload handler skips conversion when passthrough is on OR
+ retention is on AND the per-upload keep_audio_only override is
+ off, and the file has video. The decision shape changed when
+ the per-upload override landed."""
+ # The new decision string keeps VIDEO_PASSTHROUGH_ASR as an
+ # admin-level escape hatch and gates retention on the per-upload
+ # keep_audio_only flag.
+ self.assertIn('VIDEO_PASSTHROUGH_ASR', RECORDINGS)
+ self.assertIn('VIDEO_RETENTION and not keep_audio_only_flag', RECORDINGS)
+ # The extension fallback (used when ffprobe fails) still uses
+ # the original `or` shape since it predates the upload decision.
+ self.assertIn('VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR', RECORDINGS)
def test_extension_fallback_checks_passthrough(self):
- """Extension-based video detection also fires for VIDEO_PASSTHROUGH_ASR."""
+ """Extension-based video detection also fires for VIDEO_PASSTHROUGH_ASR.
+ This check predates the keep_audio_only override and stays as-is
+ because the extension fallback only decides whether `has_video`
+ should be treated as True when ffprobe failed; the per-upload
+ keep_audio_only logic runs afterwards."""
self.assertIn('VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR', RECORDINGS)
def test_convert_if_needed_still_in_else(self):
@@ -411,7 +428,7 @@ class TestInteractionMatrix(unittest.TestCase):
video_block = PROCESSING_MAIN[PROCESSING_MAIN.find('if is_video:'):]
# All three branches present in order
pt_pos = video_block.find('if VIDEO_PASSTHROUGH_ASR:')
- ret_pos = video_block.find('elif VIDEO_RETENTION:')
+ ret_pos = video_block.find('elif effective_video_retention:')
else_pos = video_block.find('\n else:', ret_pos)
self.assertNotEqual(pt_pos, -1)
self.assertNotEqual(ret_pos, -1)
diff --git a/tests/test_video_retention.py b/tests/test_video_retention.py
index c4a25e70..638205e1 100644
--- a/tests/test_video_retention.py
+++ b/tests/test_video_retention.py
@@ -78,9 +78,24 @@ class TestProcessingPipelineVideoRetention(unittest.TestCase):
"""When VIDEO_RETENTION=False, extract_audio_from_video is called with default cleanup."""
self.assertIn('extract_audio_from_video(filepath)', self.content)
+ def test_effective_video_retention_combines_env_and_per_recording_flag(self):
+ """The processing task derives `effective_video_retention` from
+ BOTH the env var AND the per-recording keep_audio_only flag.
+ This is what lets a single upload opt out of retention even when
+ VIDEO_RETENTION is on globally."""
+ self.assertIn(
+ "effective_video_retention = VIDEO_RETENTION and not getattr(recording, 'keep_audio_only', False)",
+ 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)
+ """Temp audio from video retention is cleaned up after transcription.
+
+ After the per-upload keep_audio_only override was added, the
+ cleanup branch checks the effective (per-recording) retention
+ flag rather than the global env var directly.
+ """
+ self.assertIn('is_video and effective_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):
@@ -107,9 +122,52 @@ class TestUploadHandlerVideoRetention(unittest.TestCase):
with open(os.path.join(PROJECT_ROOT, 'src/api/recordings.py'), 'r') as f:
cls.content = f.read()
+ def test_upload_handler_parses_keep_audio_only_form_field(self):
+ """The new per-upload `keep_audio_only` form field is parsed at
+ the top of the upload handler. Without this parse, the override
+ is silently ignored."""
+ self.assertIn(
+ "request.form.get('keep_audio_only', 'false').lower() == 'true'",
+ self.content,
+ )
+ self.assertIn('keep_audio_only_flag', self.content)
+ self.assertIn('effective_audio_only', self.content)
+
+ def test_upload_handler_uses_separate_size_limit_for_audio_only_video(self):
+ """When the upload is in audio-only mode AND the file extension
+ looks like video, the size gate uses max_audio_only_video_size_mb
+ instead of max_file_size_mb. The post-extraction guard then
+ ensures the stored audio still fits the regular limit."""
+ # The audio-only-video limit must be read from the SystemSetting,
+ # not hardcoded.
+ self.assertIn(
+ "SystemSetting.get_setting('max_audio_only_video_size_mb'",
+ self.content,
+ )
+ # Effective limit must split on the (audio_only AND video) condition.
+ self.assertIn('effective_audio_only and is_likely_video_by_ext', self.content)
+ # And the post-extraction size guard must still cap the stored
+ # audio against the regular limit.
+ self.assertIn('regular_limit_mb * 1024 * 1024', self.content)
+ self.assertIn('extracted_audio_mb', self.content)
+
+ def test_upload_handler_persists_keep_audio_only_on_recording(self):
+ """The recording row stores the effective audio-only flag so the
+ processing task and reprocess flows honour it."""
+ self.assertIn('keep_audio_only=effective_audio_only', self.content)
+
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 or VIDEO_PASSTHROUGH_ASR) and has_video', self.content)
+ """Upload handler skips convert_if_needed for videos when retention
+ is on AND the per-upload keep_audio_only override is off.
+
+ The exact decision string changed when the per-upload override
+ landed; this test pins the new shape.
+ """
+ # The decision must factor in keep_audio_only_flag so a single
+ # upload can opt out of retention even when VIDEO_RETENTION=True.
+ self.assertIn('VIDEO_RETENTION and not keep_audio_only_flag', self.content)
+ # And the "skip conversion" log line is still the marker that
+ # the keep-video branch was taken.
self.assertIn('skipping conversion', self.content)
def test_upload_handler_has_video_from_codec_info(self):
@@ -312,21 +370,30 @@ class TestVideoRetentionMatrix(unittest.TestCase):
return f.read()
def test_processing_has_both_branches(self):
- """processing.py has both VIDEO_RETENTION=True and False branches for video."""
+ """processing.py has both retention=on and retention=off branches
+ for video. After the per-upload keep_audio_only override landed,
+ the decision is `effective_video_retention` (derived from the env
+ var AND the recording's keep_audio_only field) rather than
+ VIDEO_RETENTION directly.
+ """
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
+ # The effective flag must be derived from both the env var and
+ # the per-recording override.
+ self.assertIn('effective_video_retention = VIDEO_RETENTION and not', content)
+ # And it must be the gate inside the is_video block.
+ self.assertIn('elif effective_video_retention:', content)
+ # The else branch (extract audio + delete original) must still
+ # follow somewhere.
lines = content.split('\n')
- found_retention_if = False
+ found_retention_branch = 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:'):
+ if 'elif effective_video_retention:' in line:
+ found_retention_branch = True
+ elif found_retention_branch 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")
+ self.assertTrue(found_else_after, "Missing else branch after effective_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."""
@@ -346,11 +413,17 @@ class TestVideoRetentionMatrix(unittest.TestCase):
"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."""
+ """All entry points (upload, file monitor, processing) honour
+ video retention. The web upload and the processing task also
+ honour the per-recording keep_audio_only override; file monitor
+ does not (it has no per-file override surface)."""
for rel_path, marker in [
- ('src/api/recordings.py', '(VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR) and has_video'),
+ # Upload handler: per-upload override factored in.
+ ('src/api/recordings.py', 'VIDEO_RETENTION and not keep_audio_only_flag'),
+ # File monitor: still global-only, no per-file override.
('src/file_monitor.py', '(VIDEO_PASSTHROUGH_ASR or VIDEO_RETENTION) and has_video'),
- ('src/tasks/processing.py', 'if VIDEO_RETENTION:'),
+ # Processing task: effective flag (env var AND per-recording).
+ ('src/tasks/processing.py', 'elif effective_video_retention:'),
]:
content = self._read_file(rel_path)
self.assertIn(marker, content, f"Missing video retention guard in {rel_path}")