Skip to content

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

Python

Pass allow_debug_copy through the processing extract_audio_from_video wrapper so incognito video uploads work, and keep FFmpeg output out of the incognito error (#482)

Murtaza Nasir2e61b6986325
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 489f50ab..c799eb20 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1214,7 +1214,7 @@ You must respond with valid JSON format only."""
db.session.rollback()
-def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_original=True):
+def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_original=True, allow_debug_copy=True):
"""Extract audio from video containers using FFmpeg.
Behavior depends on AUDIO_COMPRESS_UPLOADS setting AND codec support:
@@ -1226,6 +1226,8 @@ def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_origin
video_filepath: Path to input video file
output_format: Audio format ('mp3', 'wav', 'flac', 'copy'), default 'mp3'
cleanup_original: If True, deletes original video after extraction
+ allow_debug_copy: Passed to the FFmpeg helper; incognito passes False so
+ no PRESERVE_TEMP_AUDIO copy outlives the request
Returns:
tuple: (audio_filepath, mime_type)
@@ -1262,7 +1264,8 @@ def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_origin
output_format=AUDIO_CODEC,
bitrate=AUDIO_BITRATE,
cleanup_original=cleanup_original,
- copy_stream=False
+ copy_stream=False,
+ allow_debug_copy=allow_debug_copy,
)
elif can_copy_stream:
# Copy audio stream without re-encoding (fast, preserves quality)
@@ -1271,7 +1274,8 @@ def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_origin
video_filepath,
output_format='copy',
cleanup_original=cleanup_original,
- copy_stream=True
+ copy_stream=True,
+ allow_debug_copy=allow_debug_copy,
)
else:
# Codec not supported - must re-encode for compatibility
@@ -1281,7 +1285,8 @@ def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_origin
output_format=AUDIO_CODEC,
bitrate=AUDIO_BITRATE,
cleanup_original=cleanup_original,
- copy_stream=False
+ copy_stream=False,
+ allow_debug_copy=allow_debug_copy,
)
current_app.logger.info(f"Successfully extracted audio to {audio_filepath}")
@@ -1289,10 +1294,10 @@ def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_origin
except FFmpegNotFoundError as e:
current_app.logger.error(str(e))
- raise Exception("Audio conversion tool (FFmpeg) not found on server.")
+ raise Exception("Audio conversion tool (FFmpeg) not found on server.") from e
except FFmpegError as e:
current_app.logger.error(f"FFmpeg audio extraction failed for {video_filepath}: {str(e)}")
- raise Exception(f"Audio extraction failed: {str(e)}")
+ raise Exception(f"Audio extraction failed: {str(e)}") from e
except Exception as e:
current_app.logger.error(f"Error extracting audio from {video_filepath}: {str(e)}")
raise
@@ -2566,7 +2571,14 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
_incognito_derived_files.append(audio_filepath)
except Exception as e:
current_app.logger.error(f"[Incognito] Failed to extract audio from video: {e}")
- raise
+ # The message carries FFmpeg's output (its build and the
+ # temp path): answer from the FFmpeg error it wraps, or
+ # with a fixed message (#482).
+ if isinstance(e, FFmpegError):
+ raise
+ if isinstance(e.__cause__, FFmpegError):
+ raise e.__cause__ from None
+ raise Exception("Audio extraction failed.") from e
# Convert audio format if needed
if video_passthrough_active:
diff --git a/tests/test_incognito_settings.py b/tests/test_incognito_settings.py
index 3a5504d8..b2dd92aa 100644
--- a/tests/test_incognito_settings.py
+++ b/tests/test_incognito_settings.py
@@ -4,10 +4,16 @@ It used to pass the form's empty language straight through (so the user's
language never applied), and it skipped the account and admin hotwords and
initial prompt and the ASR speaker-count defaults. Nothing is stored either way.
+An incognito video goes through the real extraction chain with only the
+ffmpeg and ffprobe binaries faked, so a signature mismatch between the
+wrappers fails here.
+
SHARED-DB: the user and admin setting are restored afterwards.
"""
+import io
import os
+import subprocess
import sys
import uuid
from unittest.mock import MagicMock, patch
@@ -20,6 +26,8 @@ from src.app import app, db
from src.models import SystemSetting, User
import src.tasks.processing as proc
+app.config["WTF_CSRF_ENABLED"] = False
+
@pytest.fixture
def user():
@@ -88,3 +96,77 @@ def test_incognito_decode_failure_reports_a_fixed_message(user, tmp_path):
assert result["error"] == AUDIO_DECODE_FAILED_MESSAGE
assert result["error_code"] == "audio_decode_failed"
assert connector.transcribe.call_count == 0
+
+
+_FFMPEG_BANNER = (b"ffmpeg version n8.1.3 Copyright (c) 2000-2026 the FFmpeg developers\n"
+ b" configuration: --enable-gpl\n"
+ b"Error opening input file /tmp/tmpabc.mp4.\n"
+ b"Error opening input files: Invalid data found when processing input\n")
+
+
+def _fake_probe(filename, cmd='ffprobe', timeout=None):
+ """ffprobe's JSON: a video with AAC audio, or the extracted audio file."""
+ audio = {"codec_type": "audio", "codec_name": "aac" if filename.endswith(".mp4") else "mp3",
+ "sample_rate": "44100", "channels": 1}
+ streams = [audio]
+ if filename.endswith(".mp4"):
+ streams.insert(0, {"codec_type": "video", "codec_name": "h264"})
+ return {"streams": streams, "format": {"format_name": "mov,mp4" if filename.endswith(".mp4") else "mp3",
+ "duration": "30.0"}}
+
+
+def _post_incognito_video(user_id, ffmpeg):
+ """POST a video to the incognito route; only ffmpeg/ffprobe and the ASR service are faked."""
+ connector = MagicMock(PROVIDER_NAME="test", supports_diarization=False, default_diarize=False)
+ connector.specifications = MagicMock(max_duration_seconds=1800, handles_chunking_internally=False,
+ recommended_chunk_seconds=600, unsupported_codecs=[],
+ preserve_original_audio=False)
+ response = MagicMock(text="hello world transcript", segments=None, speakers=None, speaker_embeddings=None)
+ response.has_diarization.return_value = False
+ connector.transcribe.return_value = response
+ registry = MagicMock()
+ registry.get_active_connector.return_value = connector
+ client = app.test_client()
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user_id)
+ with patch("src.api.recordings.ENABLE_INCOGNITO_MODE", True), \
+ patch("src.services.transcription.get_registry", return_value=registry), \
+ patch.object(proc, "VIDEO_PASSTHROUGH_ASR", False), \
+ patch.object(proc, "chunking_service", None), patch.object(proc, "client", None), \
+ patch("src.utils.ffprobe.probe", side_effect=_fake_probe), \
+ patch("src.utils.ffmpeg_utils.subprocess.run", side_effect=ffmpeg) as run:
+ resp = client.post("/api/recordings/incognito",
+ data={"file": (io.BytesIO(b"\x00" * 4096), "meeting.mp4")},
+ content_type="multipart/form-data")
+ return resp, run, connector
+
+
+def test_incognito_video_is_extracted_through_the_real_chain(user):
+ def ffmpeg(cmd, **kwargs):
+ with open(cmd[-1], "wb") as out: # the output file ffmpeg would write
+ out.write(b"\xff\xfb" * 1024)
+ return subprocess.CompletedProcess(cmd, 0, b"", b"")
+
+ # allow_debug_copy=False reaches the FFmpeg helper: no debug copy of the audio.
+ with patch.dict(os.environ, {"PRESERVE_TEMP_AUDIO": "true"}), patch("shutil.copy2") as copy2:
+ resp, run, connector = _post_incognito_video(user, ffmpeg)
+ assert copy2.call_count == 0
+ assert resp.status_code == 200, resp.get_json()
+ assert resp.get_json()["transcription"] == "hello world transcript"
+ extraction = run.call_args_list[0].args[0]
+ assert extraction[0] == "ffmpeg" and "-vn" in extraction
+ sent = connector.transcribe.call_args.args[0]
+ assert sent.filename.endswith((".mp3", ".m4a", ".flac", ".opus"))
+
+
+def test_incognito_video_extraction_failure_keeps_ffmpeg_output_out(user):
+ def ffmpeg(cmd, **kwargs):
+ raise subprocess.CalledProcessError(1, cmd, output=b"", stderr=_FFMPEG_BANNER)
+
+ resp, _, connector = _post_incognito_video(user, ffmpeg)
+ assert resp.status_code == 400
+ body = resp.get_json()
+ assert body["code"] == "audio_decode_failed"
+ text = resp.get_data(as_text=True).lower()
+ assert "ffmpeg" not in text and "/tmp/" not in text
+ assert connector.transcribe.call_count == 0