Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Refuse an undecodable incognito audio file with 400 and answer incognito transcription errors with the plain message of their kind, not the service text (#482)
Murtaza Nasir8f6ccfcc31b1
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex d4bd7cdd..85148905 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -3161,7 +3161,8 @@ def upload_incognito():}), 400return jsonify({'incognito': True,- 'error': result['error']+ 'error': result['error'],+ 'error_type': result.get('error_type'),}), 500# Optionally generate summarydiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex c799eb20..ed13ae49 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -2607,6 +2607,10 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speakeractual_filepath = conversion_result.output_pathactual_content_type = conversion_result.mime_typeactual_filename = os.path.basename(conversion_result.output_path)+ except FFmpegError:+ # A file FFmpeg cannot decode is refused as on upload (#482),+ # not sent to the transcription service as it is.+ raiseexcept Exception as e:current_app.logger.warning(f"[Incognito] Audio conversion check failed: {e}, proceeding with original")@@ -2713,7 +2717,14 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speakerresult['error'] = AUDIO_DECODE_FAILED_MESSAGEresult['error_code'] = 'audio_decode_failed'else:- result['error'] = str(e)+ # The service's own text can carry upstream detail. The answer is+ # the plain explanation a failed job shows for a known kind of+ # error, and a fixed message otherwise.+ from src.utils.error_formatting import format_error_for_user+ formatted = format_error_for_user(str(e))+ known = formatted['is_known'] or formatted['type'] != 'unknown'+ result['error'] = formatted['message'] if known else 'The transcription could not be completed.'+ result['error_type'] = formatted['type']result['processing_time_seconds'] = int(time.time() - start_time)return resultdiff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 419c389f..44974f18 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -1171,6 +1171,7 @@ export function useUpload(state, utils) {if (!response.ok || data.error) {const err = new Error(data.error || `Processing failed with status ${response.status}`);err.code = data.code;+ err.errorType = data.error_type;throw err;}@@ -1223,7 +1224,7 @@ export function useUpload(state, utils) {} catch (error) {console.error('[Incognito] Processing failed:', error);- const friendlyErr = getFriendlyError(error.message, t, error.code);+ const friendlyErr = getFriendlyError(error.message, t, error.code, error.errorType);setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);fileItem.status = 'failed';fileItem.error = error.message;diff --git a/static/js/modules/utils/upload-errors.js b/static/js/modules/utils/upload-errors.jsindex 1a6768a9..66d41943 100644--- a/static/js/modules/utils/upload-errors.js+++ b/static/js/modules/utils/upload-errors.js@@ -5,7 +5,9 @@* The server's `code` decides when there is one (#482): the message text can* already be localized, and an unreadable file must not fall through to the* generic "try reprocessing the recording", since no recording was created.- * Without a code, the message text is matched against the patterns below.+ * An incognito transcription error carries the server's error type instead+ * (src/utils/error_formatting.py); its message is a fixed English text.+ * Without either, the message text is matched against the patterns below.*/import { errorTextMatches } from './error-patterns.js';@@ -17,10 +19,22 @@ const CODE_KEYS = {storage_quota_exceeded: ['storageQuota.title', 'storageQuota.guidance'],};-export function getFriendlyError(errorMessage, t, code) {+const TYPE_KEYS = {+ size_limit: ['errors.fileTooLargeTitle', 'errors.enableChunkingGuidance'],+ timeout: ['errors.processingTimeout', 'errors.splitAudioGuidance'],+ auth: ['errors.authenticationError', 'errors.checkApiKeyGuidance'],+ rate_limit: ['errors.rateLimitExceeded', 'errors.waitAndRetryGuidance'],+ connection: ['errors.connectionError', 'errors.checkNetworkGuidance'],+ service_error: ['errors.serviceUnavailable', 'errors.tryAgainLaterGuidance'],+ format: ['errors.invalidAudioFormat', 'errors.convertFormatGuidance'],+ extraction: ['errors.audioExtractionFailed', 'errors.convertStandardGuidance'],+};++export function getFriendlyError(errorMessage, t, code, errorType) {const _t = t || ((key) => key);- if (code && CODE_KEYS[code]) {- const [title, guidance] = CODE_KEYS[code];+ const keys = (code && CODE_KEYS[code]) || (errorType && TYPE_KEYS[errorType]);+ if (keys) {+ const [title, guidance] = keys;return { title: _t(title), guidance: _t(guidance) };}if (!errorMessage) return { title: _t('errors.processingError'), message: _t('errors.processingErrorMessage') };diff --git a/static/js/modules/utils/upload-errors.test.js b/static/js/modules/utils/upload-errors.test.jsindex fa5376a6..ada2b96f 100644--- a/static/js/modules/utils/upload-errors.test.js+++ b/static/js/modules/utils/upload-errors.test.js@@ -25,6 +25,12 @@ describe('getFriendlyError', () => {expect(getFriendlyError(ffmpeg, t).title).toBe('errors.invalidAudioFormat');});+ it('names an incognito transcription error by its server type', () => {+ expect(getFriendlyError('The transcription service rejected the API credentials.', t, undefined, 'auth'))+ .toEqual({ title: 'errors.authenticationError', guidance: 'errors.checkApiKeyGuidance' });+ expect(getFriendlyError('Too many requests', t, undefined, 'unknown').title).toBe('errors.rateLimitExceeded');+ });+it('falls back to the message text for an unknown code', () => {expect(getFriendlyError('Upload timed out', t, 'something_new').title).toBe('errors.processingTimeout');expect(getFriendlyError('odd failure', t).title).toBe('errors.processingError');diff --git a/tests/test_incognito_settings.py b/tests/test_incognito_settings.pyindex b2dd92aa..58857346 100644--- a/tests/test_incognito_settings.py+++ b/tests/test_incognito_settings.py@@ -115,8 +115,8 @@ def _fake_probe(filename, cmd='ffprobe', timeout=None):"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."""+def _post_incognito_video(user_id, ffmpeg, filename="meeting.mp4", probe=_fake_probe, transcribe=None):+ """POST a file 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=[],@@ -124,6 +124,8 @@ def _post_incognito_video(user_id, ffmpeg):response = MagicMock(text="hello world transcript", segments=None, speakers=None, speaker_embeddings=None)response.has_diarization.return_value = Falseconnector.transcribe.return_value = response+ if transcribe is not None:+ connector.transcribe.side_effect = transcriberegistry = MagicMock()registry.get_active_connector.return_value = connectorclient = app.test_client()@@ -133,10 +135,10 @@ def _post_incognito_video(user_id, ffmpeg):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.ffprobe.probe", side_effect=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")},+ data={"file": (io.BytesIO(b"\x00" * 4096), filename)},content_type="multipart/form-data")return resp, run, connector@@ -170,3 +172,46 @@ def test_incognito_video_extraction_failure_keeps_ffmpeg_output_out(user):text = resp.get_data(as_text=True).lower()assert "ffmpeg" not in text and "/tmp/" not in textassert connector.transcribe.call_count == 0+++def _unprobeable(filename, cmd='ffprobe', timeout=None):+ from src.utils.ffprobe import FFProbeError+ raise FFProbeError("Invalid data found when processing input")+++def test_incognito_undecodable_audio_is_refused_not_transcribed(user):+ """The audio branch: a file FFmpeg cannot convert is not sent to the service as it is."""+ def ffmpeg(cmd, **kwargs):+ raise subprocess.CalledProcessError(1, cmd, output=b"", stderr=_FFMPEG_BANNER)++ resp, run, connector = _post_incognito_video(user, ffmpeg, filename="not-audio.mp3", probe=_unprobeable)+ assert run.call_count >= 1 # the conversion was attempted with the real chain+ assert resp.status_code == 400+ assert resp.get_json()["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+++def _ffmpeg_ok(cmd, **kwargs):+ with open(cmd[-1], "wb") as out:+ out.write(b"\xff\xfb" * 1024)+ return subprocess.CompletedProcess(cmd, 0, b"", b"")++[email protected]("upstream,error_type,message", [+ ("Error code: 401 - {'error': 'invalid api key sk-live-abc123 for org acme-internal'}", "auth",+ "The transcription service rejected the API credentials."),+ ("worker 10.0.0.7 traceback: KeyError 'segments' in /srv/asr/app.py", "unknown",+ "The transcription could not be completed."),+])+def test_incognito_service_errors_return_no_upstream_text(user, upstream, error_type, message):+ def transcribe(request):+ raise RuntimeError(upstream)++ resp, _, _ = _post_incognito_video(user, _ffmpeg_ok, transcribe=transcribe)+ assert resp.status_code == 500+ body = resp.get_json()+ assert body["error"] == message and body["error_type"] == error_type+ text = resp.get_data(as_text=True)+ assert "sk-live" not in text and "10.0.0.7" not in text and "/srv/" not in text