Skip to content

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

Python

One reprocessing service for web, API v1 (single + batch) and the bulk action (#412 audit P8, P9): same checks, clearing of old results and job parameters; API v1 summarize gains prompt_mode and prompt_variables; guard test

Murtaza Nasirf9f0f1740be1
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 0fa350cf..3414ad19 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2386,16 +2386,9 @@ def start_transcription(recording_id):
if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'Permission denied'}), 403
- # Check if audio is available
- if recording.audio_deleted_at:
- return jsonify({'error': 'Audio has been deleted'}), 400
-
+ # Same checks, clearing and settings as the web reprocess (#412).
+ from src.services.reprocessing import queue_transcription_reprocess, ReprocessError
data = request.get_json() or {}
-
- # 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'),
@@ -2405,15 +2398,10 @@ def start_transcription(recording_id):
}
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=params
- )
+ try:
+ job_id = queue_transcription_reprocess(recording, current_user, overrides)
+ except ReprocessError as e:
+ return jsonify({'error': e.message}), e.status
return jsonify({
'success': True,
@@ -2436,24 +2424,17 @@ def start_summarization(recording_id):
if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'Permission denied'}), 403
- # Check if transcription exists
- if not recording.transcription:
- return jsonify({'error': 'No transcription available - transcribe first'}), 400
-
+ # Same checks, clearing and parameters as the web reprocess, including
+ # prompt_mode and prompt_variables (#412).
+ from src.services.reprocessing import queue_summary_reprocess, ReprocessError
data = request.get_json() or {}
-
- params = {
- 'custom_prompt': data.get('custom_prompt'),
- 'user_id': current_user.id
- }
-
- # Queue the job
- job_id = job_queue.enqueue(
- user_id=current_user.id,
- recording_id=recording_id,
- job_type='reprocess_summary',
- params={k: v for k, v in params.items() if v is not None}
- )
+ try:
+ job_id = queue_summary_reprocess(recording, current_user,
+ custom_prompt=data.get('custom_prompt'),
+ prompt_mode=data.get('prompt_mode'),
+ prompt_variables=data.get('prompt_variables'))
+ except ReprocessError as e:
+ return jsonify({'error': e.message}), e.status
return jsonify({
'success': True,
@@ -2875,19 +2856,13 @@ def batch_transcribe_recordings():
results.append({'id': recording_id, 'success': False, 'error': 'Permission denied'})
continue
- if recording.audio_deleted_at:
- results.append({'id': recording_id, 'success': False, 'error': 'Audio deleted'})
- continue
-
+ # Same checks, clearing and settings as a single reprocess (#412).
+ from src.services.reprocessing import queue_transcription_reprocess, ReprocessError
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=resolve_transcription_params(recording)
- )
+ job_id = queue_transcription_reprocess(recording, current_user)
results.append({'id': recording_id, 'success': True, 'job_id': job_id})
+ except ReprocessError as e:
+ results.append({'id': recording_id, 'success': False, 'error': e.message})
except Exception as e:
results.append({'id': recording_id, 'success': False, 'error': str(e)})
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 84b7cc7f..0e58cf2e 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -1150,38 +1150,9 @@ def reprocess_transcription(recording_id):
if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
- if not recording.audio_path or not get_storage_service().exists(recording.audio_path):
- return jsonify({'error': 'Audio file not found for reprocessing'}), 404
-
- if recording.status in ['QUEUED', 'PROCESSING', 'SUMMARIZING']:
- return jsonify({'error': 'Recording is already being processed'}), 400
-
- # File path and name for processing (conversion handled in background task if needed)
- filepath = recording.audio_path
- filename_for_asr = recording.original_filename or os.path.basename(filepath)
-
- # --- Proceed with reprocessing ---
- recording.transcription = None
- recording.summary = None
- recording.status = 'QUEUED' # Will change to PROCESSING when job starts
-
- # Clear existing events since they depend on the transcription
- Event.query.filter_by(recording_id=recording_id).delete()
-
- db.session.commit()
-
- current_app.logger.info(f"Queueing transcription reprocessing for recording {recording_id}")
-
- # Prepare job parameters
+ # Checks, clearing and settings are shared with every reprocess path (#412).
+ from src.services.reprocessing import queue_transcription_reprocess, ReprocessError
data = request.json or {}
- start_time = datetime.utcnow()
- app_context = current_app._get_current_object().app_context()
-
- # 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'),
@@ -1191,14 +1162,11 @@ def reprocess_transcription(recording_id):
}
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,
- recording_id=recording.id,
- job_type='reprocess_transcription',
- params=job_params
- )
+ try:
+ queue_transcription_reprocess(recording, current_user, overrides)
+ except ReprocessError as e:
+ return jsonify({'error': e.message}), e.status
+ current_app.logger.info(f"Queued transcription reprocessing for recording {recording_id}")
# Get queue position for response
queue_position = job_queue.get_position_in_queue(recording.id)
@@ -1235,69 +1203,18 @@ def reprocess_summary(recording_id):
if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
- # Check if transcription exists
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- return jsonify({'error': 'No valid transcription available for summary generation'}), 400
-
- # Check if transcription is an error message (not actual content)
- if is_transcription_error(recording.transcription):
- return jsonify({'error': 'Cannot generate summary: transcription failed. Please reprocess the transcription first.'}), 400
-
- # Check if already processing
- if recording.status in ['PROCESSING', 'SUMMARIZING']:
- return jsonify({'error': 'Recording is already being processed'}), 400
-
- # Check if OpenRouter client is available
- if client is None:
- return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
-
- # Get custom prompt + mode from request if provided
+ # Checks, clearing and job parameters are shared with every reprocess
+ # path, including API v1 and the bulk action (#412).
+ from src.services.reprocessing import queue_summary_reprocess, ReprocessError
data = request.get_json() or {}
- custom_prompt = data.get('custom_prompt', '').strip() if data.get('custom_prompt') else None
- prompt_mode = (data.get('prompt_mode') or 'replace').strip().lower()
- if prompt_mode not in ('replace', 'append'):
- prompt_mode = 'replace'
- custom_prompt_append = bool(custom_prompt) and prompt_mode == 'append'
-
- # Debug logging
- if custom_prompt:
- current_app.logger.info(
- f"Received custom prompt override for recording {recording_id} "
- f"(mode={prompt_mode}, length={len(custom_prompt)})"
- )
- else:
- current_app.logger.info(f"No custom prompt override provided for recording {recording_id}, will use default priority")
-
- # Per-recording prompt-template variables. Sanitised through the same
- # helper used at upload time so reprocess can't bypass the caps.
- from src.utils.prompt_variables import sanitize_variable_values
- raw_prompt_variables = data.get('prompt_variables')
- if raw_prompt_variables is not None:
- recording.prompt_variables = sanitize_variable_values(raw_prompt_variables)
-
- # Clear existing summary (status will be set to QUEUED by job_queue.enqueue)
- recording.summary = None
-
- # Clear existing events since they might be re-extracted during summary generation
- Event.query.filter_by(recording_id=recording_id).delete()
-
- db.session.commit()
-
- current_app.logger.info(f"Queueing summary reprocessing for recording {recording_id}" +
- (f" with custom prompt (length: {len(custom_prompt)})" if custom_prompt else ""))
-
- # Queue summary generation job
- job_params = {
- 'custom_prompt': custom_prompt,
- 'custom_prompt_append': custom_prompt_append,
- 'user_id': current_user.id
- }
- job_queue.enqueue(
- user_id=current_user.id,
- recording_id=recording.id,
- job_type='reprocess_summary',
- params=job_params
- )
+ try:
+ queue_summary_reprocess(recording, current_user,
+ custom_prompt=data.get('custom_prompt'),
+ prompt_mode=data.get('prompt_mode'),
+ prompt_variables=data.get('prompt_variables'))
+ except ReprocessError as e:
+ return jsonify({'error': e.message}), e.status
+ current_app.logger.info(f"Queued summary reprocessing for recording {recording_id}")
# Refresh recording to get updated status
db.session.refresh(recording)
@@ -4577,29 +4494,16 @@ def bulk_reprocess():
if recording.status not in ['COMPLETED', 'FAILED']:
continue
- # For transcription reprocess, need audio file
- if reprocess_type == 'transcription':
- if not recording.audio_path or not get_storage_service().exists(recording.audio_path):
- continue
- job_type = 'reprocess_transcription'
- else:
- # For summary, need transcription
- if not recording.transcription:
- continue
- job_type = 'reprocess_summary'
-
- # Queue the job. A transcription reprocess gets the recording's
- # resolved model, hotwords and speaker hints, as a single
- # reprocess and API v1 batch transcribe do.
- params = {'user_id': current_user.id}
- if job_type == 'reprocess_transcription':
- params = {**resolve_transcription_params(recording), **params}
- job_queue.enqueue(
- user_id=current_user.id,
- recording_id=recording.id,
- job_type=job_type,
- params=params
- )
+ # Same checks, clearing and settings as a single reprocess (#412).
+ from src.services.reprocessing import (
+ queue_transcription_reprocess, queue_summary_reprocess, ReprocessError)
+ try:
+ if reprocess_type == 'transcription':
+ queue_transcription_reprocess(recording, current_user)
+ else:
+ queue_summary_reprocess(recording, current_user)
+ except ReprocessError:
+ continue
queued_ids.append(recording_id)
diff --git a/src/services/reprocessing.py b/src/services/reprocessing.py
new file mode 100644
index 00000000..9bb80fb0
--- /dev/null
+++ b/src/services/reprocessing.py
@@ -0,0 +1,94 @@
+"""Queue a transcription or summary again: the one way every route does it.
+
+Before #412 the web routes, API v1 (single and batch) and the bulk action each
+had their own copy: some cleared the old transcript, summary and events and
+some did not, and the API skipped the status, audio and transcription checks.
+Every reprocess path now calls these functions, so the checks, the clearing
+and the resolved settings are the same on all of them. The routes keep their
+own access checks and response shapes.
+"""
+
+from src.database import db
+from src.models import Event
+
+IN_PROGRESS = ('QUEUED', 'PROCESSING', 'SUMMARIZING')
+
+
+class ReprocessError(Exception):
+ """A reprocess request that cannot be queued; status is the HTTP status."""
+
+ def __init__(self, message, status=400):
+ super().__init__(message)
+ self.message = message
+ self.status = status
+
+
+def queue_transcription_reprocess(recording, user, overrides=None):
+ """Clear the transcript, summary and events and queue a new transcription.
+
+ overrides: per-request transcription settings (language, speaker counts,
+ hotwords, initial prompt, model); the rest comes from tag, folder, account
+ and admin defaults (resolve_transcription_params). The title is generated
+ again unless the user typed it (title_source). Returns the job id.
+ """
+ from src.services.job_queue import job_queue
+ from src.services.storage import get_storage_service
+ from src.services.transcription_defaults import resolve_transcription_params
+
+ if recording.audio_deleted_at or not recording.audio_path \
+ or not get_storage_service().exists(recording.audio_path):
+ raise ReprocessError('Audio file not found for reprocessing', 404)
+ if recording.status in IN_PROGRESS:
+ raise ReprocessError('Recording is already being processed', 400)
+
+ recording.transcription = None
+ recording.summary = None
+ recording.status = 'QUEUED'
+ Event.query.filter_by(recording_id=recording.id).delete()
+ db.session.commit()
+
+ params = resolve_transcription_params(recording, overrides or {})
+ params['user_id'] = user.id
+ return job_queue.enqueue(user_id=user.id, recording_id=recording.id,
+ job_type='reprocess_transcription', params=params)
+
+
+def queue_summary_reprocess(recording, user, custom_prompt=None, prompt_mode='replace',
+ prompt_variables=None, job_type='reprocess_summary'):
+ """Clear the summary and events and queue a new summary. Returns the job id.
+
+ custom_prompt replaces the resolved prompt, or is appended to it when
+ prompt_mode is 'append'. prompt_variables, when given, replace the
+ recording's template variables (sanitised as at upload).
+ """
+ from src.services import llm
+ from src.services.job_queue import job_queue
+ from src.utils.error_formatting import is_transcription_error
+ from src.utils.prompt_variables import sanitize_variable_values
+
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ raise ReprocessError('No valid transcription available for summary generation', 400)
+ if is_transcription_error(recording.transcription):
+ raise ReprocessError('Cannot generate summary: transcription failed. Please reprocess the transcription first.', 400)
+ if recording.status in ('PROCESSING', 'SUMMARIZING'):
+ raise ReprocessError('Recording is already being processed', 400)
+ if llm.client is None:
+ raise ReprocessError('Summary service is not available (LLM client not configured)', 503)
+
+ custom_prompt = (custom_prompt or '').strip() or None
+ mode = (prompt_mode or 'replace').strip().lower()
+ if mode not in ('replace', 'append'):
+ mode = 'replace'
+ if prompt_variables is not None:
+ recording.prompt_variables = sanitize_variable_values(prompt_variables)
+
+ recording.summary = None
+ Event.query.filter_by(recording_id=recording.id).delete()
+ db.session.commit()
+
+ params = {
+ 'custom_prompt': custom_prompt,
+ 'custom_prompt_append': bool(custom_prompt) and mode == 'append',
+ 'user_id': user.id,
+ }
+ return job_queue.enqueue(user_id=user.id, recording_id=recording.id, job_type=job_type, params=params)
diff --git a/tests/test_cov_recordings_read.py b/tests/test_cov_recordings_read.py
index 1b3cef22..84175974 100644
--- a/tests/test_cov_recordings_read.py
+++ b/tests/test_cov_recordings_read.py
@@ -110,7 +110,9 @@ class FakeStorage:
@contextmanager
def use_storage(storage):
- with patch.object(rec_module, "get_storage_service", return_value=storage):
+ # Reprocessing checks storage in src/services/reprocessing.py (#412).
+ with patch.object(rec_module, "get_storage_service", return_value=storage), \
+ patch("src.services.storage.get_storage_service", return_value=storage):
yield storage
@@ -968,7 +970,7 @@ def test_reprocess_summary_enqueues(owner):
c = new_client()
login(c, owner)
# client (the OpenRouter client) must not be None for the endpoint to proceed.
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary", json={})
assert resp.status_code in (200, 202)
assert len(calls) == 1
@@ -983,7 +985,7 @@ def test_reprocess_summary_custom_prompt_append(owner):
c = new_client()
login(c, owner)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary",
json={"custom_prompt": "Be brief", "prompt_mode": "append"})
assert resp.status_code in (200, 202)
@@ -999,7 +1001,7 @@ def test_reprocess_summary_no_transcription_400(owner):
c = new_client()
login(c, owner)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary", json={})
assert resp.status_code == 400
assert calls == []
@@ -1012,7 +1014,7 @@ def test_reprocess_summary_transcription_error_400(owner):
c = new_client()
login(c, owner)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary", json={})
assert resp.status_code == 400
assert calls == []
@@ -1025,7 +1027,7 @@ def test_reprocess_summary_non_owner_denied(owner, other):
c = new_client()
login(c, other)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary", json={})
assert resp.status_code == 403
assert calls == []
@@ -1038,7 +1040,7 @@ def test_reprocess_summary_client_unavailable_503(owner):
c = new_client()
login(c, owner)
- with patch.object(rec_module, "client", None), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", None), patch("src.services.llm.client", None), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/reprocess_summary", json={})
assert resp.status_code == 503
assert calls == []
@@ -1056,7 +1058,7 @@ def test_generate_summary_enqueues(owner):
c = new_client()
login(c, owner)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/generate_summary", json={})
assert resp.status_code in (200, 202)
assert len(calls) == 1
@@ -1070,7 +1072,7 @@ def test_generate_summary_non_owner_denied(owner, other):
c = new_client()
login(c, other)
- with patch.object(rec_module, "client", object()), capture_enqueue() as calls:
+ with patch.object(rec_module, "client", object()), patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post(f"/recording/{rid}/generate_summary", json={})
assert resp.status_code == 403
assert calls == []
@@ -1209,12 +1211,12 @@ def test_bulk_delete_too_many_400(owner):
def test_bulk_reprocess_summary_enqueues(owner):
with _db():
u = db.session.get(User, owner)
- a = make_recording(u, status="COMPLETED", transcription="content a").id
- b = make_recording(u, status="COMPLETED", transcription="content b").id
+ a = make_recording(u, status="COMPLETED", transcription="content of recording a").id
+ b = make_recording(u, status="COMPLETED", transcription="content of recording b").id
c = new_client()
login(c, owner)
- with capture_enqueue() as calls:
+ with patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post("/api/recordings/bulk-reprocess",
json={"recording_ids": [a, b], "type": "summary"})
assert resp.status_code == 200
@@ -1244,12 +1246,12 @@ def test_bulk_reprocess_skips_non_owned(owner, other):
with _db():
u = db.session.get(User, owner)
o = db.session.get(User, other)
- mine = make_recording(u, status="COMPLETED", transcription="x").id
- theirs = make_recording(o, status="COMPLETED", transcription="y").id
+ mine = make_recording(u, status="COMPLETED", transcription="my own recording text").id
+ theirs = make_recording(o, status="COMPLETED", transcription="their recording text").id
c = new_client()
login(c, owner)
- with capture_enqueue() as calls:
+ with patch("src.services.llm.client", object()), capture_enqueue() as calls:
resp = c.post("/api/recordings/bulk-reprocess",
json={"recording_ids": [mine, theirs], "type": "summary"})
assert resp.status_code == 200
diff --git a/tests/test_model_defaults_409.py b/tests/test_model_defaults_409.py
index e55baa38..657d1a39 100644
--- a/tests/test_model_defaults_409.py
+++ b/tests/test_model_defaults_409.py
@@ -286,6 +286,7 @@ def test_bulk_reprocess_transcription_uses_the_resolved_params(ctx):
storage = MagicMock()
storage.exists.return_value = True
with patch('src.api.recordings.get_storage_service', return_value=storage), \
+ patch('src.services.storage.get_storage_service', return_value=storage), \
patch('src.api.recordings.job_queue.enqueue', return_value=1) as enqueue:
r = _client(user).post('/api/recordings/bulk-reprocess',
json={'recording_ids': [rec.id], 'type': 'transcription'})
diff --git a/tests/test_pipeline_guards.py b/tests/test_pipeline_guards.py
index 5f27079a..ab825d34 100644
--- a/tests/test_pipeline_guards.py
+++ b/tests/test_pipeline_guards.py
@@ -81,3 +81,22 @@ def test_calendar_files_are_built_in_one_place():
for rel in ("src/api/api_v1.py", "src/api/events.py"):
text = open(os.path.join(ROOT, rel), encoding="utf-8").read()
assert "BEGIN:VEVENT" not in text, f"{rel} builds ICS itself; use generate_combined_ics"
+
+
+def test_reprocess_jobs_are_queued_only_by_the_reprocessing_service():
+ """A route that queues reprocess_* itself skips the shared checks and clearing (#412)."""
+ offenders = []
+ for dirpath, _, files in os.walk(SRC):
+ for name in files:
+ if not name.endswith(".py"):
+ continue
+ rel = os.path.relpath(os.path.join(dirpath, name), ROOT)
+ if rel == "src/services/reprocessing.py":
+ continue
+ for node in ast.walk(ast.parse(open(os.path.join(dirpath, name), encoding="utf-8").read())):
+ if isinstance(node, ast.Call) and getattr(node.func, "attr", None) == "enqueue":
+ for kw in node.keywords:
+ if kw.arg == "job_type" and isinstance(kw.value, ast.Constant) \
+ and kw.value.value in ("reprocess_transcription", "reprocess_summary"):
+ offenders.append(f"{rel}:{node.lineno} queues {kw.value.value}")
+ assert not offenders, "Use src.services.reprocessing:\n" + "\n".join(offenders)
diff --git a/tests/test_reprocessing_service.py b/tests/test_reprocessing_service.py
new file mode 100644
index 00000000..9ae69c3b
--- /dev/null
+++ b/tests/test_reprocessing_service.py
@@ -0,0 +1,132 @@
+"""One way to reprocess, whichever route asks (#412 audit P8, P9).
+
+API v1 transcribe and summarize, the v1 batch and the web bulk action now use
+the same service as the web reprocess buttons: the same checks (audio present,
+not already processing, a usable transcript, an LLM client), the same clearing
+of old transcript, summary and events, and the same job parameters.
+
+SHARED-DB: users, recordings, events and tokens are removed afterwards.
+"""
+
+import os
+import secrets
+import sys
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import APIToken, Event, Recording, User
+from src.services.job_queue import job_queue
+from src.utils.token_auth import hash_token
+
+TRANSCRIPT = "Speaker 1: We agreed to move the launch to next quarter."
+
+
+def world():
+ with app.app_context():
+ n = f"reproc_{secrets.token_hex(4)}"
+ u = User(username=n, email=f"{n}@local.test", password="x")
+ db.session.add(u)
+ db.session.commit()
+ r = Recording(user_id=u.id, title="Sync", status="COMPLETED", original_filename="s.wav",
+ audio_path="local://s.wav", transcription=TRANSCRIPT, summary="Old summary")
+ plain = f"test-token-{secrets.token_urlsafe(16)}"
+ t = APIToken(user_id=u.id, token_hash=hash_token(plain), name="reproc")
+ db.session.add_all([r, t])
+ db.session.commit()
+ db.session.add(Event(recording_id=r.id, title="Old event", start_datetime=datetime(2026, 3, 9, 9)))
+ db.session.commit()
+ ids = dict(user=u.id, rec=r.id, token=t.id)
+ yield ids, plain
+ with app.app_context():
+ Event.query.filter_by(recording_id=ids["rec"]).delete()
+ for model, key in ((APIToken, "token"), (Recording, "rec"), (User, "user")):
+ obj = db.session.get(model, ids[key])
+ if obj is not None:
+ db.session.delete(obj)
+ db.session.commit()
+
+
+def _storage(exists=True):
+ s = MagicMock()
+ s.exists.return_value = exists
+ return patch("src.services.storage.get_storage_service", return_value=s)
+
+
+def _post(plain, path, body=None):
+ with app.test_client() as c:
+ return c.post(path, json=body or {}, headers={"Authorization": f"Bearer {plain}"})
+
+
+def test_v1_transcribe_clears_old_results_like_the_web_route(world):
+ ids, plain = world
+ with _storage(), patch.object(job_queue, "enqueue", return_value=7) as enq:
+ resp = _post(plain, f"/api/v1/recordings/{ids['rec']}/transcribe", {"language": "de"})
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ assert enq.call_args.kwargs["job_type"] == "reprocess_transcription"
+ assert enq.call_args.kwargs["params"]["language"] == "de"
+ with app.app_context():
+ r = db.session.get(Recording, ids["rec"])
+ assert (r.transcription, r.summary, r.status) == (None, None, "QUEUED")
+ assert Event.query.filter_by(recording_id=ids["rec"]).count() == 0
+
+
+def test_v1_transcribe_refuses_a_recording_already_processing(world):
+ ids, plain = world
+ with app.app_context():
+ db.session.get(Recording, ids["rec"]).status = "PROCESSING"
+ db.session.commit()
+ with _storage(), patch.object(job_queue, "enqueue") as enq:
+ resp = _post(plain, f"/api/v1/recordings/{ids['rec']}/transcribe")
+ assert resp.status_code == 400
+ enq.assert_not_called()
+
+
+def test_v1_transcribe_refuses_missing_audio(world):
+ ids, plain = world
+ with _storage(exists=False), patch.object(job_queue, "enqueue") as enq:
+ resp = _post(plain, f"/api/v1/recordings/{ids['rec']}/transcribe")
+ assert resp.status_code == 404
+ enq.assert_not_called()
+
+
+def test_v1_summarize_supports_append_mode_and_clears_old_results(world):
+ ids, plain = world
+ with patch("src.services.llm.client", object()), patch.object(job_queue, "enqueue", return_value=8) as enq:
+ resp = _post(plain, f"/api/v1/recordings/{ids['rec']}/summarize",
+ {"custom_prompt": "Focus on dates", "prompt_mode": "append"})
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ params = enq.call_args.kwargs["params"]
+ assert params["custom_prompt"] == "Focus on dates" and params["custom_prompt_append"] is True
+ with app.app_context():
+ assert db.session.get(Recording, ids["rec"]).summary is None
+ assert Event.query.filter_by(recording_id=ids["rec"]).count() == 0
+
+
+def test_v1_summarize_refuses_a_failed_transcription(world):
+ ids, plain = world
+ with app.app_context():
+ db.session.get(Recording, ids["rec"]).transcription = "Transcription failed: ASR service unreachable"
+ db.session.commit()
+ with patch("src.services.llm.client", object()), patch.object(job_queue, "enqueue") as enq:
+ resp = _post(plain, f"/api/v1/recordings/{ids['rec']}/summarize")
+ assert resp.status_code == 400
+ enq.assert_not_called()
+
+
+def test_v1_batch_uses_the_same_checks(world):
+ ids, plain = world
+ with app.app_context():
+ db.session.get(Recording, ids["rec"]).status = "SUMMARIZING"
+ db.session.commit()
+ with _storage(), patch.object(job_queue, "enqueue") as enq:
+ resp = _post(plain, "/api/v1/recordings/batch/transcribe", {"recording_ids": [ids["rec"]]})
+ assert resp.status_code == 200
+ assert resp.get_json()["results"][0] == {"id": ids["rec"], "success": False,
+ "error": "Recording is already being processed"}
+ enq.assert_not_called()