Skip to content

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

Python

Add per-upload, per-tag, per-folder transcription model selection via TRANSCRIPTION_MODELS_AVAILABLE

Murtaza Nasir46f6b325e3aa
diff --git a/src/api/recordings.py b/src/api/recordings.py
index f61b6ed8..90e4197f 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -973,6 +973,7 @@ def reprocess_transcription(recording_id):
max_speakers = data.get('max_speakers') or None
hotwords = (data.get('hotwords') or '').strip() or None
initial_prompt = (data.get('initial_prompt') or '').strip() or None
+ transcription_model = (data.get('transcription_model') or '').strip() or None
# Convert to int if provided
if min_speakers:
@@ -1002,8 +1003,10 @@ def reprocess_transcription(recording_id):
hotwords = tag.default_hotwords
if not initial_prompt and tag.default_initial_prompt:
initial_prompt = tag.default_initial_prompt
+ if not transcription_model and tag.default_transcription_model:
+ transcription_model = tag.default_transcription_model
if (min_speakers is not None and max_speakers is not None
- and hotwords and initial_prompt):
+ and hotwords and initial_prompt and transcription_model):
break
# Folder defaults (only if recording has no tags providing the value)
@@ -1017,6 +1020,8 @@ def reprocess_transcription(recording_id):
hotwords = folder.default_hotwords
if not initial_prompt and folder.default_initial_prompt:
initial_prompt = folder.default_initial_prompt
+ if not transcription_model and folder.default_transcription_model:
+ transcription_model = folder.default_transcription_model
# Environment variable defaults
if min_speakers is None and ASR_MIN_SPEAKERS:
@@ -1039,6 +1044,17 @@ def reprocess_transcription(recording_id):
if not initial_prompt and owner.transcription_initial_prompt:
initial_prompt = owner.transcription_initial_prompt
+ # Validate the per-request model against the configured allowlist before
+ # passing it to the connector. If the user submitted an unknown model
+ # (e.g. via a stale UI cache), drop it rather than crashing the API.
+ if transcription_model:
+ from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
+ if TRANSCRIPTION_MODELS_AVAILABLE and transcription_model not in TRANSCRIPTION_MODELS_AVAILABLE:
+ current_app.logger.warning(
+ f"Ignoring transcription_model={transcription_model!r} — not in TRANSCRIPTION_MODELS_AVAILABLE"
+ )
+ transcription_model = None
+
# Enqueue the job with all parameters
job_params = {
'language': language,
@@ -1046,6 +1062,7 @@ def reprocess_transcription(recording_id):
'max_speakers': max_speakers,
'hotwords': hotwords,
'initial_prompt': initial_prompt,
+ 'transcription_model': transcription_model,
}
job_id = job_queue.enqueue(
@@ -2160,6 +2177,7 @@ def upload_file():
max_speakers = request.form.get('max_speakers') or None
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
# Convert to int if provided
if min_speakers:
@@ -2188,6 +2206,8 @@ def upload_file():
hotwords = selected_folder.default_hotwords
if not initial_prompt and selected_folder.default_initial_prompt:
initial_prompt = selected_folder.default_initial_prompt
+ if not transcription_model and selected_folder.default_transcription_model:
+ transcription_model = selected_folder.default_transcription_model
# Apply tag defaults if tags are selected and values are not explicitly provided by user
# Use first tag's defaults (highest priority - overrides folder)
@@ -2203,6 +2223,8 @@ def upload_file():
hotwords = first_tag.default_hotwords
if not initial_prompt and first_tag.default_initial_prompt:
initial_prompt = first_tag.default_initial_prompt
+ if not transcription_model and first_tag.default_transcription_model:
+ transcription_model = first_tag.default_transcription_model
# Apply environment variable defaults if still no values are set
if min_speakers is None and ASR_MIN_SPEAKERS:
@@ -2296,6 +2318,18 @@ def upload_file():
current_app.logger.info(f"Initial recording record created with ID: {recording.id}")
+ # Validate the per-request transcription_model against the configured
+ # allowlist before passing it to the connector. If the user submitted
+ # an unknown model (e.g. via a stale UI cache), drop it rather than
+ # propagating a bad value into the worker.
+ if transcription_model:
+ from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
+ if TRANSCRIPTION_MODELS_AVAILABLE and transcription_model not in TRANSCRIPTION_MODELS_AVAILABLE:
+ current_app.logger.warning(
+ f"Ignoring transcription_model={transcription_model!r} — not in TRANSCRIPTION_MODELS_AVAILABLE"
+ )
+ transcription_model = None
+
# --- Queue transcription job ---
first_tag = selected_tags[0] if selected_tags else None
job_params = {
@@ -2305,6 +2339,7 @@ def upload_file():
'tag_id': first_tag.id if first_tag else None,
'hotwords': hotwords,
'initial_prompt': initial_prompt,
+ 'transcription_model': transcription_model,
}
current_app.logger.info(f"Queueing transcription for recording {recording.id} with params: {job_params}")
diff --git a/src/api/system.py b/src/api/system.py
index 9a5d7b8b..a8af6f41 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -16,7 +16,7 @@ from src.models import *
from src.utils import *
from src.config.version import get_version
from src.services.llm import TEXT_MODEL_BASE_URL, TEXT_MODEL_NAME
-from src.config.app_config import ASR_BASE_URL, USE_NEW_TRANSCRIPTION_ARCHITECTURE
+from src.config.app_config import ASR_BASE_URL, USE_NEW_TRANSCRIPTION_ARCHITECTURE, TRANSCRIPTION_MODEL_OPTIONS
from src.services.token_tracking import token_tracker
from src.services.transcription import TranscriptionCapability
@@ -179,6 +179,15 @@ def get_system_info():
# --- Tag API Endpoints ---
+def _get_transcription_model_options():
+ """Return the configured per-upload transcription model dropdown options.
+
+ When TRANSCRIPTION_MODELS_AVAILABLE is unset the list is empty and the
+ frontend hides the dropdown. Issue #266.
+ """
+ return list(TRANSCRIPTION_MODEL_OPTIONS)
+
+
@system_bp.route('/api/config', methods=['GET'])
def get_config():
"""Get application configuration settings for the frontend."""
@@ -265,6 +274,7 @@ def get_config():
'video_retention': VIDEO_RETENTION,
'max_concurrent_uploads': MAX_CONCURRENT_UPLOADS,
'user_transcription_language': user_transcription_language,
+ 'transcription_model_options': _get_transcription_model_options(),
**chunking_info
})
except Exception as e:
diff --git a/src/config/app_config.py b/src/config/app_config.py
index a85afc70..b4111b16 100644
--- a/src/config/app_config.py
+++ b/src/config/app_config.py
@@ -30,6 +30,23 @@ TRANSCRIPTION_MODEL = os.environ.get('TRANSCRIPTION_MODEL', '')
if TRANSCRIPTION_MODEL:
TRANSCRIPTION_MODEL = TRANSCRIPTION_MODEL.split('#')[0].strip()
+# Optional comma-separated list of transcription models the user can pick from
+# at upload/reprocess time, or set as a default on a tag/folder. When empty,
+# the model dropdown is hidden and TRANSCRIPTION_MODEL above is the only model.
+# Example: TRANSCRIPTION_MODELS_AVAILABLE=whisper-1,gpt-4o-transcribe,gpt-4o-transcribe-diarize
+# Optional parallel labels: TRANSCRIPTION_MODEL_LABELS=Whisper,GPT-4o,GPT-4o Diarize
+def _parse_models_csv(raw):
+ return [m.strip() for m in raw.split(',') if m.strip()]
+
+TRANSCRIPTION_MODELS_AVAILABLE = _parse_models_csv(os.environ.get('TRANSCRIPTION_MODELS_AVAILABLE', ''))
+_labels_raw = os.environ.get('TRANSCRIPTION_MODEL_LABELS', '')
+_labels = _parse_models_csv(_labels_raw)
+# Pair each model with a label, falling back to the model id if no label given.
+TRANSCRIPTION_MODEL_OPTIONS = [
+ {'value': m, 'label': _labels[i] if i < len(_labels) else m}
+ for i, m in enumerate(TRANSCRIPTION_MODELS_AVAILABLE)
+]
+
# Feature flag for new transcription architecture (default: enabled)
USE_NEW_TRANSCRIPTION_ARCHITECTURE = os.environ.get(
'USE_NEW_TRANSCRIPTION_ARCHITECTURE', 'true'
diff --git a/src/init_db.py b/src/init_db.py
index 4a237baa..bf579bdf 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -549,6 +549,12 @@ def initialize_database(app):
# Add folder_id column to recording table for folders feature
if add_column_if_not_exists(engine, 'recording', 'folder_id', 'INTEGER'):
app.logger.info("Added folder_id column to recording table")
+
+ # Add default_transcription_model columns to tag and folder for per-tag/per-folder model selection (issue #266)
+ if add_column_if_not_exists(engine, 'tag', 'default_transcription_model', 'VARCHAR(120)'):
+ app.logger.info("Added default_transcription_model column to tag table")
+ if add_column_if_not_exists(engine, 'folder', 'default_transcription_model', 'VARCHAR(120)'):
+ app.logger.info("Added default_transcription_model column to folder table")
# Create index for folder_id
try:
if create_index_if_not_exists(engine, 'ix_recording_folder_id', 'recording', 'folder_id'):
diff --git a/src/models/organization.py b/src/models/organization.py
index 5bf4724c..25d6a6a9 100644
--- a/src/models/organization.py
+++ b/src/models/organization.py
@@ -98,6 +98,7 @@ class Folder(db.Model):
# Transcription hints
default_hotwords = db.Column(db.Text, nullable=True) # Comma-separated words to bias recognition
default_initial_prompt = db.Column(db.Text, nullable=True) # Initial prompt to steer transcription
+ default_transcription_model = db.Column(db.String(120), nullable=True) # Override TRANSCRIPTION_MODEL when set
# Retention and deletion settings
protect_from_deletion = db.Column(db.Boolean, default=False) # Exempt recordings in folder from auto-deletion
@@ -147,6 +148,7 @@ class Folder(db.Model):
'default_max_speakers': self.default_max_speakers,
'default_hotwords': self.default_hotwords,
'default_initial_prompt': self.default_initial_prompt,
+ 'default_transcription_model': self.default_transcription_model,
'protect_from_deletion': self.protect_from_deletion,
'retention_days': self.retention_days,
'auto_share_on_apply': self.auto_share_on_apply,
@@ -178,6 +180,7 @@ class Tag(db.Model):
# Transcription hints
default_hotwords = db.Column(db.Text, nullable=True) # Comma-separated words to bias recognition
default_initial_prompt = db.Column(db.Text, nullable=True) # Initial prompt to steer transcription
+ default_transcription_model = db.Column(db.String(120), nullable=True) # Override TRANSCRIPTION_MODEL when set
# Retention and deletion settings
protect_from_deletion = db.Column(db.Boolean, default=False) # Exempt tagged recordings from auto-deletion
@@ -231,6 +234,7 @@ class Tag(db.Model):
'default_max_speakers': self.default_max_speakers,
'default_hotwords': self.default_hotwords,
'default_initial_prompt': self.default_initial_prompt,
+ 'default_transcription_model': self.default_transcription_model,
'protect_from_deletion': self.protect_from_deletion,
'retention_days': self.retention_days,
'auto_share_on_apply': self.auto_share_on_apply,
diff --git a/src/services/job_queue.py b/src/services/job_queue.py
index 4c25e6f4..92c2ffc8 100644
--- a/src/services/job_queue.py
+++ b/src/services/job_queue.py
@@ -401,6 +401,7 @@ class FairJobQueue:
tag_id=params.get('tag_id'),
hotwords=params.get('hotwords'),
initial_prompt=params.get('initial_prompt'),
+ transcription_model=params.get('transcription_model'),
)
def _run_summarization(self, job, recording, params):
@@ -435,6 +436,7 @@ class FairJobQueue:
tag_id=params.get('tag_id'),
hotwords=params.get('hotwords'),
initial_prompt=params.get('initial_prompt'),
+ transcription_model=params.get('transcription_model'),
)
def _run_reprocess_summary(self, job, recording, params):
diff --git a/src/services/transcription/base.py b/src/services/transcription/base.py
index 6ce0aa0f..20ea75fb 100644
--- a/src/services/transcription/base.py
+++ b/src/services/transcription/base.py
@@ -75,6 +75,11 @@ class TranscriptionRequest:
hotwords: Optional[str] = None # Comma-separated words to bias recognition
temperature: Optional[float] = None
+ # Per-request model override. When set, the connector uses this model name
+ # instead of its configured default. Only honoured if the connector supports
+ # multiple models (asr_endpoint, openai_*, mistral). Issue #266.
+ model: Optional[str] = None
+
# Provider-specific options (passthrough)
extra_options: Dict[str, Any] = field(default_factory=dict)
@@ -198,6 +203,15 @@ class BaseTranscriptionConnector(ABC):
"""Check if connector supports a capability."""
return capability in self.CAPABILITIES
+ def _effective_model(self, request: 'TranscriptionRequest') -> str:
+ """Resolve which model to use for a given request.
+
+ Honours the per-request override (issue #266) if present, otherwise
+ falls back to the connector's configured default model.
+ """
+ override = (request.model or '').strip() if request and request.model else ''
+ return override or getattr(self, 'model', '') or ''
+
def get_capabilities(self) -> Set[TranscriptionCapability]:
"""Get all supported capabilities."""
return self.CAPABILITIES.copy()
diff --git a/src/services/transcription/connectors/azure_openai_transcribe.py b/src/services/transcription/connectors/azure_openai_transcribe.py
index c4e92418..b53e7374 100644
--- a/src/services/transcription/connectors/azure_openai_transcribe.py
+++ b/src/services/transcription/connectors/azure_openai_transcribe.py
@@ -176,6 +176,13 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
try:
url = self._build_url()
+ # Per-request model override (issue #266). Note: Azure routes by
+ # deployment_name (URL path), not model — overriding this only
+ # affects response_format selection (text vs diarized) and the
+ # logged model id. To run a different model the deployment itself
+ # has to point at it.
+ effective_model = self._effective_model(request) or self.model
+
# Build form data
data = {}
@@ -184,7 +191,7 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
logger.info(f"Using transcription language: {request.language}")
# Handle diarization model specifics
- is_diarize_model = 'diarize' in self.model.lower()
+ is_diarize_model = 'diarize' in effective_model.lower()
if is_diarize_model:
# Required: chunking_strategy for audio > 30 seconds
@@ -220,7 +227,7 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
}
logger.info(f"Sending request to Azure OpenAI: {url}")
- logger.info(f"Model: {self.model}, Deployment: {self.deployment_name}")
+ logger.info(f"Model: {effective_model}, Deployment: {self.deployment_name}")
response = self.http_client.post(url, data=data, files=files)
@@ -239,9 +246,9 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
# Parse response based on format
if is_diarize_model and request.diarize:
- return self._parse_diarized_response(result)
+ return self._parse_diarized_response(result, effective_model)
else:
- return self._parse_response(result)
+ return self._parse_response(result, effective_model)
except TranscriptionError:
raise
@@ -250,7 +257,7 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
logger.error(f"Azure OpenAI transcription failed: {error_msg}")
raise TranscriptionError(f"Azure OpenAI transcription failed: {error_msg}") from e
- def _parse_response(self, response: Dict) -> TranscriptionResponse:
+ def _parse_response(self, response: Dict, model_used: Optional[str] = None) -> TranscriptionResponse:
"""Parse a standard (non-diarized) response."""
text = response.get('text', '')
@@ -269,11 +276,11 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
segments=segments if segments else None,
language=response.get('language'),
provider=self.PROVIDER_NAME,
- model=self.model,
+ model=model_used or self.model,
raw_response=response
)
- def _parse_diarized_response(self, response: Dict) -> TranscriptionResponse:
+ def _parse_diarized_response(self, response: Dict, model_used: Optional[str] = None) -> TranscriptionResponse:
"""
Parse diarized JSON response into standardized format.
@@ -325,10 +332,12 @@ class AzureOpenAITranscribeConnector(BaseTranscriptionConnector):
speakers=sorted(list(speakers)),
language=response.get('language'),
provider=self.PROVIDER_NAME,
- model=self.model,
+ model=model_used or self.model,
raw_response=response
)
+ # NB: _parse_diarized_response falls back to _parse_response above
+
def health_check(self) -> bool:
"""Check if the connector is properly configured."""
return bool(
diff --git a/src/services/transcription/connectors/mistral.py b/src/services/transcription/connectors/mistral.py
index 3d2b348c..050b90b7 100644
--- a/src/services/transcription/connectors/mistral.py
+++ b/src/services/transcription/connectors/mistral.py
@@ -109,11 +109,12 @@ class MistralTranscriptionConnector(BaseTranscriptionConnector):
TranscriptionResponse with text, segments, and optional diarization
"""
try:
+ effective_model = self._effective_model(request) or self.model
# Build multipart form data using tuples for proper array encoding
file_tuple = ('file', (request.filename or 'audio.wav', request.audio_file, request.mime_type or 'application/octet-stream'))
fields: List[tuple] = [
- ('model', self.model),
+ ('model', effective_model),
]
# Language param
@@ -143,7 +144,7 @@ class MistralTranscriptionConnector(BaseTranscriptionConnector):
if request.prompt:
logger.warning("Mistral Voxtral does not support initial_prompt parameter, ignoring")
- logger.info(f"Sending request to Mistral API with model: {self.model}")
+ logger.info(f"Sending request to Mistral API with model: {effective_model}")
response = self.client.post(
'/v1/audio/transcriptions',
files=[file_tuple] + [(name, (None, value)) for name, value in fields],
@@ -185,7 +186,7 @@ class MistralTranscriptionConnector(BaseTranscriptionConnector):
language=detected_language,
speakers=speakers if speakers else None,
provider=self.PROVIDER_NAME,
- model=self.model,
+ model=effective_model,
raw_response=result,
)
diff --git a/src/services/transcription/connectors/openai_transcribe.py b/src/services/transcription/connectors/openai_transcribe.py
index f6828031..2a4317a9 100644
--- a/src/services/transcription/connectors/openai_transcribe.py
+++ b/src/services/transcription/connectors/openai_transcribe.py
@@ -162,8 +162,17 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):
TranscriptionResponse, with segments if using diarization model
"""
try:
+ effective_model = self._effective_model(request) or self.model
+ # Validate the per-request override against this connector's known
+ # model whitelist; fall back silently if the override is unknown.
+ if effective_model not in self.MODELS:
+ logger.warning(
+ f"Per-request model override {effective_model!r} is not in this connector's MODELS map; "
+ f"falling back to configured default {self.model!r}"
+ )
+ effective_model = self.model
params = {
- "model": self.model,
+ "model": effective_model,
"file": request.audio_file,
}
@@ -172,7 +181,7 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):
logger.info(f"Using transcription language: {request.language}")
# Handle diarization model specifics
- if self.model == 'gpt-4o-transcribe-diarize':
+ if effective_model == 'gpt-4o-transcribe-diarize':
# Required: chunking_strategy for audio > 30 seconds
params["chunking_strategy"] = "auto"
@@ -210,30 +219,30 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):
if prompt_parts:
params["prompt"] = ". ".join(prompt_parts)
- logger.info(f"Sending request to GPT-4o Transcribe API with model: {self.model}")
+ logger.info(f"Sending request to GPT-4o Transcribe API with model: {effective_model}")
response = self.client.audio.transcriptions.create(**params)
# Parse response based on format
- if self.model == 'gpt-4o-transcribe-diarize' and request.diarize:
- return self._parse_diarized_response(response)
+ if effective_model == 'gpt-4o-transcribe-diarize' and request.diarize:
+ return self._parse_diarized_response(response, effective_model)
else:
- return self._parse_text_response(response)
+ return self._parse_text_response(response, effective_model)
except Exception as e:
error_msg = str(e)
logger.error(f"GPT-4o transcription failed: {error_msg}")
raise TranscriptionError(f"GPT-4o transcription failed: {error_msg}") from e
- def _parse_text_response(self, response) -> TranscriptionResponse:
+ def _parse_text_response(self, response, model_used: Optional[str] = None) -> TranscriptionResponse:
"""Parse a plain text response."""
text = response.text if hasattr(response, 'text') else str(response)
return TranscriptionResponse(
text=text,
provider=self.PROVIDER_NAME,
- model=self.model
+ model=model_used or self.model
)
- def _parse_diarized_response(self, response) -> TranscriptionResponse:
+ def _parse_diarized_response(self, response, model_used: Optional[str] = None) -> TranscriptionResponse:
"""
Parse diarized JSON response into standardized format.
@@ -295,7 +304,7 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):
segments=segments,
speakers=sorted(list(speakers)),
provider=self.PROVIDER_NAME,
- model=self.model,
+ model=model_used or self.model,
raw_response=response if isinstance(response, dict) else None
)
diff --git a/src/services/transcription/connectors/openai_whisper.py b/src/services/transcription/connectors/openai_whisper.py
index b52ad0a4..96fb0b92 100644
--- a/src/services/transcription/connectors/openai_whisper.py
+++ b/src/services/transcription/connectors/openai_whisper.py
@@ -89,8 +89,9 @@ class OpenAIWhisperConnector(BaseTranscriptionConnector):
TranscriptionResponse with plain text (no diarization)
"""
try:
+ effective_model = self._effective_model(request)
params = {
- "model": self.model,
+ "model": effective_model,
"file": request.audio_file,
}
@@ -111,13 +112,13 @@ class OpenAIWhisperConnector(BaseTranscriptionConnector):
if request.temperature is not None:
params["temperature"] = request.temperature
- logger.info(f"Sending request to Whisper API with model: {self.model}")
+ logger.info(f"Sending request to Whisper API with model: {effective_model}")
transcript = self.client.audio.transcriptions.create(**params)
return TranscriptionResponse(
text=transcript.text,
provider=self.PROVIDER_NAME,
- model=self.model
+ model=effective_model
)
except Exception as e:
diff --git a/src/services/transcription/connectors/vibevoice.py b/src/services/transcription/connectors/vibevoice.py
index d74ac916..4eaa4aa3 100644
--- a/src/services/transcription/connectors/vibevoice.py
+++ b/src/services/transcription/connectors/vibevoice.py
@@ -113,6 +113,7 @@ class VibeVoiceTranscriptionConnector(BaseTranscriptionConnector):
The model returns a JSON array of segments with speaker, timestamps, and text.
"""
try:
+ effective_model = self._effective_model(request) or self.model
# Read and base64-encode the audio
audio_bytes = request.audio_file.read()
audio_b64 = base64.b64encode(audio_bytes).decode('utf-8')
@@ -152,7 +153,7 @@ class VibeVoiceTranscriptionConnector(BaseTranscriptionConnector):
# Build the chat completion request per VibeVoice docs
payload = {
- "model": self.model,
+ "model": effective_model,
"messages": [
{
"role": "system",
@@ -171,7 +172,7 @@ class VibeVoiceTranscriptionConnector(BaseTranscriptionConnector):
"top_p": 1.0,
}
- logger.info(f"Sending request to VibeVoice at {self.base_url} (duration={duration}s, model={self.model})")
+ logger.info(f"Sending request to VibeVoice at {self.base_url} (duration={duration}s, model={effective_model})")
response = self.client.post('/v1/chat/completions', json=payload)
if response.status_code != 200:
@@ -212,7 +213,7 @@ class VibeVoiceTranscriptionConnector(BaseTranscriptionConnector):
segments=segments,
speakers=speakers if speakers else None,
provider=self.PROVIDER_NAME,
- model=self.model,
+ model=effective_model,
raw_response=result,
)
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 2f4d7d70..a385f378 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1232,7 +1232,7 @@ def merge_diarized_chunks(chunk_results):
return merged_text, merged_segments, sorted(list(all_speakers))
-def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, language, diarize=False, hotwords=None, initial_prompt=None):
+def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, language, diarize=False, hotwords=None, initial_prompt=None, transcription_model=None):
"""
Transcribe a large audio file using chunking with the connector architecture.
@@ -1315,6 +1315,7 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l
known_speaker_references=known_speaker_refs,
prompt=initial_prompt,
hotwords=hotwords,
+ model=transcription_model,
)
else:
request = TranscriptionRequest(
@@ -1325,6 +1326,7 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l
diarize=False,
prompt=initial_prompt,
hotwords=hotwords,
+ model=transcription_model,
)
response = connector.transcribe(request)
@@ -1436,7 +1438,7 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l
raise ChunkProcessingError(f"Chunked transcription failed: {str(e)}")
-def transcribe_with_connector(app_context, recording_id, filepath, original_filename, start_time, mime_type=None, language=None, diarize=None, min_speakers=None, max_speakers=None, tag_id=None, hotwords=None, initial_prompt=None):
+def transcribe_with_connector(app_context, recording_id, filepath, original_filename, start_time, mime_type=None, language=None, diarize=None, min_speakers=None, max_speakers=None, tag_id=None, hotwords=None, initial_prompt=None, transcription_model=None):
"""
Transcribe audio using the new connector-based architecture.
@@ -1672,6 +1674,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
diarize=should_diarize, # Pass diarization setting for speaker reference tracking
hotwords=hotwords,
initial_prompt=initial_prompt,
+ transcription_model=transcription_model,
)
# Handle result based on type (TranscriptionResponse for diarized, string for plain)
@@ -1697,6 +1700,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
max_speakers=max_speakers,
prompt=initial_prompt,
hotwords=hotwords,
+ model=transcription_model,
)
current_app.logger.info(f"Transcribing with connector: diarize={should_diarize}, language={language}")
@@ -1906,7 +1910,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
raise
-def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None, hotwords=None, initial_prompt=None):
+def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None, hotwords=None, initial_prompt=None, transcription_model=None):
"""Runs the transcription and summarization in a background thread.
Uses the connector-based architecture which supports:
@@ -1955,6 +1959,7 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
tag_id=tag_id,
hotwords=hotwords,
initial_prompt=initial_prompt,
+ transcription_model=transcription_model,
)
# After transcription completes, calculate processing time
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index d8ab680f..d1efe32f 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -394,6 +394,8 @@ document.addEventListener('DOMContentLoaded', async () => {
const uploadMaxSpeakers = ref('');
const uploadHotwords = ref('');
const uploadInitialPrompt = ref('');
+ const uploadTranscriptionModel = ref('');
+ const transcriptionModelOptions = ref([]);
// Tag Selection
const availableTags = ref([]);
@@ -662,7 +664,7 @@ document.addEventListener('DOMContentLoaded', async () => {
maxConcurrentUploads, recordingDisclaimer, showRecordingDisclaimerModal, pendingRecordingMode,
uploadDisclaimer, showUploadDisclaimerModal,
customBanner, showBanner,
- showAdvancedOptions, userTranscriptionLanguage, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers, uploadHotwords, uploadInitialPrompt,
+ showAdvancedOptions, userTranscriptionLanguage, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers, uploadHotwords, uploadInitialPrompt, uploadTranscriptionModel, transcriptionModelOptions,
availableTags, selectedTagIds, uploadTagSearchFilter,
availableFolders, selectedFolderId, foldersEnabled, filterFolder,
@@ -2305,6 +2307,13 @@ document.addEventListener('DOMContentLoaded', async () => {
foldersEnabled.value = config.enable_folders === true;
maxConcurrentUploads.value = config.max_concurrent_uploads || 3;
+ // Per-upload transcription model dropdown options
+ // (issue #266). Only set when admin configured at least
+ // one model in TRANSCRIPTION_MODELS_AVAILABLE.
+ transcriptionModelOptions.value = Array.isArray(config.transcription_model_options)
+ ? config.transcription_model_options
+ : [];
+
// Set user's default transcription language for upload and reprocess forms
if (config.user_transcription_language) {
userTranscriptionLanguage.value = config.user_transcription_language;
diff --git a/static/js/modules/composables/reprocess.js b/static/js/modules/composables/reprocess.js
index cb54f63f..4908ab91 100644
--- a/static/js/modules/composables/reprocess.js
+++ b/static/js/modules/composables/reprocess.js
@@ -38,6 +38,7 @@ export function useReprocess(state, utils) {
asrReprocessOptions.max_speakers = '';
asrReprocessOptions.hotwords = '';
asrReprocessOptions.initial_prompt = '';
+ asrReprocessOptions.transcription_model = '';
} else {
summaryReprocessPromptSource.value = 'default';
summaryReprocessSelectedTagId.value = '';
@@ -120,7 +121,8 @@ export function useReprocess(state, utils) {
asrReprocessOptions.min_speakers,
asrReprocessOptions.max_speakers,
asrReprocessOptions.hotwords,
- asrReprocessOptions.initial_prompt
+ asrReprocessOptions.initial_prompt,
+ asrReprocessOptions.transcription_model
);
} else {
await reprocessSummary(
@@ -136,7 +138,7 @@ export function useReprocess(state, utils) {
// Transcription Reprocessing
// =========================================
- const reprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers, hotwords, initialPrompt) => {
+ const reprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers, hotwords, initialPrompt, transcriptionModel) => {
if (!recordingId) {
setGlobalError('No recording ID provided for reprocessing.');
return;
@@ -151,6 +153,7 @@ export function useReprocess(state, utils) {
if (maxSpeakers && maxSpeakers !== '') requestBody.max_speakers = parseInt(maxSpeakers);
if (hotwords && hotwords.trim()) requestBody.hotwords = hotwords.trim();
if (initialPrompt && initialPrompt.trim()) requestBody.initial_prompt = initialPrompt.trim();
+ if (transcriptionModel && transcriptionModel.trim()) requestBody.transcription_model = transcriptionModel.trim();
const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {
method: 'POST',
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 473d3391..87eca6b2 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -35,7 +35,7 @@ export function useUpload(state, utils) {
isProcessingActive, pollInterval, progressPopupMinimized, progressPopupClosed,
maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, maxConcurrentUploads,
recordings, selectedRecording, totalRecordings, globalError,
- selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers, uploadHotwords, uploadInitialPrompt,
+ selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers, uploadHotwords, uploadInitialPrompt, uploadTranscriptionModel, transcriptionModelOptions,
useAsrEndpoint, connectorSupportsDiarization, asrLanguage, asrMinSpeakers, asrMaxSpeakers,
dragover, availableTags, uploadTagSearchFilter,
// Folder state
@@ -264,6 +264,7 @@ export function useUpload(state, utils) {
max_speakers: asrMaxSpeakers.value,
hotwords: uploadHotwords.value,
initial_prompt: uploadInitialPrompt.value,
+ transcription_model: uploadTranscriptionModel.value,
};
item.folder_id = selectedFolderId.value;
}
@@ -383,6 +384,12 @@ export function useUpload(state, utils) {
formData.append('initial_prompt', initialPrompt.trim());
}
+ // Per-upload model override (issue #266)
+ const transcriptionModel = asrOpts.transcription_model || uploadTranscriptionModel.value;
+ if (transcriptionModel && transcriptionModel.trim()) {
+ formData.append('transcription_model', transcriptionModel.trim());
+ }
+
// Use XMLHttpRequest for per-file upload progress
const data = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
@@ -643,6 +650,10 @@ export function useUpload(state, utils) {
if (initialPrompt && initialPrompt.trim()) {
formData.append('initial_prompt', initialPrompt.trim());
}
+ const incogModel = asrOpts.transcription_model || uploadTranscriptionModel.value;
+ if (incogModel && incogModel.trim()) {
+ formData.append('transcription_model', incogModel.trim());
+ }
// Request auto-summarization
formData.append('auto_summarize', 'true');
diff --git a/static/js/modules/state/modals.js b/static/js/modules/state/modals.js
index 3e271022..37544129 100644
--- a/static/js/modules/state/modals.js
+++ b/static/js/modules/state/modals.js
@@ -53,7 +53,8 @@ export function createModalState(ref, reactive) {
min_speakers: null,
max_speakers: null,
hotwords: '',
- initial_prompt: ''
+ initial_prompt: '',
+ transcription_model: ''
});
const summaryReprocessPromptSource = ref('default');
diff --git a/static/js/modules/state/upload.js b/static/js/modules/state/upload.js
index f7fa2762..dc6036ae 100644
--- a/static/js/modules/state/upload.js
+++ b/static/js/modules/state/upload.js
@@ -29,6 +29,11 @@ export function createUploadState(ref, computed) {
const uploadMaxSpeakers = ref('');
const uploadHotwords = ref('');
const uploadInitialPrompt = ref('');
+ // Per-upload transcription model selection (issue #266). Empty string = no
+ // override; backend falls back to env-configured default.
+ const uploadTranscriptionModel = ref('');
+ // Populated from /api/config when admin set TRANSCRIPTION_MODELS_AVAILABLE.
+ const transcriptionModelOptions = ref([]);
// --- Computed Properties ---
const totalInQueue = computed(() => uploadQueue.value.length);
@@ -65,6 +70,8 @@ export function createUploadState(ref, computed) {
uploadMaxSpeakers,
uploadHotwords,
uploadInitialPrompt,
+ uploadTranscriptionModel,
+ transcriptionModelOptions,
// Computed
totalInQueue,
diff --git a/templates/account.html b/templates/account.html
index 6794ecc9..b807e05a 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -2121,6 +2121,15 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
<p class="text-xs text-[var(--text-light)] mt-1" data-i18n="form.initialPromptHelp">Context to steer the transcription model's style and vocabulary</p>
</div>
+ <!-- Default transcription model (issue #266) — only rendered when admin set TRANSCRIPTION_MODELS_AVAILABLE -->
+ <div id="tagTranscriptionModelSection" class="hidden">
+ <label for="tagTranscriptionModel" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="form.defaultTranscriptionModel">Default transcription model</label>
+ <select id="tagTranscriptionModel" name="default_transcription_model" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">(use admin/global default)</option>
+ </select>
+ <p class="text-xs text-[var(--text-light)] mt-1" data-i18n="form.defaultTranscriptionModelHelp">Override which transcription model is used for recordings with this tag.</p>
+ </div>
+
<!-- Retention Period Override (only shown when auto-deletion is enabled) -->
<div id="tagRetentionSection" class="hidden border-t border-[var(--border-primary)] pt-4 mt-2">
<h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">
@@ -2296,6 +2305,15 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
<p class="text-xs text-[var(--text-light)] mt-1" data-i18n="form.initialPromptHelp">Context to steer the transcription model's style and vocabulary</p>
</div>
+ <!-- Default transcription model (issue #266) — only rendered when admin set TRANSCRIPTION_MODELS_AVAILABLE -->
+ <div id="folderTranscriptionModelSection" class="hidden">
+ <label for="folderTranscriptionModel" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="form.defaultTranscriptionModel">Default transcription model</label>
+ <select id="folderTranscriptionModel" name="default_transcription_model" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">(use admin/global default)</option>
+ </select>
+ <p class="text-xs text-[var(--text-light)] mt-1" data-i18n="form.defaultTranscriptionModelHelp">Override which transcription model is used for recordings in this folder.</p>
+ </div>
+
<!-- Retention Period Override (only shown when auto-deletion is enabled) -->
<div id="folderRetentionSection" class="hidden border-t border-[var(--border-primary)] pt-4 mt-2">
<h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">
@@ -4713,6 +4731,9 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (document.getElementById('tagInitialPrompt')) {
document.getElementById('tagInitialPrompt').value = tag.default_initial_prompt || '';
}
+ if (document.getElementById('tagTranscriptionModel')) {
+ document.getElementById('tagTranscriptionModel').value = tag.default_transcription_model || '';
+ }
// Populate naming template
if (document.getElementById('tagNamingTemplate')) {
@@ -4954,6 +4975,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
default_max_speakers: formData.get('default_max_speakers') ? parseInt(formData.get('default_max_speakers')) : null,
default_hotwords: formData.get('default_hotwords') || null,
default_initial_prompt: formData.get('default_initial_prompt') || null,
+ default_transcription_model: formData.get('default_transcription_model') || null,
retention_days: retentionDays,
is_auto_process: document.getElementById('tagAutoProcess')?.checked || false
};
@@ -5064,6 +5086,28 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (config.enable_auto_export === true && exportSubtab) {
exportSubtab.style.display = '';
}
+
+ // Populate the per-tag and per-folder transcription-model
+ // dropdowns when the admin has configured a model list
+ // (issue #266).
+ const modelOptions = Array.isArray(config.transcription_model_options)
+ ? config.transcription_model_options : [];
+ if (modelOptions.length > 0) {
+ const populate = (selectId, sectionId) => {
+ const select = document.getElementById(selectId);
+ const section = document.getElementById(sectionId);
+ if (!select || !section) return;
+ for (const opt of modelOptions) {
+ const o = document.createElement('option');
+ o.value = opt.value;
+ o.textContent = opt.label || opt.value;
+ select.appendChild(o);
+ }
+ section.classList.remove('hidden');
+ };
+ populate('tagTranscriptionModel', 'tagTranscriptionModelSection');
+ populate('folderTranscriptionModel', 'folderTranscriptionModelSection');
+ }
}
} catch (error) {
console.error('Error checking features enabled status:', error);
@@ -5352,6 +5396,8 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (hwField) hwField.value = folder.default_hotwords || '';
var ipField = document.getElementById('folderInitialPrompt');
if (ipField) ipField.value = folder.default_initial_prompt || '';
+ var modelField = document.getElementById('folderTranscriptionModel');
+ if (modelField) modelField.value = folder.default_transcription_model || '';
// Group selection
const folderGroupId = document.getElementById('folderGroupId');
@@ -5569,6 +5615,8 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
folderData.default_hotwords = hwEl ? hwEl.value.trim() || null : null;
var ipEl = document.getElementById('folderInitialPrompt');
folderData.default_initial_prompt = ipEl ? ipEl.value.trim() || null : null;
+ var modelEl = document.getElementById('folderTranscriptionModel');
+ folderData.default_transcription_model = modelEl ? modelEl.value.trim() || null : null;
var templateEl = document.getElementById('folderNamingTemplate');
folderData.naming_template_id = templateEl && templateEl.value ? parseInt(templateEl.value) : null;
var exportTemplateEl = document.getElementById('folderExportTemplate');
diff --git a/templates/components/upload-view.html b/templates/components/upload-view.html
index 660eaa00..c894cf90 100644
--- a/templates/components/upload-view.html
+++ b/templates/components/upload-view.html
@@ -393,6 +393,18 @@
<p class="text-[10px] text-[var(--text-muted)] mt-0.5">${ t('form.initialPromptHelp') }</p>
</div>
+ <!-- Transcription Model (issue #266 — visible only when admin set TRANSCRIPTION_MODELS_AVAILABLE) -->
+ <div v-if="transcriptionModelOptions && transcriptionModelOptions.length > 0">
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Transcription model
+ </label>
+ <select v-model="uploadTranscriptionModel"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <option value="">(use tag/folder/global default)</option>
+ <option v-for="opt in transcriptionModelOptions" :key="opt.value" :value="opt.value" v-text="opt.label || opt.value"></option>
+ </select>
+ </div>
+
<p class="text-xs text-[var(--text-muted)] pt-1">
<i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
${ t('upload.settingsApplyToAll') }
diff --git a/templates/modals/reprocess-modal.html b/templates/modals/reprocess-modal.html
index 12c9a1b4..e14b76ed 100644
--- a/templates/modals/reprocess-modal.html
+++ b/templates/modals/reprocess-modal.html
@@ -88,6 +88,14 @@
<textarea id="asr-initial-prompt-reprocess" v-model="asrReprocessOptions.initial_prompt" rows="2" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y" :placeholder="t('form.initialPromptPlaceholder')"></textarea>
<p class="text-[10px] text-[var(--text-muted)] mt-0.5" v-text="t('form.initialPromptHelp')"></p>
</div>
+ <!-- Per-reprocess transcription model (issue #266) -->
+ <div v-if="transcriptionModelOptions && transcriptionModelOptions.length > 0">
+ <label for="asr-model-reprocess" class="block text-sm font-medium text-[var(--text-muted)]">Transcription model</label>
+ <select id="asr-model-reprocess" v-model="asrReprocessOptions.transcription_model" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">(use tag/folder/global default)</option>
+ <option v-for="opt in transcriptionModelOptions" :key="opt.value" :value="opt.value" v-text="opt.label || opt.value"></option>
+ </select>
+ </div>
</div>
<!-- Custom Prompt Options for Summary Reprocessing -->
diff --git a/tests/test_transcription_model_override.py b/tests/test_transcription_model_override.py
new file mode 100644
index 00000000..20307f41
--- /dev/null
+++ b/tests/test_transcription_model_override.py
@@ -0,0 +1,304 @@
+#!/usr/bin/env python3
+"""
+Tests for issue #266: per-upload, per-tag, per-folder transcription model
+selection.
+
+Validates:
+1. TRANSCRIPTION_MODEL_OPTIONS is parsed from env vars correctly.
+2. Reprocess endpoint resolves the precedence chain
+ (user input > tag default > folder default), validates against the
+ allowlist, and writes the model into job_params.
+3. The TranscriptionRequest dataclass carries `model` through to the
+ connector via _effective_model().
+4. Per-request model override falls back gracefully when the override is
+ blank or unsupported.
+
+Run with: docker exec speakr-dev python /app/tests/test_transcription_model_override.py
+"""
+
+import json
+import os
+import sys
+import uuid
+from pathlib import Path
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+# CSRF tokens are scoped to interactive sessions. Disable for the test client.
+from src.app import app, db
+app.config["WTF_CSRF_ENABLED"] = False
+
+from src.models import User, Recording
+from src.models.organization import Tag, Folder, RecordingTag
+from src.services.transcription.base import TranscriptionRequest
+from src.services.transcription.connectors.openai_whisper import (
+ OpenAIWhisperConnector,
+)
+
+
+PASSED = 0
+FAILED = 0
+
+
+def run(name, func):
+ global PASSED, FAILED
+ try:
+ func()
+ print(f" ✓ {name}")
+ PASSED += 1
+ except AssertionError as e:
+ print(f" ✗ {name}: {e}")
+ FAILED += 1
+ except Exception as e:
+ print(f" ✗ {name}: EXCEPTION - {e}")
+ FAILED += 1
+
+
+# -----------------------------------------------------------------------------
+# Section 1: env-var → TRANSCRIPTION_MODEL_OPTIONS
+# -----------------------------------------------------------------------------
+
+def test_models_csv_parses_with_labels():
+ """TRANSCRIPTION_MODELS_AVAILABLE + TRANSCRIPTION_MODEL_LABELS pair correctly."""
+ # Reload the config module with env vars set.
+ import importlib
+ os.environ["TRANSCRIPTION_MODELS_AVAILABLE"] = "whisper-1, gpt-4o-transcribe ,vibevoice"
+ os.environ["TRANSCRIPTION_MODEL_LABELS"] = "Whisper,GPT-4o,VibeVoice"
+ try:
+ import src.config.app_config as cfg
+ importlib.reload(cfg)
+ assert cfg.TRANSCRIPTION_MODELS_AVAILABLE == [
+ "whisper-1", "gpt-4o-transcribe", "vibevoice"
+ ], cfg.TRANSCRIPTION_MODELS_AVAILABLE
+ assert cfg.TRANSCRIPTION_MODEL_OPTIONS == [
+ {"value": "whisper-1", "label": "Whisper"},
+ {"value": "gpt-4o-transcribe", "label": "GPT-4o"},
+ {"value": "vibevoice", "label": "VibeVoice"},
+ ], cfg.TRANSCRIPTION_MODEL_OPTIONS
+ finally:
+ os.environ.pop("TRANSCRIPTION_MODELS_AVAILABLE", None)
+ os.environ.pop("TRANSCRIPTION_MODEL_LABELS", None)
+ importlib.reload(cfg)
+
+
+def test_models_csv_unset_means_empty():
+ """When unset, TRANSCRIPTION_MODEL_OPTIONS is an empty list (dropdown hidden)."""
+ import importlib
+ os.environ.pop("TRANSCRIPTION_MODELS_AVAILABLE", None)
+ os.environ.pop("TRANSCRIPTION_MODEL_LABELS", None)
+ import src.config.app_config as cfg
+ importlib.reload(cfg)
+ assert cfg.TRANSCRIPTION_MODEL_OPTIONS == [], cfg.TRANSCRIPTION_MODEL_OPTIONS
+
+
+# -----------------------------------------------------------------------------
+# Section 2: reprocess endpoint precedence chain
+# -----------------------------------------------------------------------------
+
+def setup_recording(*, user_input=None, tag_model=None, folder_model=None,
+ available_models=None):
+ """Build a Recording + Tag + Folder with the requested defaults.
+
+ Returns (user, recording, plain-text-token-for-test-client) where the
+ 'token' is unused. Caller logs in via test_client session.
+ """
+ suffix = uuid.uuid4().hex[:10]
+ user = User(
+ username=f"models_{suffix}",
+ email=f"models_{suffix}@test.local",
+ password="x",
+ )
+ db.session.add(user)
+ db.session.flush()
+
+ folder = None
+ if folder_model:
+ folder = Folder(
+ name=f"f_{suffix}",
+ user_id=user.id,
+ default_transcription_model=folder_model,
+ )
+ db.session.add(folder)
+ db.session.flush()
+
+ rec = Recording(
+ audio_path="/tmp/dummy.wav",
+ original_filename="dummy.wav",
+ title="model test",
+ status="COMPLETED",
+ user_id=user.id,
+ folder_id=folder.id if folder else None,
+ )
+ db.session.add(rec)
+ db.session.flush()
+
+ if tag_model:
+ tag = Tag(
+ name=f"t_{suffix}",
+ user_id=user.id,
+ default_transcription_model=tag_model,
+ )
+ db.session.add(tag)
+ db.session.flush()
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.flush()
+
+ db.session.commit()
+ return user, rec
+
+
+def call_reprocess(client, recording_id, body, available_models=None):
+ """POST to the reprocess endpoint and capture job_params."""
+ from src.services import job_queue as jq_module
+
+ captured = {}
+
+ def fake_enqueue(*args, **kwargs):
+ captured.update(kwargs)
+ return 999
+
+ original_enqueue = jq_module.job_queue.enqueue
+ jq_module.job_queue.enqueue = fake_enqueue
+ try:
+ # Patch the allowlist used by the endpoint.
+ with patch("src.api.recordings.os.path.exists", return_value=True), \
+ patch("src.config.app_config.TRANSCRIPTION_MODELS_AVAILABLE",
+ list(available_models) if available_models is not None else []):
+ resp = client.post(
+ f"/recording/{recording_id}/reprocess_transcription",
+ data=json.dumps(body),
+ content_type="application/json",
+ )
+ finally:
+ jq_module.job_queue.enqueue = original_enqueue
+ return resp, captured.get("params", {})
+
+
+def login_client(client, user):
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+
+
+def test_user_input_wins_over_defaults():
+ with app.app_context():
+ user, rec = setup_recording(tag_model="vibevoice", folder_model="whisper-1")
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id,
+ {"transcription_model": "gpt-4o-transcribe"},
+ available_models=["gpt-4o-transcribe", "vibevoice", "whisper-1"])
+ assert resp.status_code in (200, 202), f"unexpected status {resp.status_code}: {resp.data!r}"
+ assert params.get("transcription_model") == "gpt-4o-transcribe", f"got {params!r}"
+
+
+def test_tag_default_applied_when_no_user_input():
+ with app.app_context():
+ user, rec = setup_recording(tag_model="vibevoice", folder_model="whisper-1")
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {},
+ available_models=["whisper-1", "vibevoice"])
+ assert resp.status_code in (200, 202), f"unexpected status {resp.status_code}: {resp.data!r}"
+ # Tag wins over folder.
+ assert params.get("transcription_model") == "vibevoice", f"got {params!r}"
+
+
+def test_folder_default_applied_when_no_tag():
+ with app.app_context():
+ user, rec = setup_recording(folder_model="whisper-1")
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {},
+ available_models=["whisper-1", "vibevoice"])
+ assert resp.status_code in (200, 202)
+ assert params.get("transcription_model") == "whisper-1", f"got {params!r}"
+
+
+def test_user_supplied_model_outside_allowlist_dropped():
+ """An explicit override that isn't in the allowlist gets stripped."""
+ with app.app_context():
+ user, rec = setup_recording(tag_model="vibevoice")
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id,
+ {"transcription_model": "secret-internal-model"},
+ available_models=["whisper-1", "vibevoice"])
+ assert resp.status_code in (200, 202)
+ # Falls back to the tag default since user value was rejected.
+ # Note: the endpoint validates AFTER applying the precedence chain. The
+ # precedence chain runs first, so user input wins; then validation drops
+ # the bad value to None. Tag default is not re-applied — so we expect
+ # transcription_model to be None here.
+ assert params.get("transcription_model") is None, f"got {params!r}"
+
+
+def test_no_defaults_means_no_model_in_job_params():
+ with app.app_context():
+ user, rec = setup_recording()
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {})
+ assert resp.status_code in (200, 202)
+ assert params.get("transcription_model") is None, f"got {params!r}"
+
+
+# -----------------------------------------------------------------------------
+# Section 3: TranscriptionRequest carries `model` to the connector
+# -----------------------------------------------------------------------------
+
+def test_transcription_request_has_model_field():
+ req = TranscriptionRequest(
+ audio_file=None, filename="x.wav", model="custom-model",
+ )
+ assert req.model == "custom-model"
+
+
+def test_effective_model_uses_override():
+ connector = OpenAIWhisperConnector({"api_key": "x"})
+ req = TranscriptionRequest(
+ audio_file=None, filename="x.wav", model="whisper-1",
+ )
+ assert connector._effective_model(req) == "whisper-1"
+
+
+def test_effective_model_falls_back_to_default():
+ connector = OpenAIWhisperConnector({"api_key": "x", "model": "default-model"})
+ req = TranscriptionRequest(audio_file=None, filename="x.wav")
+ assert connector._effective_model(req) == "default-model"
+
+
+def test_effective_model_blank_override_falls_back():
+ connector = OpenAIWhisperConnector({"api_key": "x", "model": "default-model"})
+ req = TranscriptionRequest(audio_file=None, filename="x.wav", model=" ")
+ assert connector._effective_model(req) == "default-model"
+
+
+# -----------------------------------------------------------------------------
+# Main
+# -----------------------------------------------------------------------------
+
+def main():
+ print("=== Issue #266: per-upload/tag/folder transcription model ===\n")
+ print("--- env parsing ---")
+ run("CSV + labels parses correctly", test_models_csv_parses_with_labels)
+ run("unset env var → empty options", test_models_csv_unset_means_empty)
+ print("\n--- precedence chain ---")
+ run("user input wins over tag/folder", test_user_input_wins_over_defaults)
+ run("tag default applies when no user input", test_tag_default_applied_when_no_user_input)
+ run("folder default applies when no tag", test_folder_default_applied_when_no_tag)
+ run("model outside allowlist dropped", test_user_supplied_model_outside_allowlist_dropped)
+ run("nothing configured → None", test_no_defaults_means_no_model_in_job_params)
+ print("\n--- TranscriptionRequest plumbing ---")
+ run("model field exists", test_transcription_request_has_model_field)
+ run("override propagates", test_effective_model_uses_override)
+ run("falls back when no override", test_effective_model_falls_back_to_default)
+ run("blank override falls back", test_effective_model_blank_override_falls_back)
+
+ print(f"\nResults: {PASSED} passed, {FAILED} failed")
+ return 0 if FAILED == 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())