Skip to content

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

Python

Apply tag/folder/user default hotwords and initial_prompt on transcription reprocess

Murtaza Nasir12d5e28b39d1
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 609dcfb1..f61b6ed8 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -971,6 +971,8 @@ def reprocess_transcription(recording_id):
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
# Convert to int if provided
if min_speakers:
@@ -984,18 +986,39 @@ def reprocess_transcription(recording_id):
except (ValueError, TypeError):
max_speakers = None
- # Apply tag defaults if no user input provided (for connectors that support speaker count)
- if (min_speakers is None or max_speakers is None) and recording.tags:
+ # 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 min_speakers is not None and max_speakers is not None:
+ 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 (min_speakers is not None and max_speakers is not None
+ and hotwords and initial_prompt):
break
- # Apply environment variable defaults
+ # 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
+
+ # Environment variable defaults
if min_speakers is None and ASR_MIN_SPEAKERS:
try:
min_speakers = int(ASR_MIN_SPEAKERS)
@@ -1007,11 +1030,22 @@ def reprocess_transcription(recording_id):
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
+
# Enqueue the job with all parameters
job_params = {
'language': language,
'min_speakers': min_speakers,
- 'max_speakers': max_speakers
+ 'max_speakers': max_speakers,
+ 'hotwords': hotwords,
+ 'initial_prompt': initial_prompt,
}
job_id = job_queue.enqueue(
diff --git a/static/js/modules/composables/reprocess.js b/static/js/modules/composables/reprocess.js
index 1f923a63..cb54f63f 100644
--- a/static/js/modules/composables/reprocess.js
+++ b/static/js/modules/composables/reprocess.js
@@ -36,6 +36,8 @@ export function useReprocess(state, utils) {
asrReprocessOptions.language = userTranscriptionLanguage?.value || '';
asrReprocessOptions.min_speakers = '';
asrReprocessOptions.max_speakers = '';
+ asrReprocessOptions.hotwords = '';
+ asrReprocessOptions.initial_prompt = '';
} else {
summaryReprocessPromptSource.value = 'default';
summaryReprocessSelectedTagId.value = '';
@@ -116,7 +118,9 @@ export function useReprocess(state, utils) {
recordingId,
asrReprocessOptions.language,
asrReprocessOptions.min_speakers,
- asrReprocessOptions.max_speakers
+ asrReprocessOptions.max_speakers,
+ asrReprocessOptions.hotwords,
+ asrReprocessOptions.initial_prompt
);
} else {
await reprocessSummary(
@@ -132,7 +136,7 @@ export function useReprocess(state, utils) {
// Transcription Reprocessing
// =========================================
- const reprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {
+ const reprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers, hotwords, initialPrompt) => {
if (!recordingId) {
setGlobalError('No recording ID provided for reprocessing.');
return;
@@ -145,6 +149,8 @@ export function useReprocess(state, utils) {
};
if (minSpeakers && minSpeakers !== '') requestBody.min_speakers = parseInt(minSpeakers);
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();
const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {
method: 'POST',
diff --git a/static/js/modules/state/modals.js b/static/js/modules/state/modals.js
index 84e8b19f..3e271022 100644
--- a/static/js/modules/state/modals.js
+++ b/static/js/modules/state/modals.js
@@ -51,7 +51,9 @@ export function createModalState(ref, reactive) {
const asrReprocessOptions = reactive({
language: '',
min_speakers: null,
- max_speakers: null
+ max_speakers: null,
+ hotwords: '',
+ initial_prompt: ''
});
const summaryReprocessPromptSource = ref('default');
diff --git a/templates/modals/reprocess-modal.html b/templates/modals/reprocess-modal.html
index ba6b2a2d..12c9a1b4 100644
--- a/templates/modals/reprocess-modal.html
+++ b/templates/modals/reprocess-modal.html
@@ -78,6 +78,16 @@
<label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
<input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" 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)]" :placeholder="t('form.optional')">
</div>
+ <div>
+ <label for="asr-hotwords-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.hotwords')"></label>
+ <input type="text" id="asr-hotwords-reprocess" v-model="asrReprocessOptions.hotwords" 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)]" :placeholder="t('form.hotwordsPlaceholder')">
+ <p class="text-[10px] text-[var(--text-muted)] mt-0.5" v-text="t('form.hotwordsHelp')"></p>
+ </div>
+ <div>
+ <label for="asr-initial-prompt-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.initialPrompt')"></label>
+ <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>
</div>
<!-- Custom Prompt Options for Summary Reprocessing -->
diff --git a/tests/test_reprocess_hotwords.py b/tests/test_reprocess_hotwords.py
new file mode 100644
index 00000000..392f28c4
--- /dev/null
+++ b/tests/test_reprocess_hotwords.py
@@ -0,0 +1,224 @@
+#!/usr/bin/env python3
+"""
+Regression test for issue #265: Reprocess transcription does not apply
+tag/folder/user default hotwords or initial_prompt.
+
+Asserts that the reprocess endpoint, given an empty request body, walks the
+same precedence chain that upload_file() uses:
+ user input > tag defaults > folder defaults > user defaults
+
+The test patches job_queue.enqueue() to capture the params dict that would be
+sent to the worker.
+
+Run with: docker exec speakr-dev python /app/tests/test_reprocess_hotwords.py
+"""
+
+import json
+import sys
+import uuid
+from pathlib import Path
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from src.app import app, db
+from src.models import User, Recording
+from src.models.organization import Tag, Folder, RecordingTag
+
+# CSRF tokens are scoped to interactive sessions. Disable for the test client.
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+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
+
+
+def setup_recording(*, owner_hotwords=None, owner_prompt=None,
+ tag_hotwords=None, tag_prompt=None,
+ folder_hotwords=None, folder_prompt=None):
+ """Create a user, recording, optional tag, optional folder, and any default values."""
+ suffix = uuid.uuid4().hex[:10]
+ user = User(
+ username=f"reprocess_test_{suffix}",
+ email=f"reprocess_test_{suffix}@test.local",
+ password="x", # column is just a hash string; auth isn't exercised in this test
+ )
+ user.transcription_hotwords = owner_hotwords
+ user.transcription_initial_prompt = owner_prompt
+ db.session.add(user)
+ db.session.flush()
+
+ folder = None
+ if folder_hotwords or folder_prompt:
+ folder = Folder(
+ name=f"f_{user.id}",
+ user_id=user.id,
+ default_hotwords=folder_hotwords,
+ default_initial_prompt=folder_prompt,
+ )
+ db.session.add(folder)
+ db.session.flush()
+
+ rec = Recording(
+ audio_path="/tmp/dummy.wav",
+ original_filename="dummy.wav",
+ title="test",
+ status="COMPLETED",
+ user_id=user.id,
+ folder_id=folder.id if folder else None,
+ )
+ db.session.add(rec)
+ db.session.flush()
+
+ if tag_hotwords or tag_prompt:
+ tag = Tag(
+ name=f"t_{user.id}",
+ user_id=user.id,
+ default_hotwords=tag_hotwords,
+ default_initial_prompt=tag_prompt,
+ )
+ 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):
+ """POST to the reprocess endpoint and capture the job_params."""
+ from src.services import job_queue as jq_module
+
+ captured = {}
+
+ def fake_enqueue(*args, **kwargs):
+ captured.update(kwargs)
+ return 999
+
+ original = jq_module.job_queue.enqueue
+ jq_module.job_queue.enqueue = fake_enqueue
+ try:
+ with patch("src.api.recordings.os.path.exists", return_value=True):
+ resp = client.post(
+ f"/recording/{recording_id}/reprocess_transcription",
+ data=json.dumps(body),
+ content_type="application/json",
+ )
+ finally:
+ jq_module.job_queue.enqueue = original
+ return resp, captured.get("params", {})
+
+
+def login_client(client, user):
+ """Log in via the test client by writing the session cookie directly."""
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+
+
+def test_user_input_wins():
+ """Explicit hotwords/initial_prompt in the request body take priority over all defaults."""
+ with app.app_context():
+ user, rec = setup_recording(
+ owner_hotwords="user_hot", owner_prompt="user_prompt",
+ tag_hotwords="tag_hot", tag_prompt="tag_prompt",
+ )
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {
+ "hotwords": "explicit_hot",
+ "initial_prompt": "explicit_prompt",
+ })
+ assert resp.status_code in (200, 202), f"unexpected status {resp.status_code}: {resp.data!r}"
+ assert params.get("hotwords") == "explicit_hot", f"got {params!r}"
+ assert params.get("initial_prompt") == "explicit_prompt", f"got {params!r}"
+
+
+def test_tag_defaults_apply_when_no_user_input():
+ """Tag default_hotwords / default_initial_prompt apply when request body is empty."""
+ with app.app_context():
+ user, rec = setup_recording(
+ tag_hotwords="tag_hot", tag_prompt="tag_prompt",
+ folder_hotwords="folder_hot", folder_prompt="folder_prompt",
+ owner_hotwords="user_hot", owner_prompt="user_prompt",
+ )
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {})
+ assert resp.status_code in (200, 202), f"unexpected status {resp.status_code}: {resp.data!r}"
+ # Tag wins over folder and over user. # noqa
+ assert params.get("hotwords") == "tag_hot", f"got {params!r}"
+ assert params.get("initial_prompt") == "tag_prompt", f"got {params!r}"
+
+
+def test_folder_defaults_apply_when_no_tag():
+ """Folder defaults apply when there's no tag override and no user input."""
+ with app.app_context():
+ user, rec = setup_recording(
+ folder_hotwords="folder_hot", folder_prompt="folder_prompt",
+ owner_hotwords="user_hot", owner_prompt="user_prompt",
+ )
+ client = app.test_client()
+ login_client(client, user)
+ resp, params = call_reprocess(client, rec.id, {})
+ assert resp.status_code in (200, 202)
+ # Folder wins over user, no tag in play.
+ assert params.get("hotwords") == "folder_hot", f"got {params!r}"
+ assert params.get("initial_prompt") == "folder_prompt", f"got {params!r}"
+
+
+def test_user_defaults_apply_as_last_resort():
+ """User account defaults apply when nothing else is set."""
+ with app.app_context():
+ user, rec = setup_recording(
+ owner_hotwords="user_hot", owner_prompt="user_prompt",
+ )
+ 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("hotwords") == "user_hot", f"got {params!r}"
+ assert params.get("initial_prompt") == "user_prompt", f"got {params!r}"
+
+
+def test_empty_when_nothing_configured():
+ """No user input + no tag/folder/user defaults → params have None for both."""
+ 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("hotwords") is None, f"got {params!r}"
+ assert params.get("initial_prompt") is None, f"got {params!r}"
+
+
+def main():
+ print("=== Issue #265: reprocess hotwords/initial_prompt precedence ===\n")
+ run("user input wins over all defaults", test_user_input_wins)
+ run("tag defaults apply when no user input", test_tag_defaults_apply_when_no_user_input)
+ run("folder defaults apply when no tag", test_folder_defaults_apply_when_no_tag)
+ run("user account defaults apply as last resort", test_user_defaults_apply_as_last_resort)
+ run("nothing configured → both None", test_empty_when_nothing_configured)
+
+ print(f"\nResults: {PASSED} passed, {FAILED} failed")
+ return 0 if FAILED == 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())