Skip to content

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

Python

One speaker-rename service for the web app and API v1 (#412 audit P10): API v1 renames now rebuild the Inquire chunks, and renames without a new summary rewrite the auto-export

Murtaza Nasire73201a95589
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 3414ad19..987e6f16 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2249,60 +2249,12 @@ def assign_speakers(recording_id):
else:
return jsonify({'error': f'Invalid value type for speaker "{label}"'}), 400
- # --- Apply names exactly as the web app's update_speakers does ---
- from src.services.speaker import apply_speaker_map, participants_from_segments, update_voice_profiles
- from src.services.voice_profiles import speech_seconds_by_label
-
- transcription_text = recording.transcription or ''
- try:
- transcription_data = json.loads(transcription_text)
- is_json = isinstance(transcription_data, list)
- except (json.JSONDecodeError, TypeError):
- is_json = False
-
- embeddings_updated = 0
- snippets_created = 0
- if is_json:
- seconds_by_key = speech_seconds_by_label(transcription_data)
- speaker_names_used, label_to_name = apply_speaker_map(transcription_data, speaker_map, current_user)
- recording.transcription = json.dumps(transcription_data)
- recording.participants = participants_from_segments(transcription_data)
- if speaker_names_used:
- update_speaker_usage(speaker_names_used)
- embeddings_updated, snippets_created = update_voice_profiles(
- recording, label_to_name, current_user, seconds_by_key)
- else:
- # Plain text transcript
- new_participants = []
- for speaker_label, new_name_info in speaker_map.items():
- new_name = new_name_info.get('name', '').strip()
- if new_name_info.get('isMe') and not new_name:
- new_name = current_user.name or 'Me'
- if new_name:
- transcription_text = re.sub(
- r'\[\s*' + re.escape(speaker_label) + r'\s*\]',
- f'[{new_name}]',
- transcription_text,
- flags=re.IGNORECASE
- )
- if new_name not in new_participants:
- new_participants.append(new_name)
- recording.transcription = transcription_text
- recording.participants = ', '.join(new_participants)
- if new_participants:
- update_speaker_usage(new_participants)
-
- db.session.commit()
-
- summary_queued = False
- if regenerate_summary:
- job_queue.enqueue(
- user_id=current_user.id,
- recording_id=recording.id,
- job_type='summarize',
- params={'user_id': current_user.id}
- )
- summary_queued = True
+ # Same rename and follow-up steps as the web update_speakers (#412).
+ from src.services.speaker_assignment import apply_speaker_names
+ result = apply_speaker_names(recording, current_user, speaker_map, regenerate_summary)
+ summary_queued = result['summary_queued']
+ embeddings_updated = result['embeddings_updated']
+ snippets_created = result['snippets_created']
return jsonify({
'success': True,
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 0e58cf2e..2071c588 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -938,69 +938,10 @@ def update_speakers(recording_id):
if speaker_map is None:
return jsonify({'error': 'No speaker map provided'}), 400
- transcription_text = recording.transcription
- is_json = False
- try:
- transcription_data = json.loads(transcription_text)
- # Updated check for our new simplified JSON format (a list of segment objects)
- is_json = isinstance(transcription_data, list)
- except (json.JSONDecodeError, TypeError):
- is_json = False
-
- speaker_names_used = []
-
- label_to_name = {}
- seconds_by_key = None
- if is_json:
- from src.services.voice_profiles import speech_seconds_by_label
- seconds_by_key = speech_seconds_by_label(transcription_data)
- speaker_names_used, label_to_name = apply_speaker_map(transcription_data, speaker_map, current_user)
- recording.transcription = json.dumps(transcription_data)
- recording.participants = participants_from_segments(transcription_data)
-
- else:
- # Handle plain text transcript
- new_participants = []
- for speaker_label, new_name_info in speaker_map.items():
- new_name = new_name_info.get('name', '').strip()
- # If isMe is checked but no name provided, use current user's name
- if new_name_info.get('isMe') and not new_name:
- new_name = current_user.name or 'Me'
-
- if new_name:
- transcription_text = re.sub(r'\[\s*' + re.escape(speaker_label) + r'\s*\]', f'[{new_name}]', transcription_text, flags=re.IGNORECASE)
- if new_name not in new_participants:
- new_participants.append(new_name)
-
- recording.transcription = transcription_text
- if new_participants:
- recording.participants = ', '.join(new_participants)
- speaker_names_used = new_participants
-
- # Update speaker usage statistics
- if speaker_names_used:
- update_speaker_usage(speaker_names_used)
-
- # Update speaker voice embeddings and snippets if available
- update_voice_profiles(recording, label_to_name, current_user, seconds_by_key)
-
- db.session.commit()
-
- # Speaker names changed the transcription text — rebuild the Inquire
- # chunks so semantic search answers with the applied names, not the
- # raw SPEAKER_XX labels. Background + best-effort.
- reindex_recording_chunks_async(recording_id)
-
- summary_queued = False
- if regenerate_summary:
- current_app.logger.info(f"Queueing summary regeneration for recording {recording_id} after speaker update.")
- job_queue.enqueue(
- user_id=current_user.id,
- recording_id=recording.id,
- job_type='summarize',
- params={'user_id': current_user.id}
- )
- summary_queued = True
+ # Same rename and follow-up steps as API v1 /speakers/assign (#412).
+ from src.services.speaker_assignment import apply_speaker_names
+ result = apply_speaker_names(recording, current_user, speaker_map, regenerate_summary)
+ summary_queued = result['summary_queued']
# Return recording with per-user status
recording_dict = recording.to_dict(viewer_user=current_user)
diff --git a/src/services/speaker_assignment.py b/src/services/speaker_assignment.py
new file mode 100644
index 00000000..805eb01f
--- /dev/null
+++ b/src/services/speaker_assignment.py
@@ -0,0 +1,82 @@
+"""Apply speaker names to a recording: one way for the web app and API v1.
+
+Before #412 API v1 /speakers/assign was a copy of the web update_speakers that
+skipped rebuilding the Inquire chunks, and neither route rewrote the auto-export
+when no summary followed, so exports kept the old speaker labels. Both routes
+now call apply_speaker_names; they keep their own access checks, input formats
+and response shapes.
+"""
+
+import json
+import re
+
+from flask import current_app
+
+from src.database import db
+
+
+def apply_speaker_names(recording, user, speaker_map, regenerate_summary=False):
+ """Rename speakers in the transcript and run what follows a rename.
+
+ speaker_map: {label: {'name': str, 'isMe': bool}}. Updates participants,
+ speaker usage and voice profiles, rebuilds the Inquire chunks, then either
+ queues a summary or rewrites the auto-export. Returns a dict with
+ summary_queued, embeddings_updated and snippets_created.
+ """
+ from src.services.speaker import (apply_speaker_map, participants_from_segments,
+ update_speaker_usage, update_voice_profiles)
+ from src.services.voice_profiles import speech_seconds_by_label
+
+ transcription_text = recording.transcription or ''
+ try:
+ transcription_data = json.loads(transcription_text)
+ is_json = isinstance(transcription_data, list)
+ except (json.JSONDecodeError, TypeError):
+ is_json = False
+
+ label_to_name, seconds_by_key, names_used = {}, None, []
+ if is_json:
+ seconds_by_key = speech_seconds_by_label(transcription_data)
+ names_used, label_to_name = apply_speaker_map(transcription_data, speaker_map, user)
+ recording.transcription = json.dumps(transcription_data)
+ recording.participants = participants_from_segments(transcription_data)
+ else:
+ for label, info in speaker_map.items():
+ name = (info.get('name') or '').strip()
+ if info.get('isMe') and not name:
+ name = user.name or 'Me'
+ if name:
+ transcription_text = re.sub(r'\[\s*' + re.escape(label) + r'\s*\]', f'[{name}]',
+ transcription_text, flags=re.IGNORECASE)
+ if name not in names_used:
+ names_used.append(name)
+ recording.transcription = transcription_text
+ if names_used:
+ recording.participants = ', '.join(names_used)
+
+ if names_used:
+ update_speaker_usage(names_used)
+ embeddings_updated, snippets_created = update_voice_profiles(recording, label_to_name, user, seconds_by_key) or (0, 0)
+ db.session.commit()
+
+ # The transcript text changed: rebuild the Inquire chunks (background).
+ from src.api import recordings as recordings_api
+ recordings_api.reindex_recording_chunks_async(recording.id)
+
+ summary_queued = False
+ if regenerate_summary:
+ from src.services.job_queue import job_queue
+ job_queue.enqueue(user_id=user.id, recording_id=recording.id, job_type='summarize',
+ params={'user_id': user.id})
+ summary_queued = True
+ else:
+ # Without a new summary, rewrite the export now so it shows the names.
+ from src.file_exporter import ENABLE_AUTO_EXPORT, export_recording
+ if ENABLE_AUTO_EXPORT:
+ try:
+ export_recording(recording.id)
+ except Exception as e:
+ current_app.logger.warning(f"Export after speaker update failed for {recording.id}: {e}")
+
+ return {'summary_queued': summary_queued, 'embeddings_updated': embeddings_updated,
+ 'snippets_created': snippets_created}
diff --git a/tests/test_inquire_mode.py b/tests/test_inquire_mode.py
index 2ce0dacf..2d769369 100644
--- a/tests/test_inquire_mode.py
+++ b/tests/test_inquire_mode.py
@@ -160,8 +160,15 @@ def test_speaker_and_transcript_edits_reindex_inquire_chunks():
assert hasattr(rec, 'reindex_recording_chunks_async'), "reindex helper missing"
us = _inspect.getsource(rec.update_speakers)
ut = _inspect.getsource(rec.update_transcript)
- assert 'reindex_recording_chunks_async(recording_id)' in us, \
- "update_speakers must reindex Inquire chunks after a speaker rename"
+ # Speaker renames go through the shared service (web and API v1, #412),
+ # which rebuilds the chunks.
+ from src.services import speaker_assignment as sa
+ from src.api import api_v1
+ assert 'apply_speaker_names(' in us, "update_speakers must use the shared speaker service"
+ assert 'apply_speaker_names(' in _inspect.getsource(api_v1.assign_speakers), \
+ "API v1 /speakers/assign must use the shared speaker service"
+ assert 'reindex_recording_chunks_async(recording.id)' in _inspect.getsource(sa.apply_speaker_names), \
+ "the speaker service must reindex Inquire chunks after a speaker rename"
assert 'reindex_recording_chunks_async(recording_id)' in ut, \
"update_transcript must reindex Inquire chunks after a transcript edit"
diff --git a/tests/test_speaker_assignment.py b/tests/test_speaker_assignment.py
new file mode 100644
index 00000000..5a106e12
--- /dev/null
+++ b/tests/test_speaker_assignment.py
@@ -0,0 +1,102 @@
+"""Speaker renames run the same steps from the web app and API v1 (#412 audit P10).
+
+API v1 /speakers/assign skipped rebuilding the Inquire chunks, and neither route
+rewrote the auto-export when no summary followed. Both now use
+apply_speaker_names.
+
+SHARED-DB: the user, recording and token are removed afterwards.
+"""
+
+import json
+import os
+import secrets
+import sys
+from unittest.mock import patch
+
+import pytest
+from flask import g, has_app_context
+from flask.testing import FlaskClient
+
+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, Recording, User
+from src.services.job_queue import job_queue
+from src.utils.token_auth import hash_token
+
+app.config["WTF_CSRF_ENABLED"] = False
+SEGMENTS = [{"speaker": "SPEAKER_00", "sentence": "Launch moves to Q3.", "start_time": 0.0, "end_time": 2.0},
+ {"speaker": "SPEAKER_01", "sentence": "Agreed.", "start_time": 2.0, "end_time": 3.0}]
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def world():
+ with app.app_context():
+ n = f"spk_{secrets.token_hex(4)}"
+ u = User(username=n, email=f"{n}@local.test", password="x", name="Jane")
+ db.session.add(u)
+ db.session.commit()
+ r = Recording(user_id=u.id, title="Sync", status="COMPLETED", original_filename="s.wav",
+ transcription=json.dumps(SEGMENTS))
+ plain = f"test-token-{secrets.token_urlsafe(16)}"
+ t = APIToken(user_id=u.id, token_hash=hash_token(plain), name="spk")
+ db.session.add_all([r, t])
+ db.session.commit()
+ ids = dict(user=u.id, rec=r.id, token=t.id)
+ yield ids, plain
+ with app.app_context():
+ 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 _effects():
+ return (patch("src.api.recordings.reindex_recording_chunks_async"),
+ patch("src.file_exporter.ENABLE_AUTO_EXPORT", True),
+ patch("src.file_exporter.export_recording"),
+ patch("src.services.speaker.update_voice_profiles", return_value=(0, 0)))
+
+
[email protected]("via", ["api_v1", "web"])
+def test_rename_reindexes_and_rewrites_the_export(world, via):
+ ids, plain = world
+ reindex, flag, export, voices = _effects()
+ with reindex as m_reindex, flag, export as m_export, voices:
+ if via == "api_v1":
+ with app.test_client() as c:
+ resp = c.put(f"/api/v1/recordings/{ids['rec']}/speakers/assign",
+ json={"speaker_map": {"SPEAKER_00": "Jane Doe"}},
+ headers={"Authorization": f"Bearer {plain}"})
+ else:
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(ids["user"])
+ resp = c.post(f"/recording/{ids['rec']}/update_speakers",
+ json={"speaker_map": {"SPEAKER_00": {"name": "Jane Doe", "isMe": False}}})
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ m_reindex.assert_called_once_with(ids["rec"])
+ m_export.assert_called_once_with(ids["rec"])
+ with app.app_context():
+ assert "Jane Doe" in db.session.get(Recording, ids["rec"]).transcription
+
+
+def test_rename_with_a_new_summary_exports_after_the_summary(world):
+ ids, plain = world
+ reindex, flag, export, voices = _effects()
+ with reindex, flag, export as m_export, voices, patch.object(job_queue, "enqueue", return_value=3) as enq:
+ with app.test_client() as c:
+ resp = c.put(f"/api/v1/recordings/{ids['rec']}/speakers/assign",
+ json={"speaker_map": {"SPEAKER_01": "Bob"}, "regenerate_summary": True},
+ headers={"Authorization": f"Bearer {plain}"})
+ assert resp.status_code == 200 and resp.get_json()["summary_queued"] is True
+ assert enq.call_args.kwargs["job_type"] == "summarize"
+ m_export.assert_not_called()