Skip to content

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

Python

Refuse empty and undecodable uploads with 400 and a stable code, keep FFmpeg output out of responses and remove the staging copy on every failure (#482)

Murtaza Nasir45d0bc141726
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index f8133ac2..2b7ab657 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -339,6 +339,22 @@ An upload that would exceed the user's storage quota is refused with `507 Insuff
`GET /api/v1/users/me` includes the same figures under `storage`, and `/api/v1/capabilities` lists `storage_quota`.
+A file that cannot be ingested is refused with `400`. No recording is created and the file is not kept:
+
+| Code | Meaning |
+|------|---------|
+| `empty_file` | The file part has no content. |
+| `audio_decode_failed` | The file cannot be decoded as audio or video, for example a text file with an `.mp3` extension or a damaged file. |
+
+```json
+{
+ "error": "The uploaded file could not be read as audio. It may be corrupt or in an unsupported format.",
+ "code": "audio_decode_failed"
+}
+```
+
+A conversion that runs longer than `FFMPEG_TIMEOUT_SECONDS` is a server error: `500` with the code `audio_conversion_timeout`.
+
**Example:**
```bash
@@ -391,6 +407,8 @@ When saving the webhook destination, ASR first sends an authenticated connection
}
```
+An empty or undecodable file is refused with `400` and the codes `empty_file` or `audio_decode_failed`, as on [Upload Recording](#upload-recording).
+
If ASR retries the same completed file with matching filename, note, and recording date for the same user, Speakr returns the existing recording with `idempotent_replay: true` instead of queueing another transcription. Identical audio submitted with different metadata remains a distinct recording. Simultaneous first deliveries are not a strict exactly-once guarantee.
**ASR Voice Recorder configuration:**
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 39962b58..07d36a7a 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -483,7 +483,7 @@ OPENAPI_SPEC = {
}
}
},
- "responses": {"202": {"description": "Upload accepted and queued"}, "507": {"description": "The upload would exceed the user's storage quota (code storage_quota_exceeded, with used_bytes, quota_bytes and file_bytes)"}}
+ "responses": {"202": {"description": "Upload accepted and queued"}, "400": {"description": "Invalid parameters, or a file that cannot be ingested (code empty_file or audio_decode_failed)"}, "507": {"description": "The upload would exceed the user's storage quota (code storage_quota_exceeded, with used_bytes, quota_bytes and file_bytes)"}}
}
},
"/integrations/asr-voice-recorder/upload": {
@@ -519,7 +519,7 @@ OPENAPI_SPEC = {
},
"responses": {
"200": {"description": "Connection test passed, recording accepted, or an idempotent retry matched an existing recording"},
- "400": {"description": "Upload metadata was provided without a file, or the multipart request is invalid"},
+ "400": {"description": "Upload metadata was provided without a file, the multipart request is invalid, or the file cannot be ingested (code empty_file or audio_decode_failed)"},
"401": {"description": "Missing, invalid, expired, or revoked API token"},
"413": {"description": "Upload exceeds the configured size limit"},
"429": {"description": "Too many upload attempts"},
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 8268ad2b..f54c38e9 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -41,7 +41,9 @@ from src.services.transcription_defaults import (
)
from src.tasks.processing import format_transcription_for_llm, _resolve_timestamp_template_format
from src.utils.dates import to_utc_naive
-from src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundError
+from src.utils.ffmpeg_utils import (
+ AUDIO_DECODE_FAILED_MESSAGE, FFmpegError, FFmpegNotFoundError, FFmpegTimeoutError,
+)
from src.utils.titles import resolve_upload_title, upload_title_source
from src.services.speaker import (
update_speaker_usage, apply_speaker_map, participants_from_segments, update_voice_profiles,
@@ -2201,7 +2203,10 @@ def share_target():
data = resp.get_json(silent=True) or {}
if status >= 400 or not data.get('id'):
current_app.logger.warning(f"share-target ingest failed ({status}): {data.get('error')}")
- error = {413: 'too_large', 507: 'storage_quota'}.get(status, 'save_failed')
+ if data.get('code') in ('audio_decode_failed', 'empty_file'):
+ error = 'unreadable'
+ else:
+ error = {413: 'too_large', 507: 'storage_quota'}.get(status, 'save_failed')
return redirect(url_for('recordings.index') + f'?share_target_error={error}')
return redirect(url_for('recordings.index') + f"?share_target=ok&recording_id={data['id']}")
@@ -2217,6 +2222,24 @@ def upload_file():
)
+EMPTY_FILE_MESSAGE = 'The uploaded file is empty.'
+
+
+def _discard_staging(path):
+ """Remove an upload's staging copy when the upload fails.
+
+ A file handed to storage has already left the staging directory, so
+ after that point this finds nothing to remove.
+ """
+ if not path:
+ return
+ try:
+ if os.path.exists(path):
+ os.remove(path)
+ except OSError as e:
+ current_app.logger.warning(f"Could not remove staging file {path}: {e}")
+
+
def ingest_uploaded_recording(
*,
owner,
@@ -2238,6 +2261,7 @@ def ingest_uploaded_recording(
index (a concurrent retry with the same idempotency key, #476) with a
response, or None for the usual error.
"""
+ filepath = None
try:
if uploaded_file is None:
return jsonify({'error': 'No file provided'}), 400
@@ -2367,6 +2391,13 @@ def ingest_uploaded_recording(
file.save(filepath)
current_app.logger.info(f"File saved to {filepath}")
+ # An empty part has nothing to decode: refuse it before the probe and
+ # the conversion (#482).
+ if os.path.getsize(filepath) == 0:
+ current_app.logger.info(f"Upload refused for user {owner.id}: the file is empty")
+ _discard_staging(filepath)
+ return jsonify({'error': EMPTY_FILE_MESSAGE, 'code': 'empty_file'}), 400
+
# Compute file hash on the ORIGINAL upload before any conversion/compression.
# Lossy re-encoding (e.g. FLAC→MP3) produces different bytes each run,
# so hashing after conversion would miss duplicates.
@@ -2409,11 +2440,7 @@ def ingest_uploaded_recording(
# the retry's staging copy is never needed for job recovery. Remove
# it before enqueueing to avoid leaking one full file each time a
# temporarily unavailable queue makes ASR retry the delivery.
- try:
- if os.path.exists(filepath):
- os.remove(filepath)
- except OSError:
- pass
+ _discard_staging(filepath)
existing_job = ProcessingJob.query.filter_by(
recording_id=existing.id,
@@ -2554,10 +2581,20 @@ def ingest_uploaded_recording(
except FFmpegNotFoundError as e:
current_app.logger.error(f"FFmpeg not found: {e}")
+ _discard_staging(filepath)
return jsonify({'error': 'Audio conversion tool (FFmpeg) not found on server.'}), 500
+ except FFmpegTimeoutError as e:
+ # A timeout is the server's limit, not proof the file is bad.
+ current_app.logger.error(f"FFmpeg conversion timed out for {filepath}: {e}")
+ _discard_staging(filepath)
+ return jsonify({'error': 'Audio conversion timed out.',
+ 'code': 'audio_conversion_timeout'}), 500
except FFmpegError as e:
+ # The probe is allowed to fail, so a payload that is not audio
+ # at all is first refused here, as the client's error.
current_app.logger.error(f"FFmpeg conversion failed for {filepath}: {e}")
- return jsonify({'error': f'Failed to convert audio file: {str(e)}'}), 500
+ _discard_staging(filepath)
+ return jsonify({'error': AUDIO_DECODE_FAILED_MESSAGE, 'code': 'audio_decode_failed'}), 400
# Get final file size (of original or converted file)
final_file_size = os.path.getsize(filepath)
@@ -2579,11 +2616,7 @@ def ingest_uploaded_recording(
and final_file_size > regular_limit_mb * 1024 * 1024
and not chunking_will_handle_large_audio
):
- try:
- if os.path.exists(filepath):
- os.remove(filepath)
- except OSError:
- pass
+ _discard_staging(filepath)
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 and chunking is off. "
@@ -2912,11 +2945,7 @@ def ingest_uploaded_recording(
return jsonify(response_data), success_status
except RequestEntityTooLarge:
- try:
- if 'filepath' in locals() and filepath and os.path.exists(filepath):
- os.remove(filepath)
- except OSError:
- pass
+ _discard_staging(filepath)
# 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.
@@ -2942,8 +2971,7 @@ def ingest_uploaded_recording(
# Another upload committed the same unique key first (#476): keep
# nothing of this one and let the caller answer with that recording.
db.session.rollback()
- if 'filepath' in locals() and filepath and os.path.exists(filepath):
- os.remove(filepath)
+ _discard_staging(filepath)
replay = on_conflict() if on_conflict is not None else None
if replay is not None:
current_app.logger.info("Upload lost a race on a unique key; answering with the earlier recording")
@@ -2952,6 +2980,7 @@ def ingest_uploaded_recording(
return jsonify({'error': 'An unexpected error occurred during upload.'}), 500
except Exception as e:
db.session.rollback()
+ _discard_staging(filepath)
current_app.logger.error(f"Error during file upload: {e}", exc_info=True)
return jsonify({'error': 'An unexpected error occurred during upload.'}), 500
@@ -3038,6 +3067,9 @@ def upload_incognito():
file_size = file.tell()
file.seek(0)
+ if file_size == 0:
+ return jsonify({'incognito': True, 'error': EMPTY_FILE_MESSAGE, 'code': 'empty_file'}), 400
+
# Mirror the regular /upload route's option-B size policy:
# video files (by extension) use the larger video cap because
# incognito always extracts audio (it never retains the video
@@ -3114,6 +3146,12 @@ def upload_incognito():
if result.get('error'):
current_app.logger.error(f"[Incognito] Transcription failed: {result['error']}")
+ if result.get('error_code') == 'audio_decode_failed':
+ return jsonify({
+ 'incognito': True,
+ 'error': result['error'],
+ 'code': 'audio_decode_failed',
+ }), 400
return jsonify({
'incognito': True,
'error': result['error']
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index fb68f0f6..489f50ab 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -27,7 +27,7 @@ from src.services.embeddings import process_recording_chunks
from src.services.llm import is_using_openai_api, call_llm_completion, format_api_error_message, TEXT_MODEL_NAME, client, http_client_no_proxy, TokenBudgetExceeded
from src.utils import extract_json_object, safe_json_loads
from src.utils.ffprobe import get_codec_info, is_video_file, is_lossless_audio, FFProbeError
-from src.utils.ffmpeg_utils import convert_to_mp3, extract_audio_from_video as ffmpeg_extract_audio, compress_audio, FFmpegError, FFmpegNotFoundError
+from src.utils.ffmpeg_utils import convert_to_mp3, extract_audio_from_video as ffmpeg_extract_audio, compress_audio, FFmpegError, FFmpegNotFoundError, FFmpegTimeoutError, AUDIO_DECODE_FAILED_MESSAGE
from src.utils.audio_conversion import convert_if_needed, ConversionResult
from src.utils.error_formatting import format_error_for_storage
from src.config.app_config import AUDIO_COMPRESS_UPLOADS, AUDIO_CODEC, AUDIO_BITRATE, VIDEO_PASSTHROUGH_ASR
@@ -2691,7 +2691,17 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
except Exception as e:
current_app.logger.error(f"[Incognito] Transcription failed: {str(e)}", exc_info=True)
- result['error'] = str(e)
+ # FFmpeg's output names its build and the temp path (#482): the
+ # response gets a fixed message instead.
+ if isinstance(e, FFmpegNotFoundError):
+ result['error'] = 'Audio conversion tool (FFmpeg) not found on server.'
+ elif isinstance(e, FFmpegTimeoutError):
+ result['error'] = 'Audio conversion timed out.'
+ elif isinstance(e, FFmpegError):
+ result['error'] = AUDIO_DECODE_FAILED_MESSAGE
+ result['error_code'] = 'audio_decode_failed'
+ else:
+ result['error'] = str(e)
result['processing_time_seconds'] = int(time.time() - start_time)
return result
diff --git a/src/utils/error_formatting.py b/src/utils/error_formatting.py
index 0cda7985..74b0642c 100644
--- a/src/utils/error_formatting.py
+++ b/src/utils/error_formatting.py
@@ -115,6 +115,8 @@ ERROR_PATTERNS = [
r'could not.*decode',
r'audio.*corrupt',
r'not.*valid.*audio',
+ # FFmpeg's wording for a file it cannot open
+ r'invalid data found when processing input',
],
'title': 'Invalid Audio Format',
'message': 'The audio file format is not supported or the file may be corrupted.',
diff --git a/src/utils/ffmpeg_utils.py b/src/utils/ffmpeg_utils.py
index 3156a984..7d9da26f 100644
--- a/src/utils/ffmpeg_utils.py
+++ b/src/utils/ffmpeg_utils.py
@@ -25,6 +25,13 @@ except (TypeError, ValueError):
FFMPEG_TIMEOUT_SECONDS = 3600
+# What a client is told when FFmpeg cannot decode its upload (#482). The
+# exception text stays in the log: FFmpeg's output names its build and the
+# path of the file.
+AUDIO_DECODE_FAILED_MESSAGE = ('The uploaded file could not be read as audio. '
+ 'It may be corrupt or in an unsupported format.')
+
+
class FFmpegError(Exception):
"""Custom exception for FFmpeg-related errors."""
pass
@@ -35,6 +42,15 @@ class FFmpegNotFoundError(FFmpegError):
pass
+class FFmpegTimeoutError(FFmpegError):
+ """Raised when an FFmpeg command runs past FFMPEG_TIMEOUT_SECONDS.
+
+ A timeout says nothing about the input, so callers that answer a client
+ can tell it apart from a file FFmpeg could not decode.
+ """
+ pass
+
+
def describe_size_reduction(reduction_percent: float) -> str:
"""Label a size change for a log line: "40.2% smaller", "93.5% larger".
@@ -562,7 +578,7 @@ def _run_ffmpeg_command(cmd: list, operation_description: str) -> None:
# hanging forever on a stalled/adversarial input.
error_msg = f"{operation_description} timed out after {FFMPEG_TIMEOUT_SECONDS}s"
current_app.logger.error(f"FFmpeg error: {error_msg}")
- raise FFmpegError(error_msg)
+ raise FFmpegTimeoutError(error_msg)
except subprocess.CalledProcessError as e:
error_msg = f"{operation_description} failed: {decode_ffmpeg_output(e.stderr)}"
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 1979338e..3f7dbe16 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -143,7 +143,7 @@ const parseUnformattedError = (text) => {
type: 'service_error'
},
{
- patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt', 'not valid audio'],
+ patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt', 'not valid audio', 'invalid data found when processing input'],
title: _t('errors.invalidAudioFormat', 'Invalid Audio Format'),
message: _t('errors.invalidAudioFormatMessage', 'The audio file format is not supported or the file may be corrupted.'),
guidance: _t('errors.invalidAudioFormatGuidance', 'Try converting the audio to MP3 or WAV format before uploading.'),
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 42d50bd3..419c389f 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -10,40 +10,12 @@ import { getUploadCsrfToken, isCsrfRejection } from '../csrf.js';
import { shouldSliceUpload, uploadFileInSlices } from '../db/sliced-file-upload.js';
import { computeUploadTimeout } from '../utils/upload-timeout.js';
import { recorderInUse } from '../utils/recorder-state.js';
-import { errorTextMatches } from '../utils/error-patterns.js';
+import { getFriendlyError } from '../utils/upload-errors.js';
import {
sortQueuedForJoin, moveQueuedItem, placeQueuedItem, totalJoinDuration,
newJoinGroupId, isVideoFileName, MAX_JOIN_FILES,
} from '../utils/upload-join.js';
-// Parse error message and return friendly error info
-function getFriendlyError(errorMessage, t) {
- const _t = t || ((key) => key);
- if (!errorMessage) return { title: _t('errors.processingError'), message: _t('errors.processingErrorMessage') };
- const lowerText = errorMessage.toLowerCase();
- const patterns = [
- // Reverse-proxy 413 (nginx / NPM default). Must match BEFORE the
- // generic 413 pattern below; the proxy rejects the request body before
- // Speakr sees it, so enabling chunking on the Speakr side will not help.
- { patterns: ['request entity too large', 'request body is too large', '413 request entity too large'], title: _t('errors.uploadBlockedByProxyTitle'), guidance: _t('errors.uploadBlockedByProxyGuidance') },
- { patterns: ['storage quota', 'storage is full'], title: _t('storageQuota.title'), guidance: _t('storageQuota.guidance') },
- { patterns: ['maximum content size limit', 'file too large', 'payload too large', 'exceeded', 'content too large'], title: _t('errors.fileTooLargeTitle'), guidance: _t('errors.enableChunkingGuidance') },
- { patterns: ['timed out', 'timeout', 'deadline exceeded'], title: _t('errors.processingTimeout'), guidance: _t('errors.splitAudioGuidance') },
- { patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'], title: _t('errors.authenticationError'), guidance: _t('errors.checkApiKeyGuidance') },
- { patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'], title: _t('errors.rateLimitExceeded'), guidance: _t('errors.waitAndRetryGuidance') },
- { patterns: ['connection refused', 'connection reset', 'could not connect', 'network unreachable'], title: _t('errors.connectionError'), guidance: _t('errors.checkNetworkGuidance') },
- { patterns: ['503', '502', '500', 'service unavailable', 'server error', 'internal server error'], title: _t('errors.serviceUnavailable'), guidance: _t('errors.tryAgainLaterGuidance') },
- { patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt'], title: _t('errors.invalidAudioFormat'), guidance: _t('errors.convertFormatGuidance') },
- { patterns: ['audio extraction failed', 'ffmpeg failed', 'no audio stream'], title: _t('errors.audioExtractionFailed'), guidance: _t('errors.convertStandardGuidance') },
- ];
- for (const pattern of patterns) {
- for (const p of pattern.patterns) {
- if (errorTextMatches(lowerText, p)) return { title: pattern.title, guidance: pattern.guidance };
- }
- }
- return { title: _t('errors.processingError'), guidance: _t('errors.processingErrorFallbackGuidance') };
-}
-
export function useUpload(state, utils) {
const {
uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,
@@ -745,7 +717,11 @@ export function useUpload(state, utils) {
});
if (quotaMsg && quotaMsg !== 'storageQuota.uploadRefused') errorMsg = quotaMsg;
}
+ // A file the server could not read (#482): the item says so in the UI language.
+ if (parsed.code === 'audio_decode_failed' && t) errorMsg = t('errors.audioDecodeFailedGuidance');
+ if (parsed.code === 'empty_file' && t) errorMsg = t('errors.emptyFileGuidance');
const err = new Error(errorMsg);
+ err.code = parsed.code;
if (isCsrfRejection(xhr.status, parsed.error || '')) {
err.isCsrfRejection = true;
}
@@ -925,7 +901,7 @@ export function useUpload(state, utils) {
}
// Show friendly error message
- const friendlyErr = getFriendlyError(error.message, t);
+ const friendlyErr = getFriendlyError(error.message, t, error.code);
setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);
// If this failure is itself a resurfaced retry, just bump the retry
@@ -1193,7 +1169,9 @@ export function useUpload(state, utils) {
const data = await response.json();
if (!response.ok || data.error) {
- throw new Error(data.error || `Processing failed with status ${response.status}`);
+ const err = new Error(data.error || `Processing failed with status ${response.status}`);
+ err.code = data.code;
+ throw err;
}
processingProgress.value = 80;
@@ -1245,7 +1223,7 @@ export function useUpload(state, utils) {
} catch (error) {
console.error('[Incognito] Processing failed:', error);
- const friendlyErr = getFriendlyError(error.message, t);
+ const friendlyErr = getFriendlyError(error.message, t, error.code);
setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);
fileItem.status = 'failed';
fileItem.error = error.message;
diff --git a/static/js/modules/db/sliced-file-upload.js b/static/js/modules/db/sliced-file-upload.js
index 6359a1ae..8f2af602 100644
--- a/static/js/modules/db/sliced-file-upload.js
+++ b/static/js/modules/db/sliced-file-upload.js
@@ -397,6 +397,7 @@ async function finalize(sessionId, formData, tokenRef, options) {
const error = new Error(body?.error
|| `Upload could not be finalized (HTTP ${result.status})`);
error.status = result.status;
+ error.code = body?.code;
error.resumable = finalizeCouldStillLand(result.status);
throw error;
}
diff --git a/static/js/modules/utils/upload-errors.js b/static/js/modules/utils/upload-errors.js
new file mode 100644
index 00000000..1a6768a9
--- /dev/null
+++ b/static/js/modules/utils/upload-errors.js
@@ -0,0 +1,51 @@
+/**
+ * Friendly titles and guidance for a failed upload (upload dialog,
+ * incognito upload).
+ *
+ * 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.
+ */
+
+import { errorTextMatches } from './error-patterns.js';
+
+const CODE_KEYS = {
+ audio_decode_failed: ['errors.invalidAudioFormat', 'errors.audioDecodeFailedGuidance'],
+ empty_file: ['errors.invalidAudioFormat', 'errors.emptyFileGuidance'],
+ audio_conversion_timeout: ['errors.processingTimeout', 'errors.splitAudioGuidance'],
+ storage_quota_exceeded: ['storageQuota.title', 'storageQuota.guidance'],
+};
+
+export function getFriendlyError(errorMessage, t, code) {
+ const _t = t || ((key) => key);
+ if (code && CODE_KEYS[code]) {
+ const [title, guidance] = CODE_KEYS[code];
+ return { title: _t(title), guidance: _t(guidance) };
+ }
+ if (!errorMessage) return { title: _t('errors.processingError'), message: _t('errors.processingErrorMessage') };
+ const lowerText = errorMessage.toLowerCase();
+ const patterns = [
+ // Reverse-proxy 413 (nginx / NPM default). Must match BEFORE the
+ // generic 413 pattern below; the proxy rejects the request body before
+ // Speakr sees it, so enabling chunking on the Speakr side will not help.
+ { patterns: ['request entity too large', 'request body is too large', '413 request entity too large'], title: _t('errors.uploadBlockedByProxyTitle'), guidance: _t('errors.uploadBlockedByProxyGuidance') },
+ { patterns: ['storage quota', 'storage is full'], title: _t('storageQuota.title'), guidance: _t('storageQuota.guidance') },
+ { patterns: ['maximum content size limit', 'file too large', 'payload too large', 'exceeded', 'content too large'], title: _t('errors.fileTooLargeTitle'), guidance: _t('errors.enableChunkingGuidance') },
+ { patterns: ['timed out', 'timeout', 'deadline exceeded'], title: _t('errors.processingTimeout'), guidance: _t('errors.splitAudioGuidance') },
+ { patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'], title: _t('errors.authenticationError'), guidance: _t('errors.checkApiKeyGuidance') },
+ { patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'], title: _t('errors.rateLimitExceeded'), guidance: _t('errors.waitAndRetryGuidance') },
+ { patterns: ['connection refused', 'connection reset', 'could not connect', 'network unreachable'], title: _t('errors.connectionError'), guidance: _t('errors.checkNetworkGuidance') },
+ { patterns: ['503', '502', '500', 'service unavailable', 'server error', 'internal server error'], title: _t('errors.serviceUnavailable'), guidance: _t('errors.tryAgainLaterGuidance') },
+ // "Invalid data found when processing input" is FFmpeg's wording for
+ // a file it cannot open.
+ { patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt', 'invalid data found when processing input'], title: _t('errors.invalidAudioFormat'), guidance: _t('errors.convertFormatGuidance') },
+ { patterns: ['audio extraction failed', 'ffmpeg failed', 'no audio stream'], title: _t('errors.audioExtractionFailed'), guidance: _t('errors.convertStandardGuidance') },
+ ];
+ for (const pattern of patterns) {
+ for (const p of pattern.patterns) {
+ if (errorTextMatches(lowerText, p)) return { title: pattern.title, guidance: pattern.guidance };
+ }
+ }
+ return { title: _t('errors.processingError'), guidance: _t('errors.processingErrorFallbackGuidance') };
+}
diff --git a/static/js/modules/utils/upload-errors.test.js b/static/js/modules/utils/upload-errors.test.js
new file mode 100644
index 00000000..fa5376a6
--- /dev/null
+++ b/static/js/modules/utils/upload-errors.test.js
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { getFriendlyError } from './upload-errors.js';
+
+const t = (key) => key;
+
+describe('getFriendlyError', () => {
+ it('names an unreadable or empty file by its code (#482)', () => {
+ expect(getFriendlyError('Datei nicht lesbar', t, 'audio_decode_failed')).toEqual({
+ title: 'errors.invalidAudioFormat', guidance: 'errors.audioDecodeFailedGuidance',
+ });
+ expect(getFriendlyError('The uploaded file is empty.', t, 'empty_file')).toEqual({
+ title: 'errors.invalidAudioFormat', guidance: 'errors.emptyFileGuidance',
+ });
+ });
+
+ it('names a full storage by its code when the message is localized', () => {
+ expect(getFriendlyError('Diese Datei passt nicht in Ihren Speicher', t, 'storage_quota_exceeded').title)
+ .toBe('storageQuota.title');
+ });
+
+ it('reads FFmpeg\'s wording for a file it cannot open as an invalid format', () => {
+ const ffmpeg = 'Compression of x.mp3 to mp3 failed: ffmpeg version n8.1.3 ... '
+ + 'Error opening input files: Invalid data found when processing input';
+ expect(getFriendlyError(ffmpeg, t).title).toBe('errors.invalidAudioFormat');
+ });
+
+ 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/static/locales/de.json b/static/locales/de.json
index b6eaf518..6d6ec9c0 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -864,6 +864,7 @@
"selectBody": "Wählen Sie eine aus der Seitenleiste oder starten Sie eine neue Aufnahme."
},
"errors": {
+ "audioDecodeFailedGuidance": "Die Datei konnte nicht als Audio gelesen werden. Sie ist möglicherweise beschädigt oder hat ein nicht unterstütztes Format. Konvertieren Sie sie in MP3 oder WAV und laden Sie sie erneut hoch.",
"audioExtractionFailed": "Audio-Extraktion fehlgeschlagen",
"audioExtractionFailedGuidance": "Versuchen Sie, die Datei vor dem Hochladen in ein Standard-Audioformat (MP3, WAV) zu konvertieren.",
"audioExtractionFailedMessage": "Audio konnte nicht aus der hochgeladenen Datei extrahiert werden.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "Konnte keine Verbindung zum Transkriptionsdienst herstellen.",
"convertFormatGuidance": "Vor dem Hochladen in MP3 oder WAV konvertieren",
"convertStandardGuidance": "In ein Standard-Audioformat konvertieren",
+ "emptyFileGuidance": "Die Datei ist leer. Prüfen Sie die Originaldatei und laden Sie sie erneut hoch.",
"enableChunkingGuidance": "Aktivieren Sie Chunking in den Admin-Einstellungen oder verkleinern Sie die Chunk-Größe, falls bereits aktiviert; andernfalls komprimieren Sie die Quelldatei",
"fallbackMessage": "Ein Fehler ist aufgetreten",
"fallbackTitle": "Fehler",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "Die geteilte Audiodatei wurde gespeichert, konnte aber nicht zur Transkription eingereiht werden.",
"shareTarget_save_failed": "Speakr konnte die geteilte Audiodatei nicht speichern. Bitte direkt hochladen.",
"shareTarget_too_large": "Die geteilte Audiodatei überschreitet Speakrs Upload-Limit.",
+ "shareTarget_unreadable": "Die geteilte Datei konnte nicht als Audio gelesen werden. Sie ist möglicherweise leer, beschädigt oder hat ein nicht unterstütztes Format.",
"splitAudioGuidance": "Versuchen Sie, die Audiodatei in kleinere Teile aufzuteilen",
"statusCheckFailed": "Der Aufnahmestatus konnte nicht abgefragt werden (HTTP {{status}}).",
"summaryFailed": "Zusammenfassung fehlgeschlagen. Bitte erneut versuchen.",
diff --git a/static/locales/en.json b/static/locales/en.json
index 351b2457..8d67c1a6 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -864,6 +864,7 @@
"selectBody": "Pick one from the sidebar or start a new recording."
},
"errors": {
+ "audioDecodeFailedGuidance": "The file could not be read as audio. It may be damaged or in an unsupported format. Convert it to MP3 or WAV and upload it again.",
"audioExtractionFailed": "Audio Extraction Failed",
"audioExtractionFailedGuidance": "Try converting the file to a standard audio format (MP3, WAV) before uploading.",
"audioExtractionFailedMessage": "Could not extract audio from the uploaded file.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "Could not connect to the transcription service.",
"convertFormatGuidance": "Convert to MP3 or WAV before uploading",
"convertStandardGuidance": "Convert to standard audio format",
+ "emptyFileGuidance": "The file is empty. Check the original file and upload it again.",
"enableChunkingGuidance": "Enable chunking in your admin settings, or lower the per-chunk size if it is already enabled; otherwise compress the source file",
"fallbackMessage": "An error occurred",
"fallbackTitle": "Error",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "The shared audio was saved but could not be queued for transcription.",
"shareTarget_save_failed": "Speakr could not save the shared audio. Please try uploading directly.",
"shareTarget_too_large": "The shared audio file is larger than Speakr's upload limit.",
+ "shareTarget_unreadable": "The shared file could not be read as audio. It may be empty, damaged or in an unsupported format.",
"splitAudioGuidance": "Try splitting the audio into smaller parts",
"statusCheckFailed": "Could not check the recording status (HTTP {{status}}).",
"summaryFailed": "Summary generation failed. Please try again.",
diff --git a/static/locales/es.json b/static/locales/es.json
index 12613514..41847d6f 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -864,6 +864,7 @@
"selectBody": "Elija una en la barra lateral o inicie una nueva grabación."
},
"errors": {
+ "audioDecodeFailedGuidance": "No se pudo leer el archivo como audio. Puede estar dañado o tener un formato no compatible. Conviértalo a MP3 o WAV y vuelva a subirlo.",
"audioExtractionFailed": "Falló la extracción de audio",
"audioExtractionFailedGuidance": "Pruebe a convertir el archivo a un formato de audio estándar (MP3, WAV) antes de subirlo.",
"audioExtractionFailedMessage": "No se pudo extraer el audio del archivo subido.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "No se pudo conectar con el servicio de transcripción.",
"convertFormatGuidance": "Convierta a MP3 o WAV antes de subir",
"convertStandardGuidance": "Convierta a un formato de audio estándar",
+ "emptyFileGuidance": "El archivo está vacío. Compruebe el archivo original y vuelva a subirlo.",
"enableChunkingGuidance": "Active la fragmentación en la configuración de administrador, o reduzca el tamaño por fragmento si ya está activada; de lo contrario, comprima el archivo de origen",
"fallbackMessage": "Ocurrió un error",
"fallbackTitle": "Error",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "El audio compartido se guardó pero no se pudo poner en cola para transcripción.",
"shareTarget_save_failed": "Speakr no pudo guardar el audio compartido. Por favor, súbalo directamente.",
"shareTarget_too_large": "El archivo de audio compartido supera el límite de subida de Speakr.",
+ "shareTarget_unreadable": "No se pudo leer el archivo compartido como audio. Puede estar vacío, dañado o tener un formato no compatible.",
"splitAudioGuidance": "Pruebe a dividir el audio en partes más pequeñas",
"statusCheckFailed": "No se ha podido comprobar el estado de la grabación (HTTP {{status}}).",
"summaryFailed": "No se pudo generar el resumen. Inténtalo de nuevo.",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index ec82d260..d2290740 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -864,6 +864,7 @@
"selectBody": "Choisissez-en un dans la barre latérale ou lancez un nouvel enregistrement."
},
"errors": {
+ "audioDecodeFailedGuidance": "Le fichier n'a pas pu être lu comme audio. Il est peut-être endommagé ou dans un format non pris en charge. Convertissez-le en MP3 ou WAV et envoyez-le à nouveau.",
"audioExtractionFailed": "Échec de l’extraction audio",
"audioExtractionFailedGuidance": "Essayez de convertir le fichier dans un format audio standard (MP3, WAV) avant l’envoi.",
"audioExtractionFailedMessage": "Impossible d’extraire l’audio du fichier envoyé.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "Impossible de se connecter au service de transcription.",
"convertFormatGuidance": "Convertissez en MP3 ou WAV avant l’envoi",
"convertStandardGuidance": "Convertissez en format audio standard",
+ "emptyFileGuidance": "Le fichier est vide. Vérifiez le fichier d'origine et envoyez-le à nouveau.",
"enableChunkingGuidance": "Activez le découpage dans vos paramètres d'administration ou réduisez la taille par chunk s'il est déjà activé ; sinon, compressez le fichier source",
"fallbackMessage": "Une erreur est survenue",
"fallbackTitle": "Erreur",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "L'audio partagé a été enregistré mais n'a pas pu être mis en file pour transcription.",
"shareTarget_save_failed": "Speakr n'a pas pu enregistrer l'audio partagé. Veuillez l'envoyer directement.",
"shareTarget_too_large": "Le fichier audio partagé dépasse la limite d'envoi de Speakr.",
+ "shareTarget_unreadable": "Le fichier partagé n'a pas pu être lu comme audio. Il est peut-être vide, endommagé ou dans un format non pris en charge.",
"splitAudioGuidance": "Essayez de diviser l’audio en parties plus petites",
"statusCheckFailed": "Le statut de l'enregistrement n'a pas pu être vérifié (HTTP {{status}}).",
"summaryFailed": "La génération du résumé a échoué. Veuillez réessayer.",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 1fbbbe04..7f66eff3 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -864,6 +864,7 @@
"selectBody": "Escolha uma na barra lateral ou inicie uma nova gravação."
},
"errors": {
+ "audioDecodeFailedGuidance": "Não foi possível ler o arquivo como áudio. Ele pode estar danificado ou em um formato não suportado. Converta-o para MP3 ou WAV e envie-o novamente.",
"audioExtractionFailed": "Falha na Extração de Áudio",
"audioExtractionFailedGuidance": "Tente converter o arquivo para um formato de áudio padrão (MP3, WAV) antes de enviar.",
"audioExtractionFailedMessage": "Não foi possível extrair áudio do arquivo enviado.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "Não foi possível conectar ao serviço de transcrição.",
"convertFormatGuidance": "Converta para MP3 ou WAV antes de enviar",
"convertStandardGuidance": "Converter para formato de áudio padrão",
+ "emptyFileGuidance": "O arquivo está vazio. Verifique o arquivo original e envie-o novamente.",
"enableChunkingGuidance": "Ative o chunking nas configurações de administrador, ou diminua o tamanho por chunk se já estiver ativado; caso contrário, comprima o arquivo de origem",
"fallbackMessage": "Ocorreu um erro",
"fallbackTitle": "Erro",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "O áudio compartilhado foi salvo, mas não pôde ser enfileirado para transcrição.",
"shareTarget_save_failed": "Speakr não conseguiu salvar o áudio compartilhado. Faça o upload diretamente.",
"shareTarget_too_large": "O arquivo de áudio compartilhado excede o limite de upload do Speakr.",
+ "shareTarget_unreadable": "Não foi possível ler o arquivo compartilhado como áudio. Ele pode estar vazio, danificado ou em um formato não suportado.",
"splitAudioGuidance": "Tente dividir o áudio em partes menores",
"statusCheckFailed": "Não foi possível verificar o status da gravação (HTTP {{status}}).",
"summaryFailed": "Falha ao gerar o resumo. Tente novamente.",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index bd9eea10..5f5482dc 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -864,6 +864,7 @@
"selectBody": "Выберите запись на боковой панели или начните новую."
},
"errors": {
+ "audioDecodeFailedGuidance": "Не удалось прочитать файл как аудио. Возможно, он повреждён или имеет неподдерживаемый формат. Преобразуйте его в MP3 или WAV и загрузите снова.",
"audioExtractionFailed": "Не удалось извлечь аудио",
"audioExtractionFailedGuidance": "Попробуйте преобразовать файл в стандартный аудиоформат (MP3, WAV) перед загрузкой.",
"audioExtractionFailedMessage": "Не удалось извлечь аудио из загруженного файла.",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "Не удалось подключиться к сервису транскрипции.",
"convertFormatGuidance": "Преобразуйте в MP3 или WAV перед загрузкой",
"convertStandardGuidance": "Преобразуйте в стандартный аудиоформат",
+ "emptyFileGuidance": "Файл пуст. Проверьте исходный файл и загрузите его снова.",
"enableChunkingGuidance": "Включите разбиение на части в настройках администратора или уменьшите размер одного фрагмента, если оно уже включено; иначе сожмите исходный файл",
"fallbackMessage": "Произошла ошибка",
"fallbackTitle": "Ошибка",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "Переданное аудио сохранено, но не удалось поставить его в очередь на транскрипцию.",
"shareTarget_save_failed": "Speakr не смог сохранить переданное аудио. Пожалуйста, загрузите его напрямую.",
"shareTarget_too_large": "Переданный аудиофайл превышает лимит загрузки Speakr.",
+ "shareTarget_unreadable": "Не удалось прочитать переданный файл как аудио. Возможно, он пуст, повреждён или имеет неподдерживаемый формат.",
"splitAudioGuidance": "Попробуйте разделить аудио на части поменьше",
"statusCheckFailed": "Не удалось проверить статус записи (HTTP {{status}}).",
"summaryFailed": "Не удалось сгенерировать резюме. Повторите попытку.",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index ab767f20..bfc73260 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -864,6 +864,7 @@
"selectBody": "从侧边栏中选择一个,或开始新的录音。"
},
"errors": {
+ "audioDecodeFailedGuidance": "无法将该文件读取为音频。文件可能已损坏或格式不受支持。请将其转换为 MP3 或 WAV 后重新上传。",
"audioExtractionFailed": "音频提取失败",
"audioExtractionFailedGuidance": "请尝试将文件转换为标准音频格式(MP3、WAV)后再上传。",
"audioExtractionFailedMessage": "无法从上传的文件中提取音频。",
@@ -878,6 +879,7 @@
"connectionErrorMessage": "无法连接到转录服务。",
"convertFormatGuidance": "上传前请转换为 MP3 或 WAV",
"convertStandardGuidance": "请转换为标准音频格式",
+ "emptyFileGuidance": "该文件为空。请检查原始文件后重新上传。",
"enableChunkingGuidance": "在管理员设置中启用分块上传;如已启用,请降低每块的大小,否则请压缩源文件",
"fallbackMessage": "发生错误",
"fallbackTitle": "错误",
@@ -929,6 +931,7 @@
"shareTarget_queue_failed": "共享的音频已保存,但无法加入转录队列。",
"shareTarget_save_failed": "Speakr 无法保存共享的音频。请改为直接上传。",
"shareTarget_too_large": "共享的音频文件超过 Speakr 的上传限制。",
+ "shareTarget_unreadable": "无法将共享的文件读取为音频。文件可能为空、已损坏或格式不受支持。",
"splitAudioGuidance": "请尝试将音频拆分为更小的部分",
"statusCheckFailed": "无法检查录音状态(HTTP {{status}})。",
"summaryFailed": "摘要生成失败。请重试。",
diff --git a/tests/test_asr_voice_recorder_upload.py b/tests/test_asr_voice_recorder_upload.py
index 28a56478..3ed7a7e4 100644
--- a/tests/test_asr_voice_recorder_upload.py
+++ b/tests/test_asr_voice_recorder_upload.py
@@ -435,6 +435,92 @@ def test_normal_api_upload_still_returns_202(tmp_path):
_cleanup_user(user)
+_FFMPEG_FAILURE = (
+ "Compression of x_voice.m4a to mp3 failed: ffmpeg version n8.1.3 configuration: --enable-gpl\n"
+ "Error opening input file /data/uploads/_staging/x_voice.m4a.\n"
+ "Error opening input files: Invalid data found when processing input"
+)
+
+
+def _post_api(client, token, payload, filename="voice.m4a", **fields):
+ return client.post(
+ "/api/v1/recordings/upload",
+ headers={"Authorization": f"Bearer {token}"},
+ data={"file": (io.BytesIO(payload), filename), **fields},
+ content_type="multipart/form-data",
+ )
+
+
[email protected]("route", ["api", "asr"])
+def test_undecodable_upload_returns_400_without_ffmpeg_details(tmp_path, route):
+ from src.utils.ffmpeg_utils import FFmpegError
+ with app.app_context():
+ user = _user("asr_undecodable")
+ _, token = _token(user)
+ client = app.test_client()
+ try:
+ with _upload_mocks(str(tmp_path)) as (_, enqueue, webhook), \
+ patch("src.api.recordings.get_codec_info", side_effect=FFProbeError("unprobeable")), \
+ patch("src.api.recordings.convert_if_needed", side_effect=FFmpegError(_FFMPEG_FAILURE)):
+ if route == "api":
+ response = _post_api(client, token, b"This is not audio.\n", idempotency_key="k-482")
+ else:
+ response = _post(client, secret=token, payload=b"This is not audio.\n")
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "audio_decode_failed"
+ text = response.get_data(as_text=True).lower()
+ assert "ffmpeg" not in text and "_staging" not in text and str(tmp_path).lower() not in text
+ assert list(tmp_path.iterdir()) == []
+ assert enqueue.call_count == 0 and webhook.call_count == 0
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ finally:
+ _cleanup_user(user)
+
+
[email protected]("route", ["api", "asr"])
+def test_empty_upload_returns_400_before_conversion(tmp_path, route):
+ with app.app_context():
+ user = _user("asr_empty")
+ _, token = _token(user)
+ client = app.test_client()
+ try:
+ with _upload_mocks(str(tmp_path)), \
+ patch("src.api.recordings.convert_if_needed") as convert:
+ if route == "api":
+ response = _post_api(client, token, b"")
+ else:
+ response = _post(client, secret=token, payload=b"")
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "empty_file"
+ assert convert.call_count == 0
+ assert list(tmp_path.iterdir()) == []
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ finally:
+ _cleanup_user(user)
+
+
+def test_retry_after_a_rejected_upload_with_the_same_key_succeeds(tmp_path):
+ """A refused upload creates no recording, so its idempotency key stays free."""
+ from src.utils.ffmpeg_utils import FFmpegError
+ with app.app_context():
+ user = _user("asr_retry_key")
+ _, token = _token(user)
+ client = app.test_client()
+ try:
+ with _upload_mocks(str(tmp_path)):
+ with patch("src.api.recordings.convert_if_needed", side_effect=FFmpegError(_FFMPEG_FAILURE)):
+ refused = _post_api(client, token, b"broken", idempotency_key="k-retry")
+ accepted = _post_api(client, token, b"real-audio", idempotency_key="k-retry")
+ assert refused.status_code == 400
+ assert accepted.status_code == 202
+ recording = db.session.get(Recording, accepted.get_json()["id"])
+ assert recording.upload_idempotency_key == "k-retry"
+ finally:
+ _cleanup_user(user)
+
+
def test_asr_upload_rate_cost_bounds_requests_and_declared_bytes_before_parsing():
for declared_mib, expected_cost in ((5, 52), (100, 100)):
with app.test_request_context(
diff --git a/tests/test_cov_recordings_write.py b/tests/test_cov_recordings_write.py
index 38f3c395..ee3db477 100644
--- a/tests/test_cov_recordings_write.py
+++ b/tests/test_cov_recordings_write.py
@@ -29,6 +29,8 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.app import app, db
from src.models import User, Recording, Tag, Folder, RecordingTag, SystemSetting
+from src.utils.ffmpeg_utils import AUDIO_DECODE_FAILED_MESSAGE
+from src.utils.ffprobe import FFProbeError
app.config["WTF_CSRF_ENABLED"] = False
@@ -618,7 +620,17 @@ def test_upload_requires_login():
assert resp.status_code in (302, 401)
-def test_upload_ffmpeg_error_returns_500():
+# What FFmpeg prints when it cannot open an upload: its build banner and the
+# absolute staging path, neither of which may reach the client (#482).
+_FFMPEG_FAILURE = (
+ "Compression of 20261024195609_abc_not-audio.mp3 to mp3 failed: ffmpeg version n8.1.3 "
+ "Copyright (c) 2000-2026 the FFmpeg developers\n configuration: --enable-gpl\n"
+ "Error opening input file /data/uploads/_staging/20261024195609_abc_not-audio.mp3.\n"
+ "Error opening input files: Invalid data found when processing input"
+)
+
+
+def test_upload_ffmpeg_error_returns_400_without_ffmpeg_details():
with app.app_context():
user = _mk_user("up_ffmpeg")
client = app.test_client()
@@ -627,16 +639,124 @@ def test_upload_ffmpeg_error_returns_500():
from src.utils.ffmpeg_utils import FFmpegError
fake_storage = _FakeStorage(staging)
with patch("src.api.recordings.get_storage_service", return_value=fake_storage), \
- patch("src.api.recordings.get_codec_info",
- return_value={"has_video": False, "audio_codec": "flac"}), \
+ patch("src.api.recordings.get_codec_info", side_effect=FFProbeError("unprobeable")), \
patch("src.api.recordings.convert_if_needed",
- side_effect=FFmpegError("boom")), \
- patch("src.services.job_queue.job_queue.enqueue", return_value=1):
+ side_effect=FFmpegError(_FFMPEG_FAILURE)), \
+ patch("src.services.job_queue.job_queue.enqueue", return_value=1) as enqueue:
+ resp = _do_upload(client, filename="not-audio.mp3", payload=b"This is not audio.\n")
+ assert resp.status_code == 400
+ body = resp.get_json()
+ assert body["code"] == "audio_decode_failed"
+ assert body["error"] == AUDIO_DECODE_FAILED_MESSAGE
+ text = resp.get_data(as_text=True).lower()
+ assert "ffmpeg" not in text
+ assert "/data/uploads" not in text and "_staging" not in text and staging.lower() not in text
+ assert os.listdir(staging) == []
+ assert enqueue.call_count == 0
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ _cleanup(user)
+
+
+def test_upload_empty_file_is_rejected_before_conversion():
+ with app.app_context():
+ user = _mk_user("up_empty")
+ client = app.test_client()
+ _login(client, user)
+ staging = os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+ with _upload_mocks(staging), \
+ patch("src.api.recordings.get_codec_info") as probe, \
+ patch("src.api.recordings.convert_if_needed") as convert:
+ resp = _do_upload(client, filename="empty.mp3", payload=b"")
+ assert resp.status_code == 400
+ assert resp.get_json() == {"error": "The uploaded file is empty.", "code": "empty_file"}
+ assert probe.call_count == 0
+ assert convert.call_count == 0
+ assert os.listdir(staging) == []
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ _cleanup(user)
+
+
+def test_upload_conversion_timeout_is_a_server_error():
+ with app.app_context():
+ user = _mk_user("up_ff_timeout")
+ client = app.test_client()
+ _login(client, user)
+ staging = os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+ from src.utils.ffmpeg_utils import FFmpegTimeoutError
+ with _upload_mocks(staging), \
+ patch("src.api.recordings.convert_if_needed",
+ side_effect=FFmpegTimeoutError("Compression of x.flac to mp3 timed out after 3600s")):
+ resp = _do_upload(client, filename="long.flac")
+ assert resp.status_code == 500
+ assert resp.get_json() == {"error": "Audio conversion timed out.", "code": "audio_conversion_timeout"}
+ assert os.listdir(staging) == []
+ _cleanup(user)
+
+
+def test_upload_ffmpeg_missing_stays_500_and_removes_staging_copy():
+ with app.app_context():
+ user = _mk_user("up_ff_missing")
+ client = app.test_client()
+ _login(client, user)
+ staging = os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+ from src.utils.ffmpeg_utils import FFmpegNotFoundError
+ with _upload_mocks(staging), \
+ patch("src.api.recordings.convert_if_needed", side_effect=FFmpegNotFoundError("no ffmpeg")):
resp = _do_upload(client, filename="a.flac")
assert resp.status_code == 500
- # An error payload is returned; the exact wording (convert-specific vs
- # the generic upload handler) is an implementation detail.
- assert resp.get_json().get("error")
+ assert resp.get_json() == {"error": "Audio conversion tool (FFmpeg) not found on server."}
+ assert os.listdir(staging) == []
+ _cleanup(user)
+
+
+def test_upload_unexpected_error_removes_staging_copy():
+ with app.app_context():
+ user = _mk_user("up_unexpected")
+ client = app.test_client()
+ _login(client, user)
+ staging = os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+ with _upload_mocks(staging), \
+ patch("src.api.recordings.resolve_transcription_params",
+ side_effect=RuntimeError("secret internal detail")):
+ resp = _do_upload(client)
+ assert resp.status_code == 500
+ assert resp.get_json() == {"error": "An unexpected error occurred during upload."}
+ assert os.listdir(staging) == []
+ _cleanup(user)
+
+
+def test_incognito_empty_file_returns_400():
+ with app.app_context():
+ user = _mk_user("inc_empty")
+ client = app.test_client()
+ _login(client, user)
+ with patch("src.api.recordings.ENABLE_INCOGNITO_MODE", True), \
+ patch("src.tasks.processing.transcribe_incognito") as transcribe:
+ resp = client.post("/api/recordings/incognito",
+ data={"file": (io.BytesIO(b""), "empty.mp3")},
+ content_type="multipart/form-data")
+ assert resp.status_code == 400
+ assert resp.get_json()["code"] == "empty_file"
+ assert transcribe.call_count == 0
+ _cleanup(user)
+
+
+def test_incognito_decode_failure_returns_400():
+ with app.app_context():
+ user = _mk_user("inc_decode")
+ client = app.test_client()
+ _login(client, user)
+ with patch("src.api.recordings.ENABLE_INCOGNITO_MODE", True), \
+ patch("src.tasks.processing.transcribe_incognito",
+ return_value={"error": AUDIO_DECODE_FAILED_MESSAGE,
+ "error_code": "audio_decode_failed"}):
+ resp = client.post("/api/recordings/incognito",
+ data={"file": (io.BytesIO(b"This is not audio."), "x.mp4")},
+ content_type="multipart/form-data")
+ assert resp.status_code == 400
+ body = resp.get_json()
+ assert body["code"] == "audio_decode_failed"
+ assert body["incognito"] is True
_cleanup(user)
diff --git a/tests/test_error_status_codes.py b/tests/test_error_status_codes.py
index 457d90b6..dd195bb6 100644
--- a/tests/test_error_status_codes.py
+++ b/tests/test_error_status_codes.py
@@ -33,3 +33,10 @@ def test_real_status_codes_are_still_recognised(text, kind):
def test_a_longer_number_is_not_a_status_code():
assert format_error_for_user("used 1429 tokens, then the request failed")["type"] != "rate_limit"
+
+
+def test_ffmpeg_wording_for_an_unreadable_file_is_a_format_error():
+ # #482: FFmpeg says neither "corrupt" nor "unsupported format".
+ text = ("Compression of x.mp3 to mp3 failed: ffmpeg version n8.1.3 ... "
+ "Error opening input files: Invalid data found when processing input")
+ assert format_error_for_user(text)["type"] == "format"
diff --git a/tests/test_incognito_settings.py b/tests/test_incognito_settings.py
index bcb4608d..3a5504d8 100644
--- a/tests/test_incognito_settings.py
+++ b/tests/test_incognito_settings.py
@@ -67,3 +67,24 @@ def test_incognito_resolves_language_hotwords_and_admin_prompt(user, tmp_path):
assert request.language == "de"
assert request.hotwords == "Speakr"
assert request.prompt == "A planning meeting."
+
+
+def test_incognito_decode_failure_reports_a_fixed_message(user, tmp_path):
+ """FFmpeg's output (build banner, temp path) stays out of the result (#482)."""
+ from src.utils.ffmpeg_utils import AUDIO_DECODE_FAILED_MESSAGE, FFmpegError
+ video = tmp_path / "a.mp4"
+ video.write_bytes(b"not a video")
+ connector = MagicMock(PROVIDER_NAME="test", supports_diarization=False)
+ with app.app_context():
+ u = db.session.get(User, user)
+ registry = MagicMock()
+ registry.get_active_connector.return_value = connector
+ with patch("src.services.transcription.get_registry", return_value=registry), \
+ patch.object(proc, "is_video_file", return_value=True), \
+ patch.object(proc, "VIDEO_PASSTHROUGH_ASR", False), \
+ patch.object(proc, "extract_audio_from_video",
+ side_effect=FFmpegError("ffmpeg version n8.1.3 ... Error opening input file /tmp/tmpx.mp4")):
+ result = proc.transcribe_incognito(str(video), "a.mp4", language="", user=u)
+ assert result["error"] == AUDIO_DECODE_FAILED_MESSAGE
+ assert result["error_code"] == "audio_decode_failed"
+ assert connector.transcribe.call_count == 0
diff --git a/tests/test_share_target.py b/tests/test_share_target.py
index df3cbc5f..c2fc5a31 100644
--- a/tests/test_share_target.py
+++ b/tests/test_share_target.py
@@ -94,6 +94,22 @@ def test_share_target_missing_file_redirects_with_error_flag():
db.session.commit()
+def test_share_target_empty_file_redirects_with_unreadable_flag():
+ with app.app_context():
+ user = _setup_user("share_empty")
+ client = app.test_client()
+ _login(client, user)
+ with _no_media_tools():
+ resp = client.post("/share-target",
+ data={"shared_audio": (io.BytesIO(b""), "memo.m4a")},
+ content_type="multipart/form-data", follow_redirects=False)
+ assert resp.status_code == 302
+ assert "share_target_error=unreadable" in resp.headers.get("Location", "")
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ db.session.delete(user)
+ db.session.commit()
+
+
def test_share_target_creates_recording_and_enqueues_job():
with app.app_context():
user = _setup_user("share_ok")