Skip to content

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

Python

Unify transcription param resolution behind one shared resolver so merge, reprocess, share, auto-process, and stitch all honor tag/folder/env/account defaults identically to uploads

Murtaza Nasir75823eef53b3
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 2a80d1c5..17227360 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2277,27 +2277,27 @@ def start_transcription(recording_id):
data = request.get_json() or {}
- # Apply the same per-request model override path as the upload/reprocess
- # web endpoints (issue #266). Validates against the admin-curated list +
- # env allowlist and applies the admin-saved default when nothing was sent.
- from src.api.recordings import _resolve_transcription_model
- transcription_model = _resolve_transcription_model(data.get('transcription_model'))
-
- params = {
- 'language': data.get('language'),
+ # Resolve the full transcribe param set through the shared chain so the API
+ # applies the same tag/folder/env/account defaults + admin model validation
+ # as the web upload/reprocess endpoints (issue #266).
+ from src.services.transcription_defaults import resolve_transcription_params
+ overrides = {
'min_speakers': data.get('min_speakers'),
'max_speakers': data.get('max_speakers'),
'hotwords': data.get('hotwords'),
'initial_prompt': data.get('initial_prompt'),
- 'transcription_model': transcription_model,
+ 'transcription_model': data.get('transcription_model'),
}
+ if 'language' in data:
+ overrides['language'] = data.get('language')
+ params = resolve_transcription_params(recording, overrides)
# Queue the job
job_id = job_queue.enqueue(
user_id=current_user.id,
recording_id=recording_id,
job_type='reprocess_transcription',
- params={k: v for k, v in params.items() if v is not None}
+ params=params
)
return jsonify({
@@ -2768,11 +2768,12 @@ def batch_transcribe_recordings():
continue
try:
+ from src.services.transcription_defaults import resolve_transcription_params
job_id = job_queue.enqueue(
user_id=current_user.id,
recording_id=recording_id,
job_type='reprocess_transcription',
- params={}
+ params=resolve_transcription_params(recording)
)
results.append({'id': recording_id, 'success': True, 'job_id': job_id})
except Exception as e:
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 87ae7288..e297ba1f 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -26,52 +26,14 @@ from src.utils import *
from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS, ASR_DIARIZE, USE_NEW_TRANSCRIPTION_ARCHITECTURE
-def _resolve_transcription_model(value):
- """Apply admin-curated allowlist + default to a candidate model name.
-
- Resolution:
- 1. If the caller passed a non-empty value:
- a. If the admin saved a visible-models list in system_setting and the
- value is in it, accept.
- b. Else if TRANSCRIPTION_MODELS_AVAILABLE is set and the value is in
- it, accept.
- c. Else if neither list is configured, accept (no allowlist enforced).
- d. Otherwise, drop the value with a warning.
- 2. If the caller passed nothing, fall back to the admin-saved default
- model (system_setting key `transcription_default_model`) when set.
- Returns the validated model id or None.
- """
- from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
- import json as _json
-
- candidate = (value or '').strip() or None
- visible = []
- try:
- raw = SystemSetting.get_setting('transcription_models_visible_json', None)
- if raw:
- parsed = _json.loads(raw)
- if isinstance(parsed, list):
- visible = [
- (item['value'] if isinstance(item, dict) else item)
- for item in parsed if item
- ]
- except Exception:
- visible = []
-
- if candidate:
- in_db_list = bool(visible) and candidate in visible
- in_env_list = bool(TRANSCRIPTION_MODELS_AVAILABLE) and candidate in TRANSCRIPTION_MODELS_AVAILABLE
- if visible or TRANSCRIPTION_MODELS_AVAILABLE:
- if not (in_db_list or in_env_list):
- current_app.logger.warning(
- f"Ignoring transcription_model={candidate!r} — not in admin-curated list or TRANSCRIPTION_MODELS_AVAILABLE"
- )
- candidate = None
- return candidate
-
- # Fall back to admin-saved default when no override flowed through.
- default = SystemSetting.get_setting('transcription_default_model', None)
- return default or None
+# Model validation + the full default-resolution chain now live in one shared
+# module so every ingestion path (upload, reprocess, merge, stitch, share,
+# auto-process) resolves transcription params identically. Kept as an alias so
+# existing references in this file keep working.
+from src.services.transcription_defaults import (
+ resolve_transcription_model as _resolve_transcription_model,
+ resolve_transcription_params,
+)
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
@@ -1269,105 +1231,21 @@ def reprocess_transcription(recording_id):
start_time = datetime.utcnow()
app_context = current_app._get_current_object().app_context()
- # Build job parameters - language handling:
- # - If 'language' key exists with a value (e.g., 'es'), use that language
- # - If 'language' key exists but is empty string, keep as empty string (signals auto-detect)
- # - If 'language' key doesn't exist at all, fall back to user's default (backwards compat)
- if 'language' in data:
- # User explicitly chose a language (or auto-detect with empty string)
- language = data.get('language') # Could be 'es', '', or None
- else:
- # Language not provided - use user's default (backwards compatibility)
- language = recording.owner.transcription_language if recording.owner else None
-
- min_speakers = data.get('min_speakers') or None
- 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:
- try:
- min_speakers = int(min_speakers)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers:
- try:
- max_speakers = int(max_speakers)
- except (ValueError, TypeError):
- max_speakers = None
-
- # Apply precedence chain mirroring upload_file():
- # user input > tag defaults > folder defaults > env defaults > user defaults
-
- # Tag defaults (highest priority after user input). Use the first tag's
- # defaults when present.
- if recording.tags:
- for tag_association in sorted(recording.tag_associations, key=lambda x: x.order):
- tag = tag_association.tag
- if min_speakers is None and tag.default_min_speakers:
- min_speakers = tag.default_min_speakers
- if max_speakers is None and tag.default_max_speakers:
- max_speakers = tag.default_max_speakers
- if not hotwords and tag.default_hotwords:
- 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 transcription_model):
- break
-
- # Folder defaults (only if recording has no tags providing the value)
- if recording.folder:
- folder = recording.folder
- if min_speakers is None and folder.default_min_speakers:
- min_speakers = folder.default_min_speakers
- if max_speakers is None and folder.default_max_speakers:
- max_speakers = folder.default_max_speakers
- if not hotwords and folder.default_hotwords:
- 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:
- try:
- min_speakers = int(ASR_MIN_SPEAKERS)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers is None and ASR_MAX_SPEAKERS:
- try:
- max_speakers = int(ASR_MAX_SPEAKERS)
- except (ValueError, TypeError):
- max_speakers = None
-
- # User defaults (lowest priority). The recording owner's account-level
- # hotwords / initial_prompt apply when no tag/folder/env value was set.
- owner = recording.owner
- if owner:
- if not hotwords and owner.transcription_hotwords:
- hotwords = owner.transcription_hotwords
- if not initial_prompt and owner.transcription_initial_prompt:
- initial_prompt = owner.transcription_initial_prompt
-
- # Validate against admin-curated list and apply admin default when
- # nothing else in the chain set a model. See _resolve_transcription_model.
- transcription_model = _resolve_transcription_model(transcription_model)
-
- # Enqueue the job with all parameters
- job_params = {
- 'language': language,
- 'min_speakers': min_speakers,
- 'max_speakers': max_speakers,
- 'hotwords': hotwords,
- 'initial_prompt': initial_prompt,
- 'transcription_model': transcription_model,
+ # Resolve the full transcribe param set through the shared chain:
+ # per-request override > tag > folder > env > owner > admin default.
+ # The 'language' key is only forwarded when explicitly present so an
+ # empty string still means auto-detect and an absent key falls back to
+ # the owner's default (see resolve_transcription_params).
+ overrides = {
+ 'min_speakers': data.get('min_speakers'),
+ 'max_speakers': data.get('max_speakers'),
+ 'hotwords': data.get('hotwords'),
+ 'initial_prompt': data.get('initial_prompt'),
+ 'transcription_model': data.get('transcription_model'),
}
+ if 'language' in data:
+ overrides['language'] = data.get('language')
+ job_params = resolve_transcription_params(recording, overrides)
job_id = job_queue.enqueue(
user_id=current_user.id,
@@ -2443,14 +2321,11 @@ def share_target():
db.session.add(recording)
db.session.commit()
- # Enqueue transcription with user's defaults. Mirrors the precedence
- # chain in upload_file for the fields that apply when no tag/folder
- # context is available.
- job_params = {
- 'language': current_user.transcription_language,
- 'hotwords': current_user.transcription_hotwords,
- 'initial_prompt': current_user.transcription_initial_prompt,
- }
+ # Enqueue transcription through the shared resolver so a shared file honors
+ # the same account defaults (and any future tag/folder context) as every
+ # other ingestion path. A share sheet carries no tag/folder, so this
+ # resolves to the owner's account-level defaults.
+ job_params = resolve_transcription_params(recording)
try:
job_queue.enqueue(
user_id=current_user.id,
diff --git a/src/file_monitor.py b/src/file_monitor.py
index a9e881a7..9b1ec527 100644
--- a/src/file_monitor.py
+++ b/src/file_monitor.py
@@ -481,14 +481,10 @@ class FileMonitor:
)
recording.audio_path = stored_object.locator
- user_hotwords = (user.transcription_hotwords or '').strip() if getattr(user, 'transcription_hotwords', None) else None
- user_initial_prompt = (user.transcription_initial_prompt or '').strip() if getattr(user, 'transcription_initial_prompt', None) else None
- user_language = (user.transcription_language or '').strip() if getattr(user, 'transcription_language', None) else None
-
self.logger.info(f"Created recording record with ID: {recording.id} for user: {user.username}")
- # Apply tag if specified
- job_params = {}
+ # Apply tag if specified (so the recording carries it before we
+ # resolve transcribe params below).
if tag_id:
from src.models import Tag, RecordingTag
tag = db.session.get(Tag, tag_id)
@@ -502,30 +498,15 @@ class FileMonitor:
db.session.commit()
self.logger.info(f"Applied tag '{tag.name}' (id={tag_id}) to recording {recording.id}")
- # Pass tag settings to job params
- if tag.default_hotwords:
- job_params['hotwords'] = tag.default_hotwords
- if tag.default_initial_prompt:
- job_params['initial_prompt'] = tag.default_initial_prompt
- if tag.default_language:
- job_params['language'] = tag.default_language
- if tag.default_min_speakers:
- job_params['min_speakers'] = tag.default_min_speakers
- if tag.default_max_speakers:
- job_params['max_speakers'] = tag.default_max_speakers
- if tag.custom_prompt:
- job_params['custom_prompt'] = tag.custom_prompt
- job_params['tag_id'] = tag_id
-
- if 'language' not in job_params and user_language:
- job_params['language'] = user_language
- if 'hotwords' not in job_params and user_hotwords:
- job_params['hotwords'] = user_hotwords
- if 'initial_prompt' not in job_params and user_initial_prompt:
- job_params['initial_prompt'] = user_initial_prompt
-
db.session.commit()
+ # Resolve transcribe params through the shared chain so an
+ # auto-processed file honors the same tag/folder/env/account
+ # defaults (speaker hints, model, hotwords, prompt) as a normal
+ # upload — previously this path only forwarded a thin subset.
+ from src.services.transcription_defaults import resolve_transcription_params
+ job_params = resolve_transcription_params(recording)
+
# Queue for background processing
from src.services.job_queue import job_queue
job_queue.enqueue(
diff --git a/src/services/recording_merge.py b/src/services/recording_merge.py
index dd184d65..c72f8cfb 100644
--- a/src/services/recording_merge.py
+++ b/src/services/recording_merge.py
@@ -288,16 +288,12 @@ def run_merge_job(recording, params):
current_app.logger.warning(f"Failed to delete source recording {rec.id} after merge: {e}")
db.session.commit()
- # Queue transcription using the user's defaults.
- from src.models import User
- owner = db.session.get(User, recording.user_id)
- first_tag = recording.tags[0] if recording.tags else None
- job_params = {
- 'language': owner.transcription_language if owner else None,
- 'hotwords': owner.transcription_hotwords if owner else None,
- 'initial_prompt': owner.transcription_initial_prompt if owner else None,
- 'tag_id': first_tag.id if first_tag else None,
- }
+ # Queue transcription with the SAME resolved params a normal upload gets, so
+ # the merged file honors all of the owner's tag/folder/account preferences
+ # (speaker-count hints, hotwords, initial prompt, transcription model) and
+ # therefore diarization + auto speaker labelling behave identically (#323).
+ from src.services.transcription_defaults import resolve_transcription_params
+ job_params = resolve_transcription_params(recording)
job_queue.enqueue(
user_id=recording.user_id,
recording_id=recording.id,
diff --git a/src/services/recording_stitch.py b/src/services/recording_stitch.py
index 59c7d4e3..0badd568 100644
--- a/src/services/recording_stitch.py
+++ b/src/services/recording_stitch.py
@@ -421,23 +421,36 @@ def kickoff_transcription_for_stitched(
user_id: int,
metadata: dict,
) -> None:
- """Enqueue the downstream transcribe job using the same precedence
- chain as ``upload_file`` for the fields that apply to a recording
- that already exists. Idempotent (the job_queue rejects duplicate
- active jobs of the same type for the same recording)."""
+ """Enqueue the downstream transcribe job through the shared param resolver
+ so a stitched recording-session file honors the owner's tag/folder/account
+ defaults just like a normal upload. The session's own selections (captured in
+ ``metadata``) act as the per-request overrides. Idempotent (the job_queue
+ rejects duplicate active jobs of the same type for the same recording)."""
from src.services.job_queue import job_queue
+ from src.services.transcription_defaults import resolve_transcription_params
+ from src.database import db
+ from src.models import Recording
+
+ recording = db.session.get(Recording, recording_id)
+
+ overrides = {
+ 'min_speakers': metadata.get('min_speakers'),
+ 'max_speakers': metadata.get('max_speakers'),
+ 'hotwords': metadata.get('hotwords'),
+ 'initial_prompt': metadata.get('initial_prompt'),
+ 'transcription_model': metadata.get('transcription_model'),
+ }
+ session_language = metadata.get('language') or metadata.get('asr_language')
+ if session_language:
+ overrides['language'] = session_language
+ if metadata.get('tag_id') is not None:
+ overrides['tag_id'] = metadata.get('tag_id')
+
+ job_params = resolve_transcription_params(recording, overrides)
job_queue.enqueue(
user_id=user_id,
recording_id=recording_id,
job_type='transcribe',
- params={
- 'language': metadata.get('language') or metadata.get('asr_language'),
- 'min_speakers': metadata.get('min_speakers'),
- 'max_speakers': metadata.get('max_speakers'),
- 'tag_id': metadata.get('tag_id'),
- 'hotwords': metadata.get('hotwords'),
- 'initial_prompt': metadata.get('initial_prompt'),
- 'transcription_model': metadata.get('transcription_model'),
- },
+ params=job_params,
is_new_upload=True,
)
diff --git a/src/services/transcription_defaults.py b/src/services/transcription_defaults.py
new file mode 100644
index 00000000..b7f56ecb
--- /dev/null
+++ b/src/services/transcription_defaults.py
@@ -0,0 +1,202 @@
+"""Single source of truth for the transcription job parameters that every
+ingestion path enqueues.
+
+Historically each path (upload, reprocess, merge, recording-session stitch,
+share-target, auto-process) built its own ``job_params`` dict. Several only
+passed a thin subset (e.g. account-level defaults), so recordings created by
+those paths silently skipped tag/folder defaults, speaker-count hints, and the
+admin-curated transcription model. That in turn changed downstream behavior such
+as diarization and automatic speaker labelling.
+
+This module centralizes the precedence chain so all paths resolve settings
+identically. Precedence, highest first:
+
+ explicit per-request override
+ > first tag's defaults
+ > folder defaults
+ > environment defaults (ASR_MIN_SPEAKERS / ASR_MAX_SPEAKERS)
+ > owner (account) defaults
+ > admin-curated model default
+
+Every caller passes the ``recording`` (which carries tags/folder/owner) plus an
+optional ``overrides`` dict of already-parsed per-request values, and gets back
+the complete params dict used by the transcribe job.
+"""
+
+import json as _json
+
+from flask import current_app
+
+# Sentinel so callers can pass tag_id=None explicitly (meaning "no tag prompt")
+# and have it respected, versus omitting the key to get the first-tag default.
+_UNSET = object()
+
+
+def _int_or_none(value):
+ if value is None or value == '':
+ return None
+ try:
+ return int(value)
+ except (ValueError, TypeError):
+ return None
+
+
+def resolve_transcription_model(value):
+ """Validate a candidate transcription model against the admin-curated
+ allowlist and fall back to the admin-saved default.
+
+ Resolution:
+ 1. If a non-empty value is passed and an allowlist exists (admin-saved
+ visible list or TRANSCRIPTION_MODELS_AVAILABLE), the value is accepted
+ only when it is in that list; otherwise it is dropped with a warning.
+ With no allowlist configured, any value is accepted.
+ 2. If nothing was passed, fall back to the admin-saved default model
+ (system_setting key ``transcription_default_model``) when set.
+ Returns the validated model id or None.
+ """
+ from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
+ from src.models import SystemSetting
+
+ candidate = (value or '').strip() or None
+ visible = []
+ try:
+ raw = SystemSetting.get_setting('transcription_models_visible_json', None)
+ if raw:
+ parsed = _json.loads(raw)
+ if isinstance(parsed, list):
+ visible = [
+ (item['value'] if isinstance(item, dict) else item)
+ for item in parsed if item
+ ]
+ except Exception:
+ visible = []
+
+ if candidate:
+ in_db_list = bool(visible) and candidate in visible
+ in_env_list = bool(TRANSCRIPTION_MODELS_AVAILABLE) and candidate in TRANSCRIPTION_MODELS_AVAILABLE
+ if visible or TRANSCRIPTION_MODELS_AVAILABLE:
+ if not (in_db_list or in_env_list):
+ current_app.logger.warning(
+ f"Ignoring transcription_model={candidate!r} — not in admin-curated list or TRANSCRIPTION_MODELS_AVAILABLE"
+ )
+ candidate = None
+ return candidate
+
+ default = SystemSetting.get_setting('transcription_default_model', None)
+ return default or None
+
+
+def resolve_transcription_params(recording, overrides=None):
+ """Resolve the complete transcribe job params for a recording.
+
+ Args:
+ recording: the Recording (provides .tags / .tag_associations / .folder /
+ .owner for the default chain).
+ overrides: optional dict of already-parsed per-request values. Recognized
+ keys: ``language``, ``min_speakers``, ``max_speakers``, ``hotwords``,
+ ``initial_prompt``, ``transcription_model``, ``tag_id``. Any key that
+ is absent or None/empty is filled from the recording's tag -> folder
+ -> env -> owner defaults.
+
+ ``language`` is special: if the key is PRESENT (even as '' meaning
+ auto-detect) it is used verbatim; if ABSENT, the owner's default
+ language is used. ``tag_id`` is special: if the key is PRESENT (even
+ as None) it is respected; if ABSENT, the first tag's id is used.
+
+ Returns:
+ dict with keys language, min_speakers, max_speakers, tag_id, hotwords,
+ initial_prompt, transcription_model — identical in shape across every
+ ingestion path.
+ """
+ from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS
+
+ overrides = overrides or {}
+
+ def _override_str(key):
+ v = overrides.get(key)
+ if isinstance(v, str):
+ v = v.strip() or None
+ return v
+
+ min_speakers = _int_or_none(overrides.get('min_speakers'))
+ max_speakers = _int_or_none(overrides.get('max_speakers'))
+ hotwords = _override_str('hotwords')
+ initial_prompt = _override_str('initial_prompt')
+ transcription_model = _override_str('transcription_model')
+
+ owner = recording.owner
+
+ # language: an explicit override key (including '' for auto-detect) wins and
+ # skips the default chain entirely. Otherwise language resolves through the
+ # same tag -> folder -> owner chain as every other field.
+ language_explicit = 'language' in overrides
+ language = overrides.get('language') if language_explicit else None
+
+ # Tag defaults — first tag (by association order) that supplies each value.
+ first_tag = None
+ if recording.tags:
+ for assoc in sorted(recording.tag_associations, key=lambda x: x.order):
+ tag = assoc.tag
+ if first_tag is None:
+ first_tag = tag
+ if not language_explicit and not language and tag.default_language:
+ language = tag.default_language
+ if min_speakers is None and tag.default_min_speakers:
+ min_speakers = tag.default_min_speakers
+ if max_speakers is None and tag.default_max_speakers:
+ max_speakers = tag.default_max_speakers
+ if not hotwords and tag.default_hotwords:
+ 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
+
+ # Folder defaults.
+ folder = recording.folder
+ if folder:
+ if not language_explicit and not language and folder.default_language:
+ language = folder.default_language
+ if min_speakers is None and folder.default_min_speakers:
+ min_speakers = folder.default_min_speakers
+ if max_speakers is None and folder.default_max_speakers:
+ max_speakers = folder.default_max_speakers
+ if not hotwords and folder.default_hotwords:
+ 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 defaults.
+ if min_speakers is None and ASR_MIN_SPEAKERS:
+ min_speakers = _int_or_none(ASR_MIN_SPEAKERS)
+ if max_speakers is None and ASR_MAX_SPEAKERS:
+ max_speakers = _int_or_none(ASR_MAX_SPEAKERS)
+
+ # Owner (account-level) defaults.
+ if owner:
+ if not language_explicit and not language and owner.transcription_language:
+ language = owner.transcription_language
+ if not hotwords and owner.transcription_hotwords:
+ hotwords = owner.transcription_hotwords
+ if not initial_prompt and owner.transcription_initial_prompt:
+ initial_prompt = owner.transcription_initial_prompt
+
+ # Admin-curated validation / default for the model.
+ transcription_model = resolve_transcription_model(transcription_model)
+
+ # tag_id: explicit override respected (including None), else first tag.
+ tag_id = overrides.get('tag_id', _UNSET)
+ if tag_id is _UNSET:
+ tag_id = first_tag.id if first_tag else None
+
+ return {
+ 'language': language,
+ 'min_speakers': min_speakers,
+ 'max_speakers': max_speakers,
+ 'tag_id': tag_id,
+ 'hotwords': hotwords,
+ 'initial_prompt': initial_prompt,
+ 'transcription_model': transcription_model,
+ }
diff --git a/tests/test_cov_file_monitor.py b/tests/test_cov_file_monitor.py
index 044f79f1..9e261279 100644
--- a/tests/test_cov_file_monitor.py
+++ b/tests/test_cov_file_monitor.py
@@ -596,14 +596,19 @@ class TestProcessFile(unittest.TestCase):
assoc = RecordingTag.query.filter_by(recording_id=rec.id, tag_id=tag.id).first()
self.assertIsNotNone(assoc)
+ # Auto-process now resolves transcribe params through the shared
+ # resolver (resolve_transcription_params), the same chain uploads use.
params = enqueued[0]['params']
self.assertEqual(params['hotwords'], 'Foo, Bar')
self.assertEqual(params['initial_prompt'], 'a prompt')
self.assertEqual(params['language'], 'es')
self.assertEqual(params['min_speakers'], 2)
self.assertEqual(params['max_speakers'], 4)
- self.assertEqual(params['custom_prompt'], 'summarize this')
self.assertEqual(params['tag_id'], tag.id)
+ # custom_prompt is a SUMMARY concern: the auto-summary resolves
+ # tag.custom_prompt from the recording's applied tag directly, so it is
+ # deliberately not forwarded in the (transcribe) job params.
+ self.assertNotIn('custom_prompt', params)
def test_process_file_logs_conversion_and_compression(self):
# convert_if_needed reporting was_converted/was_compressed exercises the
diff --git a/tests/test_transcription_defaults.py b/tests/test_transcription_defaults.py
new file mode 100644
index 00000000..55466c2d
--- /dev/null
+++ b/tests/test_transcription_defaults.py
@@ -0,0 +1,128 @@
+"""Tests for the shared transcription-param resolver.
+
+resolve_transcription_params is the single source of truth every ingestion path
+(upload, reprocess, merge, stitch, share, auto-process) uses to turn a recording
++ optional per-request overrides into the transcribe job params. These tests pin
+the precedence chain: override > tag > folder > env > owner > admin default.
+"""
+
+import os
+import sys
+import uuid
+
+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
+from src.services.transcription_defaults import resolve_transcription_params
+
+
+def _mk_user(**kw):
+ u = User(username=f"td_{uuid.uuid4().hex[:8]}", email=f"td_{uuid.uuid4().hex[:8]}@local.test", password="x", **kw)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _mk_recording(user, **kw):
+ rec = Recording(user_id=user.id, title="r", status="COMPLETED",
+ audio_path="local://x.mp3", original_filename="x.mp3", **kw)
+ db.session.add(rec)
+ db.session.commit()
+ return rec
+
+
+def test_owner_defaults_when_no_tag_or_folder():
+ with app.app_context():
+ user = _mk_user(transcription_language="fr", transcription_hotwords="alpha",
+ transcription_initial_prompt="beta")
+ rec = _mk_recording(user)
+ p = resolve_transcription_params(rec)
+ assert p["language"] == "fr"
+ assert p["hotwords"] == "alpha"
+ assert p["initial_prompt"] == "beta"
+ assert p["tag_id"] is None
+
+
+def test_tag_defaults_override_owner():
+ with app.app_context():
+ user = _mk_user(transcription_language="fr", transcription_hotwords="owner_hw")
+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id,
+ default_language="de", default_hotwords="tag_hw",
+ default_min_speakers=2, default_max_speakers=5)
+ db.session.add(tag)
+ db.session.commit()
+ rec = _mk_recording(user)
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.commit()
+ p = resolve_transcription_params(rec)
+ assert p["language"] == "de" # tag beats owner
+ assert p["hotwords"] == "tag_hw"
+ assert p["min_speakers"] == 2
+ assert p["max_speakers"] == 5
+ assert p["tag_id"] == tag.id
+
+
+def test_folder_fills_gaps_not_covered_by_tag():
+ with app.app_context():
+ user = _mk_user()
+ folder = Folder(name=f"f_{uuid.uuid4().hex[:6]}", user_id=user.id,
+ default_hotwords="folder_hw", default_min_speakers=3)
+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id, default_language="es")
+ db.session.add_all([folder, tag])
+ db.session.commit()
+ rec = _mk_recording(user, folder_id=folder.id)
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.commit()
+ p = resolve_transcription_params(rec)
+ assert p["language"] == "es" # from tag
+ assert p["hotwords"] == "folder_hw" # tag had none -> folder fills
+ assert p["min_speakers"] == 3 # folder fills
+
+
+def test_explicit_override_beats_everything():
+ with app.app_context():
+ user = _mk_user(transcription_hotwords="owner_hw")
+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id, default_hotwords="tag_hw")
+ db.session.add(tag)
+ db.session.commit()
+ rec = _mk_recording(user)
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.commit()
+ p = resolve_transcription_params(rec, {"hotwords": "override_hw", "min_speakers": "4"})
+ assert p["hotwords"] == "override_hw"
+ assert p["min_speakers"] == 4 # coerced from string
+
+
+def test_explicit_empty_language_is_autodetect_not_owner_default():
+ with app.app_context():
+ user = _mk_user(transcription_language="fr")
+ rec = _mk_recording(user)
+ # 'language' present but empty => auto-detect, must NOT fall back to 'fr'
+ p = resolve_transcription_params(rec, {"language": ""})
+ assert p["language"] == ""
+
+
+def test_absent_language_falls_back_to_owner_default():
+ with app.app_context():
+ user = _mk_user(transcription_language="fr")
+ rec = _mk_recording(user)
+ p = resolve_transcription_params(rec, {"hotwords": "x"}) # no language key
+ assert p["language"] == "fr"
+
+
+def test_explicit_tag_id_none_is_respected():
+ with app.app_context():
+ user = _mk_user()
+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id)
+ db.session.add(tag)
+ db.session.commit()
+ rec = _mk_recording(user)
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=1))
+ db.session.commit()
+ # caller explicitly suppresses the tag prompt
+ p = resolve_transcription_params(rec, {"tag_id": None})
+ assert p["tag_id"] is None
+ # absent -> first tag
+ p2 = resolve_transcription_params(rec)
+ assert p2["tag_id"] == tag.id