Skip to content

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

Python

Speaker merge: show the kept speaker's name in every recording of the merged speakers

Murtaza Nasirbfa06b62a791
diff --git a/src/api/speakers.py b/src/api/speakers.py
index 5b00c4b1..639791cb 100644
--- a/src/api/speakers.py
+++ b/src/api/speakers.py
@@ -168,66 +168,13 @@ def update_speaker(speaker_id):
# Update the speaker name
speaker.name = new_name
- # Update all transcript chunks that reference this speaker's old name
- # This ensures the name change cascades to all recordings
- from src.models import TranscriptChunk
- chunks_updated = TranscriptChunk.query.filter_by(
- user_id=current_user.id,
- speaker_name=old_name
- ).update({'speaker_name': new_name})
-
- # Update Recording.participants field (comma-separated list of speakers)
- # AND update speaker names in the transcription JSON
- recordings_updated = 0
- user_recordings = Recording.query.filter_by(user_id=current_user.id).all()
-
- for recording in user_recordings:
- updated = False
-
- # Update participants field if it contains the old name
- if recording.participants and old_name in recording.participants:
- # Replace exact speaker name matches in participants list
- # Handle various formats: "Ross", "Ross, John", "John, Ross", etc.
- participants_list = [p.strip() for p in recording.participants.split(',')]
- if old_name in participants_list:
- # Replace the old name with new name
- participants_list = [new_name if p == old_name else p for p in participants_list]
- recording.participants = ', '.join(participants_list)
- updated = True
-
- # Update speaker names in the transcription JSON
- # This is what displays in the transcript view speaker badges
- if recording.transcription:
- try:
- transcription_data = json.loads(recording.transcription)
-
- # Handle JSON format (array of segments with speaker field)
- if isinstance(transcription_data, list):
- segments_updated = False
- for segment in transcription_data:
- if segment.get('speaker') == old_name:
- segment['speaker'] = new_name
- segments_updated = True
-
- if segments_updated:
- recording.transcription = json.dumps(transcription_data)
- updated = True
- except (json.JSONDecodeError, TypeError):
- # Not JSON or invalid format, skip
- pass
-
- # The label map records which name each diarization label shows;
- # without this the next save would think the voice was removed.
- if recording.speaker_label_map and old_name in recording.speaker_label_map.values():
- recording.speaker_label_map = {
- label: (new_name if name == old_name else name)
- for label, name in recording.speaker_label_map.items()}
- updated = True
-
- if updated:
- recordings_updated += 1
+ # Cascade the new name to every recording of this user
+ from src.services.speaker_merge import rename_speaker_in_recordings, refresh_renamed_recordings
+ chunks_updated, renamed = rename_speaker_in_recordings(current_user.id, old_name, new_name)
+ recordings_updated = len(renamed)
db.session.commit()
+ refresh_renamed_recordings(renamed)
current_app.logger.info(
f"Updated speaker {speaker_id} from '{old_name}' to '{new_name}': "
diff --git a/src/services/speaker_merge.py b/src/services/speaker_merge.py
index 1bf4c9b2..ef039426 100644
--- a/src/services/speaker_merge.py
+++ b/src/services/speaker_merge.py
@@ -8,10 +8,13 @@ When speakers are merged:
- Voice embeddings are combined using weighted average
- All snippets are transferred to the target speaker
- Usage statistics are combined
+- Every recording that shows a source speaker's name shows the target's name
- Source speakers are deleted
- Confidence score is recalculated
"""
+import json
+
import numpy as np
from src.database import db
from src.models import Speaker, SpeakerSnippet
@@ -99,6 +102,13 @@ def merge_speakers(target_id, source_ids, user_id):
db.session.flush()
refresh_speaker_summary(target)
+ # Recordings keep speaker names, not speaker ids: without this the
+ # recordings of a merged speaker kept showing the old name.
+ renamed = set()
+ for source in sources:
+ _, recording_ids = rename_speaker_in_recordings(user_id, source.name, target.name)
+ renamed.update(recording_ids)
+
# Delete source speakers
for source in sources:
db.session.delete(source)
@@ -106,9 +116,92 @@ def merge_speakers(target_id, source_ids, user_id):
# Commit all changes
db.session.commit()
+ refresh_renamed_recordings(renamed)
return target
+def _same_name(a, b):
+ return isinstance(a, str) and a.strip().lower() == b.strip().lower()
+
+
+def rename_speaker_in_recordings(user_id, old_name, new_name):
+ """Show new_name wherever the user's recordings show old_name.
+
+ Covers the transcript segments, the participants list, the diarization
+ label map and the Inquire chunks' speaker column. Names match ignoring
+ case and surrounding spaces, as saved speakers do. Does not commit.
+ Returns (chunks_updated, ids of the recordings changed).
+ """
+ from src.models import Recording, TranscriptChunk
+
+ old_key = old_name.strip().lower()
+ chunks_updated = 0
+ for chunk in TranscriptChunk.query.filter(
+ TranscriptChunk.user_id == user_id,
+ db.func.lower(db.func.trim(TranscriptChunk.speaker_name)) == old_key).all():
+ chunk.speaker_name = new_name
+ chunks_updated += 1
+
+ changed = []
+ for recording in Recording.query.filter_by(user_id=user_id).all():
+ updated = False
+
+ if recording.participants:
+ names = [p.strip() for p in recording.participants.split(',') if p.strip()]
+ if any(_same_name(p, old_name) for p in names):
+ merged = []
+ for p in names:
+ p = new_name if _same_name(p, old_name) else p
+ if not any(_same_name(p, m) for m in merged):
+ merged.append(p)
+ recording.participants = ', '.join(merged)
+ updated = True
+
+ if recording.transcription:
+ try:
+ segments = json.loads(recording.transcription)
+ except (json.JSONDecodeError, TypeError):
+ segments = None
+ if isinstance(segments, list):
+ hit = False
+ for segment in segments:
+ if isinstance(segment, dict) and _same_name(segment.get('speaker'), old_name):
+ segment['speaker'] = new_name
+ hit = True
+ if hit:
+ recording.transcription = json.dumps(segments)
+ updated = True
+
+ # The label map records which name each diarization label shows;
+ # without this the next save would think the voice was removed.
+ label_map = recording.speaker_label_map
+ if isinstance(label_map, dict) and any(_same_name(n, old_name) for n in label_map.values()):
+ recording.speaker_label_map = {
+ label: (new_name if _same_name(n, old_name) else n) for label, n in label_map.items()}
+ updated = True
+
+ if updated:
+ changed.append(recording.id)
+ return chunks_updated, changed
+
+
+def refresh_renamed_recordings(recording_ids):
+ """After names change in committed recordings: rebuild their Inquire
+ chunks (the chunk text holds the names) and rewrite their auto-exports."""
+ if not recording_ids:
+ return
+ from flask import current_app
+ from src.api import recordings as recordings_api
+ from src.file_exporter import ENABLE_AUTO_EXPORT, export_recording
+ for rid in sorted(recording_ids):
+ recordings_api.reindex_recording_chunks_async(rid)
+ if ENABLE_AUTO_EXPORT:
+ try:
+ export_recording(rid)
+ except Exception as e:
+ current_app.logger.warning(f"Export after speaker rename failed for {rid}: {e}")
+
+
def _merge_voice_samples(target, sources):
"""Give the target every voice sample of the sources.
diff --git a/tests/test_speaker_merge_renames.py b/tests/test_speaker_merge_renames.py
new file mode 100644
index 00000000..74320e78
--- /dev/null
+++ b/tests/test_speaker_merge_renames.py
@@ -0,0 +1,138 @@
+"""Merging speakers renames them in the recordings.
+
+Recordings keep speaker names, not speaker ids. A merge in Speaker Management
+moved the voice samples and snippets to the kept speaker, but every recording
+of a merged speaker went on showing the old name. Merge and rename now share
+rename_speaker_in_recordings, and both rebuild the Inquire chunks and rewrite
+the exports of the recordings they change.
+
+SHARED-DB: users, speakers, recordings and chunks 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 Recording, Speaker, TranscriptChunk, User
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def _segments(*names):
+ return json.dumps([{"speaker": n, "sentence": f"{n} spoke.", "start_time": float(i), "end_time": i + 1.0}
+ for i, n in enumerate(names)])
+
+
+def world():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ me = User(username=f"mrg_{s}", email=f"mrg_{s}@local.test", password="x")
+ other = User(username=f"mrgo_{s}", email=f"mrgo_{s}@local.test", password="x")
+ db.session.add_all([me, other])
+ db.session.commit()
+ keep = Speaker(name="Murtaza", user_id=me.id, use_count=3)
+ old = Speaker(name="Murtaza Nasir", user_id=me.id, use_count=2)
+ bob = Speaker(name="Bob", user_id=me.id, use_count=1)
+ db.session.add_all([keep, old, bob])
+ only_old = Recording(user_id=me.id, title="A", status="COMPLETED", original_filename="a.wav",
+ transcription=_segments("Murtaza Nasir", "Bob"), participants="Bob, Murtaza Nasir",
+ speaker_label_map={"SPEAKER_00": "Murtaza Nasir", "SPEAKER_01": "Bob"})
+ both = Recording(user_id=me.id, title="B", status="COMPLETED", original_filename="b.wav",
+ transcription=_segments("murtaza nasir", "Murtaza"), participants="Murtaza, Murtaza Nasir")
+ untouched = Recording(user_id=me.id, title="C", status="COMPLETED", original_filename="c.wav",
+ transcription=_segments("Bob"), participants="Bob")
+ theirs = Recording(user_id=other.id, title="D", status="COMPLETED", original_filename="d.wav",
+ transcription=_segments("Murtaza Nasir"), participants="Murtaza Nasir")
+ db.session.add_all([only_old, both, untouched, theirs])
+ db.session.commit()
+ chunk = TranscriptChunk(recording_id=only_old.id, user_id=me.id, chunk_index=0,
+ content="Murtaza Nasir: Murtaza Nasir spoke.", speaker_name="Murtaza Nasir")
+ db.session.add(chunk)
+ db.session.commit()
+ ids = dict(me=me.id, other=other.id, keep=keep.id, old=old.id, bob=bob.id, only_old=only_old.id,
+ both=both.id, untouched=untouched.id, theirs=theirs.id, chunk=chunk.id)
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ TranscriptChunk.query.filter(TranscriptChunk.user_id.in_([ids["me"], ids["other"]])).delete(
+ synchronize_session=False)
+ Recording.query.filter(Recording.user_id.in_([ids["me"], ids["other"]])).delete(synchronize_session=False)
+ Speaker.query.filter(Speaker.user_id.in_([ids["me"], ids["other"]])).delete(synchronize_session=False)
+ User.query.filter(User.id.in_([ids["me"], ids["other"]])).delete(synchronize_session=False)
+ db.session.commit()
+
+
+def _client(uid):
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(uid)
+ return c
+
+
+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"))
+
+
+def _speakers(rid):
+ rec = db.session.get(Recording, rid)
+ return [seg["speaker"] for seg in json.loads(rec.transcription)], rec.participants, rec.speaker_label_map
+
+
+def test_a_merge_renames_the_merged_speaker_in_every_recording(world):
+ reindex, flag, export = _effects()
+ with reindex as m_reindex, flag, export as m_export:
+ resp = _client(world["me"]).post("/speakers/merge",
+ json={"target_id": world["keep"], "source_ids": [world["old"]]})
+ assert resp.status_code == 200, resp.get_json()
+ with app.app_context():
+ segs, parts, label_map = _speakers(world["only_old"])
+ assert segs == ["Murtaza", "Bob"] and parts == "Bob, Murtaza"
+ assert label_map == {"SPEAKER_00": "Murtaza", "SPEAKER_01": "Bob"}
+ segs, parts, _ = _speakers(world["both"])
+ assert segs == ["Murtaza", "Murtaza"] and parts == "Murtaza" # no duplicate
+ assert db.session.get(TranscriptChunk, world["chunk"]).speaker_name == "Murtaza"
+ assert _speakers(world["untouched"])[:2] == (["Bob"], "Bob")
+ assert _speakers(world["theirs"])[:2] == (["Murtaza Nasir"], "Murtaza Nasir") # another user
+ assert db.session.get(Speaker, world["old"]) is None
+ changed = sorted([world["only_old"], world["both"]])
+ assert sorted(c.args[0] for c in m_reindex.call_args_list) == changed
+ assert sorted(c.args[0] for c in m_export.call_args_list) == changed
+
+
+def test_a_merge_preview_changes_nothing(world):
+ resp = _client(world["me"]).post("/speakers/merge", json={"target_id": world["keep"],
+ "source_ids": [world["old"]], "preview": True})
+ assert resp.status_code == 200
+ with app.app_context():
+ assert _speakers(world["only_old"])[0] == ["Murtaza Nasir", "Bob"]
+
+
+def test_a_rename_reaches_every_recording_and_rebuilds_their_chunks(world):
+ reindex, flag, export = _effects()
+ with reindex as m_reindex, flag, export:
+ resp = _client(world["me"]).put(f"/speakers/{world['old']}", json={"name": "M. Nasir"})
+ assert resp.status_code == 200 and resp.get_json()["recordings_updated"] == 2
+ with app.app_context():
+ assert _speakers(world["only_old"])[0] == ["M. Nasir", "Bob"]
+ assert _speakers(world["both"])[0] == ["M. Nasir", "Murtaza"]
+ assert _speakers(world["theirs"])[0] == ["Murtaza Nasir"]
+ assert sorted(c.args[0] for c in m_reindex.call_args_list) == sorted([world["only_old"], world["both"]])