Skip to content

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

Python

Every request names the configured model; the voice embedding check explains its failures (#409)

Murtaza Nasir80851c5ebdc2
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index ef6c485b..a7665c73 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -107,6 +107,15 @@ ASR_DIARIZE=true
# Enable speaker embeddings for voice profile matching (WhisperX only)
ASR_RETURN_SPEAKER_EMBEDDINGS=true
+# Transcription model
+# Speakr sends a model with each request when one is configured: the upload's
+# choice, a tag or folder default, or the default model chosen in the admin
+# settings. Otherwise the request names no model and the ASR service uses its
+# own default: PRELOAD_MODEL on whisperx-asr-service (or DEFAULT_MODEL from
+# service version 0.4.2). Keep PRELOAD_MODEL set on the service, or choose a
+# default model in Speakr's admin settings. TRANSCRIPTION_MODEL has no effect
+# with this connector.
+
# Voice embedding compatibility check
# Voice profiles are only comparable with embeddings from the model that made
# them. If the backend starts returning embeddings from a different model,
diff --git a/docs/admin-guide/model-configuration.md b/docs/admin-guide/model-configuration.md
index 4744f0a9..8e428e03 100644
--- a/docs/admin-guide/model-configuration.md
+++ b/docs/admin-guide/model-configuration.md
@@ -505,9 +505,10 @@ Resolution order at upload time:
1. Per-upload selection (Advanced ASR Options dropdown)
2. First tag's `default_transcription_model`
3. Folder's `default_transcription_model`
-4. Global `TRANSCRIPTION_MODEL` env var (current behaviour)
+4. The default transcription model chosen by an administrator in the admin settings
+5. The connector's own model. For the OpenAI, Mistral and VibeVoice connectors this is `TRANSCRIPTION_MODEL`. The `asr_endpoint` connector has none: it sends no `model` parameter, and the ASR service uses its own default.
-If the override isn't in `TRANSCRIPTION_MODELS_AVAILABLE`, it's silently dropped and Speakr falls back to the global default — useful as a safety net against stale browser caches sending old model ids.
+If the override isn't in `TRANSCRIPTION_MODELS_AVAILABLE`, it's dropped with a warning in the log and the recording uses the connector's own model, which guards against stale browser caches sending old model ids. The same resolution applies to reprocessing, bulk reprocessing, API v1, watch folders, incognito mode and the startup voice embedding check.
The override is propagated to the connector via the `model` field on `TranscriptionRequest`. Connectors that key on a model name (OpenAI Whisper / Transcribe, Mistral, VibeVoice) honour it directly. The `asr_endpoint` connector forwards the override as a `model=` query parameter; the [whisperx-asr-service](https://github.com/murtaza-nasir/whisperx-asr-service) fork uses it to switch the loaded Whisper model on demand, while the upstream `ahmetoner/whisper-asr-webservice` ignores unknown query parameters, so the override is safe in either case.
diff --git a/docs/admin-guide/whisperx-setup.md b/docs/admin-guide/whisperx-setup.md
index 3b5d118d..917f9df9 100644
--- a/docs/admin-guide/whisperx-setup.md
+++ b/docs/admin-guide/whisperx-setup.md
@@ -224,7 +224,11 @@ COMPUTE_TYPE=int8
### Model Selection
-Models are selected per-recording in Speakr. Available options:
+Speakr sends a model with each request when one is configured: the model chosen at upload, a tag's or folder's default transcription model, or the default transcription model set by an administrator. When none of these is set, the request names no model and the service uses its own default.
+
+On whisperx-asr-service, that default is `PRELOAD_MODEL`, the model it also loads at startup. If `PRELOAD_MODEL` is empty, including when the service's `.env` omits it under Docker Compose, requests that name no model fail with `Invalid model size ''` on service versions before 0.4.2. Either set `PRELOAD_MODEL` (for example `large-v3`) in the service's `.env`, or choose a default transcription model in Speakr's admin settings. From 0.4.2 the service also accepts `DEFAULT_MODEL`, which sets the default without preloading anything, for a GPU shared with other applications.
+
+Available options:
| Model | Quality | Speed | VRAM Required |
|-------|---------|-------|---------------|
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 47d9092b..ef5f1aa5 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -1925,6 +1925,7 @@ def get_transcription_info():
'language_detection': True,
'chunking': False,
}
+ connector = None
if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
try:
from src.services.transcription import get_registry
@@ -1963,19 +1964,16 @@ def get_transcription_info():
except Exception:
models = []
if not models:
- from src.config.app_config import (
- TRANSCRIPTION_MODELS_AVAILABLE,
- TRANSCRIPTION_MODEL_LABELS,
- )
- if TRANSCRIPTION_MODELS_AVAILABLE:
- labels = TRANSCRIPTION_MODEL_LABELS or []
- for i, value in enumerate(TRANSCRIPTION_MODELS_AVAILABLE):
- models.append({
- 'value': value,
- 'label': labels[i] if i < len(labels) else value,
- })
-
- default_model = SystemSetting.get_setting('transcription_default_model', None) or TRANSCRIPTION_MODEL or None
+ # TRANSCRIPTION_MODELS_AVAILABLE paired with TRANSCRIPTION_MODEL_LABELS.
+ from src.config.app_config import TRANSCRIPTION_MODEL_OPTIONS
+ models = [dict(option) for option in TRANSCRIPTION_MODEL_OPTIONS]
+
+ # The model a transcription with no tag, folder or request choice uses:
+ # the admin default, else the connector's own configured model.
+ from src.services.transcription_defaults import resolve_transcription_model
+ default_model = (resolve_transcription_model(None)
+ or (getattr(connector, 'model', None) if connector else None)
+ or None)
return jsonify({
'connector': connector_name,
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 8ce726eb..9ab34519 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -3207,6 +3207,7 @@ def upload_incognito():
max_speakers = request.form.get('max_speakers')
hotwords = request.form.get('hotwords', '').strip() or None
initial_prompt = request.form.get('initial_prompt', '').strip() or None
+ transcription_model = request.form.get('transcription_model', '').strip() or None
auto_summarize = request.form.get('auto_summarize', 'false').lower() == 'true'
# Convert to int if provided
@@ -3237,7 +3238,8 @@ def upload_incognito():
max_speakers=max_speakers,
hotwords=hotwords,
initial_prompt=initial_prompt,
- user=current_user
+ user=current_user,
+ transcription_model=transcription_model
)
if result.get('error'):
@@ -4637,12 +4639,17 @@ def bulk_reprocess():
continue
job_type = 'reprocess_summary'
- # Queue the job
+ # Queue the job. A transcription reprocess gets the recording's
+ # resolved model, hotwords and speaker hints, as a single
+ # reprocess and API v1 batch transcribe do.
+ params = {'user_id': current_user.id}
+ if job_type == 'reprocess_transcription':
+ params = {**resolve_transcription_params(recording), **params}
job_queue.enqueue(
user_id=current_user.id,
recording_id=recording.id,
job_type=job_type,
- params={'user_id': current_user.id}
+ params=params
)
queued_ids.append(recording_id)
diff --git a/src/services/transcription/connectors/asr_endpoint.py b/src/services/transcription/connectors/asr_endpoint.py
index a5afef34..22a314e7 100644
--- a/src/services/transcription/connectors/asr_endpoint.py
+++ b/src/services/transcription/connectors/asr_endpoint.py
@@ -169,9 +169,12 @@ class ASREndpointConnector(BaseTranscriptionConnector):
# distil-medium.en) and switches the loaded Whisper model
# on demand. The upstream onerahmet/whisper-asr-webservice
# ignores unknown params, so this is safe in both cases.
- if request.model:
- params['model'] = request.model
- logger.info(f"Using per-request model override: {request.model}")
+ # Never an empty or whitespace name: the service would take it
+ # literally instead of using its own default model.
+ model = self._effective_model(request).strip()
+ if model:
+ params['model'] = model
+ logger.info(f"Using per-request model override: {model}")
content_type = request.mime_type or 'application/octet-stream'
files = {
@@ -228,7 +231,8 @@ class ASREndpointConnector(BaseTranscriptionConnector):
if len(body_excerpt) > 800:
body_excerpt = body_excerpt[:800] + '...'
logger.error(
- f"ASR request failed with status {e.response.status_code}: {body_excerpt}"
+ f"ASR request for {request.filename!r} failed with status "
+ f"{e.response.status_code}: {body_excerpt}"
)
detail = (
f"ASR request failed with status {e.response.status_code}: {body_excerpt}"
diff --git a/src/services/transcription_defaults.py b/src/services/transcription_defaults.py
index 4441d318..634f0802 100644
--- a/src/services/transcription_defaults.py
+++ b/src/services/transcription_defaults.py
@@ -83,7 +83,7 @@ def resolve_transcription_model(value):
return candidate
default = SystemSetting.get_setting('transcription_default_model', None)
- return default or None
+ return (default or '').strip() or None
def resolve_transcription_params(recording=None, overrides=None, *, tags=None, folder=None, owner=None):
diff --git a/src/services/voice_embedding_check.py b/src/services/voice_embedding_check.py
index 2faf3c78..382b4d26 100644
--- a/src/services/voice_embedding_check.py
+++ b/src/services/voice_embedding_check.py
@@ -79,6 +79,20 @@ def cosine_similarity(a, b):
return dot / (na * nb)
+def default_transcription_model():
+ """The model an upload gets with no tag, folder or per-upload choice.
+
+ The probe sends the same one, so it tests the configuration recordings
+ actually use and never depends on the service's own default (#409).
+ """
+ try:
+ from src.services.transcription_defaults import resolve_transcription_model
+ return resolve_transcription_model(None)
+ except Exception as e:
+ logger.debug(f"Could not resolve the default transcription model: {e}")
+ return None
+
+
def backend_fingerprint():
"""Identify the configured backend well enough to notice reconfiguration.
@@ -94,7 +108,10 @@ def backend_fingerprint():
parts = [
registry.get_active_connector_name() or '',
str(getattr(connector, 'base_url', '') or ''),
- str(getattr(connector, 'model', '') or ''),
+ # The model the probe sends. Without an admin default this is the
+ # connector's own model, as before, so stored fingerprints stay
+ # valid; choosing a default model triggers one fresh probe.
+ str(default_transcription_model() or getattr(connector, 'model', '') or ''),
]
except Exception as e:
logger.debug(f"Could not fingerprint the transcription backend: {e}")
@@ -142,6 +159,7 @@ def probe_backend():
diarize=True,
min_speakers=1,
max_speakers=1,
+ model=default_transcription_model(),
))
except Exception as e:
raise CanaryUnavailable(f'transcription of the canary failed: {e}')
@@ -236,7 +254,7 @@ def check_voice_embeddings(app, force=False):
try:
vector = probe_backend()
except CanaryUnavailable as e:
- logger.warning(f'Voice embedding check could not run: {e}')
+ logger.warning(canary_failure_message(e))
# Leave any existing reference and its status untouched. A backend
# that is down is not a backend that changed.
status = get_status(app)
@@ -368,6 +386,30 @@ def _clear_notification(app):
logger.warning('Could not clear the voice embedding notification: %s', e)
+def canary_failure_message(error):
+ """Log text for a check that could not run: what it was, and what to do.
+
+ The connector logs the failed request as an error on its own; without
+ this the line reads like a failed recording.
+ """
+ detail = str(error)
+ message = (
+ f"Voice embedding check could not run: {detail}. This came from the "
+ f"voice embedding check, which sends the bundled test clip "
+ f"{CANARY_FILENAME} to the transcription service; no recording was "
+ f"affected and nothing was changed."
+ )
+ lowered = detail.lower()
+ if 'invalid model size' in lowered or ("model" in lowered and "''" in detail):
+ message += (
+ " The service has no default model: set PRELOAD_MODEL (or "
+ "DEFAULT_MODEL on whisperx-asr-service 0.4.2 and later) on the ASR "
+ "service, or choose a default transcription model in Speakr's admin "
+ "settings."
+ )
+ return message
+
+
def _spaces(fn):
"""Run a voice-space update without ever failing the check."""
try:
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 05ca4b8e..d3519081 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -2561,7 +2561,7 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
db.session.commit()
-def transcribe_incognito(filepath, original_filename, language=None, min_speakers=None, max_speakers=None, hotwords=None, initial_prompt=None, user=None):
+def transcribe_incognito(filepath, original_filename, language=None, min_speakers=None, max_speakers=None, hotwords=None, initial_prompt=None, user=None, transcription_model=None):
"""
Perform transcription without any database operations.
Used for Incognito Mode where no data is persisted.
@@ -2575,6 +2575,8 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
hotwords: Optional comma-separated hotwords to bias recognition
initial_prompt: Optional initial prompt to steer transcription
user: Optional user object for language/diarization preferences
+ transcription_model: Optional model choice; validated and defaulted the
+ same way as for an upload (the admin default applies when empty)
Returns:
dict with transcription, title, processing_time, etc.
@@ -2713,13 +2715,19 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
should_chunk = (chunking_service and
chunking_service.needs_chunking(actual_filepath, False, connector_specs))
+ # Same model an upload would get, so a service without its own default
+ # model works in incognito mode too (#409).
+ from src.services.transcription_defaults import resolve_transcription_model
+ transcription_model = resolve_transcription_model(transcription_model)
+
current_app.logger.info(f"[Incognito] Starting transcription: diarize={should_diarize}, language={language}, chunking={should_chunk}")
if should_chunk:
# Use chunking for large files
chunk_result = transcribe_chunks_with_connector(
connector, actual_filepath, actual_filename, actual_content_type, language,
- diarize=should_diarize, hotwords=hotwords, initial_prompt=initial_prompt
+ diarize=should_diarize, hotwords=hotwords, initial_prompt=initial_prompt,
+ transcription_model=transcription_model
)
if hasattr(chunk_result, 'segments') and chunk_result.segments and chunk_result.has_diarization():
@@ -2738,7 +2746,8 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
min_speakers=min_speakers,
max_speakers=max_speakers,
prompt=initial_prompt,
- hotwords=hotwords
+ hotwords=hotwords,
+ model=transcription_model
)
response = connector.transcribe(request)
diff --git a/tests/test_model_defaults_409.py b/tests/test_model_defaults_409.py
new file mode 100644
index 00000000..e55baa38
--- /dev/null
+++ b/tests/test_model_defaults_409.py
@@ -0,0 +1,335 @@
+"""Every request names the model Speakr is configured to use (#409).
+
+whisperx-asr-service falls back to its own default model when a request names
+none, and that default is empty when PRELOAD_MODEL is empty. Speakr's startup
+voice embedding check sent no model at all, incognito mode ignored the admin
+default, and bulk reprocessing skipped the model, hotword and speaker hints
+entirely. These tests pin that every path resolves the model the same way an
+ordinary upload does, and that an empty or whitespace name is never sent.
+
+SHARED-DB: every test restores the admin default setting and removes its rows.
+"""
+
+import hashlib
+import io
+import json
+import logging
+import os
+import sys
+import uuid
+import wave
+from contextlib import contextmanager
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+from flask import g
+from flask.testing import FlaskClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import Recording, SystemSetting, Tag, User
+from src.services import voice_embedding_check as vec
+from src.services.transcription.base import TranscriptionRequest
+
+app.config["WTF_CSRF_ENABLED"] = False
+DEFAULT_KEY = 'transcription_default_model'
+REAL_HTTPX_CLIENT = httpx.Client
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def ctx():
+ with app.app_context():
+ saved = SystemSetting.get_setting(DEFAULT_KEY, None)
+ yield
+ db.session.rollback()
+ SystemSetting.set_setting(DEFAULT_KEY, saved or '', setting_type='string')
+
+
+def _set_default(value):
+ SystemSetting.set_setting(DEFAULT_KEY, value, setting_type='string')
+
+
+@contextmanager
+def _no_allowlist():
+ with patch("src.config.app_config.TRANSCRIPTION_MODELS_AVAILABLE", []), \
+ patch.object(SystemSetting, "get_setting", wraps=SystemSetting.get_setting) as get:
+ original = get.side_effect
+ yield
+
+
+def _user():
+ s = uuid.uuid4().hex[:8]
+ u = User(username=f"md_{s}", email=f"md_{s}@local.test", password="x")
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _client(user):
+ c = _Client(app, app.response_class)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+ return c
+
+
+# ------------------------------------------------------------ the resolver
+
+def test_the_stored_admin_default_is_stripped(ctx):
+ from src.services.transcription_defaults import resolve_transcription_model
+ _set_default(' large-v3 \t')
+ assert resolve_transcription_model(None) == 'large-v3'
+ _set_default(' ')
+ assert resolve_transcription_model(None) is None
+
+
+# ------------------------------------------------------------ asr_endpoint
+
+def _asr_connector():
+ from src.services.transcription.connectors.asr_endpoint import ASREndpointConnector
+ return ASREndpointConnector({'base_url': 'http://asr.test:9000'})
+
+
+def _send(connector, model, status=200, body=None):
+ """Transcribe through the connector against a fake service; return the
+ query parameters it received."""
+ seen = {}
+
+ def handler(request):
+ seen.update(dict(request.url.params))
+ if status != 200:
+ return httpx.Response(status, json=body or {"detail": "boom"})
+ return httpx.Response(200, json={"text": "hello", "language": "en", "segments": []})
+
+ transport = httpx.MockTransport(handler)
+ with patch("src.services.transcription.connectors.asr_endpoint.httpx.Client",
+ lambda *a, **k: REAL_HTTPX_CLIENT(transport=transport)):
+ try:
+ connector.transcribe(TranscriptionRequest(
+ audio_file=io.BytesIO(b"RIFF"), filename="clip.wav", mime_type="audio/wav", model=model))
+ except Exception:
+ pass
+ return seen
+
+
[email protected]("model", [None, "", " ", "\t\n"])
+def test_asr_endpoint_never_sends_an_empty_or_whitespace_model(ctx, model):
+ assert 'model' not in _send(_asr_connector(), model)
+
+
+def test_asr_endpoint_sends_a_real_model_stripped(ctx):
+ assert _send(_asr_connector(), " distil-large-v3.5 ")['model'] == 'distil-large-v3.5'
+
+
+def test_an_asr_failure_names_the_file_it_was_for(ctx, caplog):
+ with caplog.at_level(logging.ERROR):
+ _send(_asr_connector(), None, status=500, body={"detail": "Invalid model size ''"})
+ assert any("'clip.wav'" in r.getMessage() and "Invalid model size" in r.getMessage() for r in caplog.records)
+
+
+# ------------------------------------------------------------ the canary
+
+class _EmbeddingResponse:
+ speaker_embeddings = {'SPEAKER_00': [0.1] * 256}
+
+
+def _probe_capturing():
+ seen = {}
+
+ class _Conn:
+ def transcribe(self, request):
+ seen['model'] = request.model
+ seen['filename'] = request.filename
+ return _EmbeddingResponse()
+
+ with patch('src.services.transcription.registry.get_registry') as reg:
+ reg.return_value.get_active_connector.return_value = _Conn()
+ vec.probe_backend()
+ return seen
+
+
+def test_the_canary_sends_the_admin_default_model(ctx):
+ _set_default('large-v3')
+ assert _probe_capturing()['model'] == 'large-v3'
+
+
+def test_the_canary_sends_no_model_when_none_is_configured(ctx):
+ _set_default('')
+ assert _probe_capturing()['model'] is None
+
+
+def _fingerprint_with(connector_model):
+ conn = MagicMock()
+ conn.base_url = 'http://asr.test:9000'
+ conn.model = connector_model
+ with patch('src.services.transcription.registry.get_registry') as reg:
+ reg.return_value.get_active_connector.return_value = conn
+ reg.return_value.get_active_connector_name.return_value = 'asr_endpoint'
+ return vec.backend_fingerprint()
+
+
+def test_the_fingerprint_is_unchanged_without_an_admin_default(ctx):
+ """Existing installations keep their stored fingerprint, so upgrading
+ does not re-run the probe for nothing."""
+ _set_default('')
+ before = hashlib.sha256('asr_endpoint|http://asr.test:9000|'.encode()).hexdigest()[:16]
+ assert _fingerprint_with('') == before
+
+
+def test_choosing_an_admin_default_changes_the_fingerprint(ctx):
+ _set_default('')
+ without = _fingerprint_with('')
+ _set_default('large-v3')
+ assert _fingerprint_with('') != without
+
+
+def test_a_failed_canary_says_where_it_came_from_and_what_to_do(ctx, caplog):
+ message = vec.canary_failure_message(vec.CanaryUnavailable(
+ "transcription of the canary failed: ASR request failed with status 500: "
+ "{\"detail\":\"Invalid model size '', expected one of: tiny\"}"))
+ assert 'voice embedding check' in message and vec.CANARY_FILENAME in message
+ assert 'no recording was affected' in message
+ assert 'PRELOAD_MODEL' in message and 'default transcription model' in message
+
+
+def test_an_unrelated_canary_failure_gets_no_model_hint(ctx):
+ message = vec.canary_failure_message(vec.CanaryUnavailable('connection refused'))
+ assert 'PRELOAD_MODEL' not in message and 'no recording was affected' in message
+
+
+def test_the_check_logs_the_explanatory_warning(ctx, caplog):
+ with patch.object(vec, 'embeddings_supported', return_value=True), \
+ patch.object(vec, 'probe_backend', side_effect=vec.CanaryUnavailable("Invalid model size ''")), \
+ caplog.at_level(logging.WARNING):
+ vec.check_voice_embeddings(app, force=True)
+ assert any('no recording was affected' in r.getMessage() and 'PRELOAD_MODEL' in r.getMessage()
+ for r in caplog.records)
+
+
+# ------------------------------------------------------------ incognito
+
+def _wav(tmp_path):
+ path = os.path.join(str(tmp_path), 'incognito.wav')
+ with wave.open(path, 'wb') as w:
+ w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000)
+ w.writeframes(b'\x00\x00' * 1600)
+ return path
+
+
+def _passthrough(filepath, **kwargs):
+ r = MagicMock()
+ r.output_path = filepath
+ r.was_converted = r.was_compressed = False
+ return r
+
+
[email protected]("chunked", [False, True])
+def test_incognito_uses_the_admin_default_model(ctx, tmp_path, chunked):
+ from src.tasks import processing
+ _set_default('large-v3')
+ seen = {}
+
+ class _Resp:
+ segments = []
+ text = 'hello'
+ def has_diarization(self):
+ return False
+
+ class _Conn:
+ specifications = MagicMock()
+ supports_diarization = False
+ def transcribe(self, request):
+ seen['model'] = request.model
+ return _Resp()
+
+ def _chunks(*args, **kwargs):
+ seen['model'] = kwargs.get('transcription_model')
+ return _Resp()
+
+ chunker = MagicMock()
+ chunker.needs_chunking.return_value = chunked
+ chunker.get_audio_duration.return_value = 1
+ with patch('src.services.transcription.get_registry') as reg, \
+ patch.object(processing, 'convert_if_needed', side_effect=_passthrough), \
+ patch.object(processing, 'is_video_file', return_value=False), \
+ patch.object(processing, 'chunking_service', chunker), \
+ patch.object(processing, 'transcribe_chunks_with_connector', side_effect=_chunks):
+ reg.return_value.get_active_connector.return_value = _Conn()
+ processing.transcribe_incognito(_wav(tmp_path), 'incognito.wav', language='en')
+ assert seen.get('model') == 'large-v3'
+
+
+# ------------------------------------------------------------ bulk reprocess
+
+def test_bulk_reprocess_transcription_uses_the_resolved_params(ctx):
+ user = _user()
+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id, default_transcription_model='medium',
+ default_hotwords='Speakr, WhisperX', default_min_speakers=2, default_max_speakers=4)
+ db.session.add(tag)
+ db.session.commit()
+ rec = Recording(user_id=user.id, title='r', status='COMPLETED', audio_path='local://x.mp3',
+ original_filename='x.mp3', transcription='[]')
+ db.session.add(rec)
+ db.session.commit()
+ from src.models import RecordingTag
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.commit()
+ try:
+ storage = MagicMock()
+ storage.exists.return_value = True
+ with patch('src.api.recordings.get_storage_service', return_value=storage), \
+ patch('src.api.recordings.job_queue.enqueue', return_value=1) as enqueue:
+ r = _client(user).post('/api/recordings/bulk-reprocess',
+ json={'recording_ids': [rec.id], 'type': 'transcription'})
+ assert r.status_code == 200, r.get_data(as_text=True)
+ params = enqueue.call_args.kwargs['params']
+ assert params['user_id'] == user.id
+ assert params['transcription_model'] == 'medium'
+ assert params['hotwords'] == 'Speakr, WhisperX'
+ assert params['min_speakers'] == 2 and params['max_speakers'] == 4
+ finally:
+ RecordingTag.query.filter_by(recording_id=rec.id).delete()
+ db.session.delete(db.session.get(Recording, rec.id))
+ db.session.delete(db.session.get(Tag, tag.id))
+ db.session.delete(db.session.get(User, user.id))
+ db.session.commit()
+
+
+# ------------------------------------------------------------ API v1
+
+def test_api_capabilities_report_the_default_the_resolver_uses(ctx):
+ from src.services.transcription_defaults import resolve_transcription_model
+ user = _user()
+ try:
+ _set_default(' large-v3 ')
+ body = _client(user).get('/api/v1/transcription').get_json()
+ assert body['default_model'] == resolve_transcription_model(None) == 'large-v3'
+ finally:
+ db.session.delete(db.session.get(User, user.id))
+ db.session.commit()
+
+
+def test_api_capabilities_list_env_models_without_an_admin_list(ctx):
+ """The endpoint imported a name that does not exist and returned 500
+ whenever the admin had not saved a model list."""
+ user = _user()
+ saved = SystemSetting.get_setting('transcription_models_visible_json', None)
+ try:
+ SystemSetting.set_setting('transcription_models_visible_json', '', setting_type='string')
+ options = [{'value': 'large-v3', 'label': 'Large v3'}, {'value': 'medium', 'label': 'medium'}]
+ with patch('src.config.app_config.TRANSCRIPTION_MODEL_OPTIONS', options):
+ r = _client(user).get('/api/v1/transcription')
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert r.get_json()['models'] == options
+ finally:
+ SystemSetting.set_setting('transcription_models_visible_json', saved or '', setting_type='string')
+ db.session.delete(db.session.get(User, user.id))
+ db.session.commit()