Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Extract events in the finishing step (#412, Db): events no longer depend on auto-summarization; without a summary the transcript is used up to the admin length limit
Murtaza Nasir105b1d4d0bc3
diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 680b43c7..1d16c522 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -355,18 +355,30 @@ def _end_transaction_before_external_call(*instances):session.expire_on_commit = previous-def finish_processing(recording_id):+def finish_processing(recording_id, events_transcript=None, events_summary=None):"""The last step of every processing path (#412).- Marks the recording COMPLETED, then applies team-tag auto-shares, writes the+ Extracts events (when the owner has event extraction on), marks the+ recording COMPLETED, then applies team-tag auto-shares, writes theauto-export and builds the Inquire chunks. Every exit of the pipeline callsthis (title only, summary, empty or skipped summary, short transcription),- so none of them can skip a step. The steps after COMPLETED are best-effort:- a failure is logged and the recording stays COMPLETED.+ so none of them can skip a step. Events no longer depend on a summary: with+ auto-summarization off they are extracted from the transcript. The steps+ after COMPLETED are best-effort: a failure is logged and the recording+ stays COMPLETED."""recording = db.session.get(Recording, recording_id)if not recording:return+ from src.utils.error_formatting import is_transcription_error+ owner = recording.owner+ if (owner and owner.extract_events and client is not None and recording.transcription+ and len(recording.transcription.strip()) >= 10 and not is_transcription_error(recording.transcription)):+ transcript = events_transcript or format_transcription_for_llm(recording.transcription)+ extract_events_from_transcript(recording_id, transcript, events_summary or "")+ recording = db.session.get(Recording, recording_id)+ if not recording:+ returnrecording.status = 'COMPLETED'recording.completed_at = datetime.utcnow()db.session.commit()@@ -906,11 +918,6 @@ Summarization Instructions:db.session.commit()current_app.logger.info(f"Summary generated successfully for recording {recording_id}")- # Extract events if enabled for this user BEFORE marking as completed- if recording.owner and recording.owner.extract_events:- extract_events_from_transcript(recording_id, formatted_transcription, summary)-- # Events are extracted before the recording is finished.summarization_end_time = time.time()recording.summarization_duration_seconds = int(summarization_end_time - summarization_start_time)db.session.commit()@@ -922,11 +929,12 @@ Summarization Instructions:recording.summarization_duration_seconds = int(summarization_end_time - summarization_start_time)db.session.commit()- # Status, auto-shares, export and Inquire chunks (#305, #412). The- # steps after COMPLETED are best-effort inside finish_processing, so- # a share/export hiccup cannot reach the except below and overwrite- # a good summary with an error.- finish_processing(recording_id)+ # Events, status, auto-shares, export and Inquire chunks (#305, #412).+ # The steps after COMPLETED are best-effort inside finish_processing,+ # so a share/export hiccup cannot reach the except below and+ # overwrite a good summary with an error.+ finish_processing(recording_id, events_transcript=formatted_transcription,+ events_summary=summary or None)except Exception as e:error_msg = format_api_error_message(str(e))@@ -964,6 +972,17 @@ def extract_events_from_transcript(recording_id, transcript_text, summary_text):if recording.owner:user_output_language = recording.owner.output_language+ # With a summary: the summary plus a transcript excerpt, as before. Without+ # one (auto-summarization off, #412): the transcript itself, up to the+ # admin transcript length limit.+ if summary_text:+ events_source = (f"Transcript Summary:\n{summary_text}\n\n"+ f"Transcript excerpt (for additional context):\n{transcript_text[:8000]}")+ else:+ limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ body = transcript_text if limit == -1 else transcript_text[:limit]+ events_source = f"Transcript:\n{body}"+# Build comprehensive context informationcurrent_date = datetime.now()context_parts = []@@ -1062,11 +1081,7 @@ For each event found, extract:- Attendees: List of people who should attend (if mentioned)- Reminder minutes: How how long before to remind (default 1 day)-Transcript Summary:-{summary_text}--Transcript excerpt (for additional context):-{transcript_text[:8000]}+{events_source}RESPONSE FORMAT:Respond with a JSON object containing an "events" array. If no events are found, return a JSON object with an empty events array.diff --git a/tests/test_events_without_summary.py b/tests/test_events_without_summary.pynew file mode 100644index 00000000..aa0b3529--- /dev/null+++ b/tests/test_events_without_summary.py@@ -0,0 +1,113 @@+"""Events are extracted by the finishing step, with or without a summary (#412, Db).++Before #412 event extraction ran only inside the summary task, so with+auto-summarization off it never ran, even when the owner had it on. It now+runs in finish_processing: from the summary plus a transcript excerpt when a+summary exists (as before), else from the transcript up to the admin length+limit.++SHARED-DB: the users and recordings created here are removed afterwards.+"""++import os+import sys+import uuid+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 Recording, User+import src.tasks.processing as proc+++def made():+ ids = []+ yield ids+ with app.app_context():+ db.session.rollback()+ for model, oid in reversed(ids):+ obj = db.session.get(model, oid)+ if obj is not None:+ db.session.delete(obj)+ db.session.commit()+++def _setup(made, extract=True, transcription="word " * 50, title="Board meeting"):+ s = uuid.uuid4().hex[:8]+ u = User(username=f"ev_{s}", email=f"ev_{s}@local.test", password="x", extract_events=extract)+ db.session.add(u)+ db.session.commit()+ made.append((User, u.id))+ r = Recording(user_id=u.id, title=title, original_filename="ev.mp3", status="PROCESSING",+ transcription=transcription)+ db.session.add(r)+ db.session.commit()+ made.append((Recording, r.id))+ return u, r+++def _quiet():+ return (patch.object(proc, "apply_team_tag_auto_shares"), patch.object(proc, "export_recording"),+ patch.object(proc, "process_recording_chunks"))+++def _completion(text):+ msg = MagicMock(content=text, reasoning=None)+ return MagicMock(choices=[MagicMock(message=msg)])+++def test_events_are_extracted_when_auto_summarization_is_off(made):+ with app.app_context():+ _, r = _setup(made)+ a, b, c = _quiet()+ with a, b, c, patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "extract_events_from_transcript") as ev:+ proc.generate_title_task(app.app_context(), r.id, will_auto_summarize=False)+ ev.assert_called_once()+ rid, transcript, summary = ev.call_args.args+ assert rid == r.id and summary == "" and "word" in transcript+++def test_no_events_when_the_owner_has_extraction_off(made):+ with app.app_context():+ _, r = _setup(made, extract=False)+ a, b, c = _quiet()+ with a, b, c, patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "extract_events_from_transcript") as ev:+ proc.finish_processing(r.id)+ ev.assert_not_called()+++def test_the_summary_path_extracts_events_once_with_the_summary(made):+ with app.app_context():+ _, r = _setup(made)+ a, b, c = _quiet()+ with a, b, c, patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "call_llm_completion", return_value=_completion("## Summary\nLaunch moved.")), \+ patch.object(proc, "extract_events_from_transcript") as ev:+ proc.generate_summary_only_task(app.app_context(), r.id)+ ev.assert_called_once()+ assert ev.call_args.args[2].startswith("## Summary")+++def test_without_a_summary_the_prompt_carries_the_transcript_past_8000_chars(made):+ with app.app_context():+ long = "Speaker 1: " + ("We meet on Friday at noon. " * 900) # ~24k chars+ _, r = _setup(made, transcription=long)+ seen = {}++ def fake_llm(messages, **kwargs):+ seen["prompt"] = "\n".join(m["content"] for m in messages)+ return _completion('{"events": []}')++ with patch.object(proc, "call_llm_completion", side_effect=fake_llm), \+ patch.object(proc, "client", MagicMock()):+ proc.extract_events_from_transcript(r.id, long, "")+ prompt = seen["prompt"]+ assert "Transcript Summary" not in prompt+ assert "Transcript:\n" in prompt+ assert prompt.count("We meet on Friday at noon.") > 8000 // len("We meet on Friday at noon. ")