Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Transcripts: one JSON shape in API v1 (mailr spec G12) and segments linked to saved speakers
Murtaza Nasirf8096985add9
diff --git a/docs/features.md b/docs/features.mdindex 6b2a638a..3a1602e1 100644--- a/docs/features.md+++ b/docs/features.md@@ -133,6 +133,8 @@ Implement intelligent data lifecycle management with flexible retention policiesBuild and maintain a library of speaker profiles that persist across recordings. [Identify speakers](user-guide/transcripts.md#speaker-identification) after each transcription to build your library. Once identified, speakers are remembered and suggested in future recordings. The system tracks usage statistics, showing how often each speaker appears and when they were last identified. Bulk management tools help maintain a clean, organized speaker library.+**Renaming and merging**: Each named speaker in a transcript is linked to the saved speaker. Renaming a speaker in **Account, Speakers Management** shows the new name in every recording that speaker appears in, and merging speakers shows the kept speaker in every recording of the merged ones: transcript, participants and Inquire search. Summaries keep the names they were written with until they are regenerated. Recordings transcribed before v0.10.11-alpha are linked once at upgrade, through voice samples where they exist and otherwise by name.+**Voice Profile Recognition**: A person's voice profile is built from samples: each time you name someone in a recording, Speakr keeps that recording's voice embedding for them (up to 20 per person, oldest dropped first). Embeddings of any size work; WhisperX returns 256 dimensions. Samples that closely resemble each other form a voice variant, so the same person on a phone and in a meeting room can have two, and a new recording is compared with every variant, the closest one counting. The variants are always rebuilt from the samples, which makes corrections complete: renaming a speaker moves their sample to the right person, and removing a sample in **Account, Speakers Management, Voice profile** undoes its effect entirely.Several safeguards keep profiles clean. A speaker with less than 15 seconds of speech in a recording (`VOICE_PROFILE_MIN_SPEECH_SECONDS`) neither trains a profile nor gets auto-labelled, since such a short stretch gives a noisy embedding. A sample that is unlike everything a well-established profile already holds is kept out and logged as a likely wrong name. Samples from auto-labelling count half as much as names a person confirmed, and confirming the name in the speaker dialog upgrades them. Profiles built before this design are kept and read as one sample, weighted by how many recordings built them.diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex b8b7b2ee..e6034c01 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -674,14 +674,22 @@ GET /api/v1/recordings/{id}/transcript| Parameter | Type | Default | Description ||-----------|------|---------|-------------|| `format` | string | `json` | Output format: `json`, `text`, `srt`, `vtt` |+| `start`, `end` | number | - | JSON only: segments that overlap this window, in seconds |+| `max_segments` | integer | - | JSON only: at most this many segments; `next_start` gives the start time of the next one |=== "JSON Format"```json{"format": "json",+ "kind": "segments",+ "duration": 1834.2,"segments": [{+ "index": 0,"speaker": "Alice",+ "speaker_label": "SPEAKER_00",+ "speaker_id": 12,+ "text": "Hello everyone","sentence": "Hello everyone","start_time": 0.0,"end_time": 2.5@@ -690,6 +698,8 @@ GET /api/v1/recordings/{id}/transcript}```+ Every segment has every key above, whatever format the transcript was saved in; clients can rely on this shape. `text` and `sentence` are the same (`sentence` is kept for older clients). Times are seconds or `null`. `speaker_label` is the diarization label (also after the speaker was named), or `null` when it is not known. `speaker_id` is the id of the saved speaker the segment is linked to, else `null`; for a linked segment, `speaker` is that speaker's current name. A transcript without speaker segments returns `"kind": "plain"`, an empty `segments` list and the text in `raw`.+=== "Text Format"Uses your default transcript template:```jsondiff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 6281dbf1..2cc42b11 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -1602,18 +1602,27 @@ def get_transcript(recording_id):format_type = request.args.get('format', 'json').lower()if format_type == 'json':+ # One documented shape whatever key set the transcript was stored+ # with (mailr spec G12); optional window: start, end, max_segments.+ from src.services.transcript_segments import canonical_segments, window+ segments = canonical_segments(recording)+ if segments is None:+ return jsonify({'format': 'json', 'kind': 'plain', 'segments': [], 'raw': recording.transcription})try:- segments = json.loads(recording.transcription)- return jsonify({- 'format': 'json',- 'segments': segments- })- except json.JSONDecodeError:- return jsonify({- 'format': 'json',- 'segments': [],- 'raw': recording.transcription- })+ start = request.args.get('start', type=float)+ end = request.args.get('end', type=float)+ max_segments = request.args.get('max_segments', type=int)+ except ValueError:+ start = end = max_segments = None+ if max_segments is not None and max_segments < 1:+ return jsonify({'error': 'max_segments must be at least 1', 'code': 'invalid_parameter'}), 400+ body = {'format': 'json', 'kind': 'segments', 'duration': recording.get_audio_duration()}+ if start is not None or end is not None or max_segments is not None:+ segments, next_start = window(segments, start, end, max_segments)+ if next_start is not None:+ body['next_start'] = next_start+ body['segments'] = segments+ return jsonify(body)elif format_type == 'text':# Use user's default template for text formatdiff --git a/src/api/recordings.py b/src/api/recordings.pyindex 51cd7df3..6deec1fd 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -987,14 +987,17 @@ def update_transcript(recording_id):seconds_by_key = speech_seconds_by_label(transcript_data)speaker_names_used, label_to_name = apply_speaker_map(transcript_data, speaker_map, current_user)+ # Saved speakers first (update_speaker_usage commits on its own), so+ # the segments link to them in the same commit as the names.+ if speaker_names_used:+ update_speaker_usage(speaker_names_used)+ from src.services.speaker_links import link_list+ link_list(transcript_data, recording)+# Save the updated transcriptrecording.transcription = json.dumps(transcript_data)recording.participants = participants_from_segments(transcript_data)- # Update speaker usage statistics- if speaker_names_used:- update_speaker_usage(speaker_names_used)-update_voice_profiles(recording, label_to_name, current_user, seconds_by_key)db.session.commit()diff --git a/src/api/speakers.py b/src/api/speakers.pyindex 613c384f..29dc9400 100644--- a/src/api/speakers.py+++ b/src/api/speakers.py@@ -170,7 +170,8 @@ def update_speaker(speaker_id):# Cascade the new name to every recording of this userfrom 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)+ chunks_updated, renamed = rename_speaker_in_recordings(current_user.id, old_name, new_name,+ speaker_id=speaker.id, new_speaker_id=speaker.id)recordings_updated = len(renamed)db.session.commit()diff --git a/src/init_db.py b/src/init_db.pyindex b05f5195..1dab554b 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -1110,6 +1110,16 @@ def _run_migrations(app, engine):db.session.rollback()app.logger.warning(f"transcription_language normalization migration skipped: {e}")+ # Link named transcript segments to saved speakers (speaker_id), once.+ # Voice samples help where they exist; the name match covers the rest.+ try:+ from src.services.speaker_links import backfill_all+ run_once(engine, '0003_link_transcript_speakers',+ lambda eng: backfill_all(eng, logger=app.logger), logger=app.logger)+ except Exception as e:+ db.session.rollback()+ app.logger.warning(f"Transcript speaker linking skipped, retried next start: {e}")+with _migration_section(app, failures, "inquire mode chunk backfill"):# Process existing recordings for inquire mode (chunk and embed them)# Only run if inquire mode is enableddiff --git a/src/services/speaker_assignment.py b/src/services/speaker_assignment.pyindex 805eb01f..67167d8f 100644--- a/src/services/speaker_assignment.py+++ b/src/services/speaker_assignment.py@@ -38,6 +38,13 @@ def apply_speaker_names(recording, user, speaker_map, regenerate_summary=False):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)+ # Saved speakers first (update_speaker_usage commits on its own), so+ # the segments can link to them in the same commit as the names.+ if names_used:+ update_speaker_usage(names_used)+ names_used = []+ from src.services.speaker_links import link_list+ link_list(transcription_data, recording)recording.transcription = json.dumps(transcription_data)recording.participants = participants_from_segments(transcription_data)else:diff --git a/src/services/speaker_links.py b/src/services/speaker_links.pynew file mode 100644index 00000000..788019ee--- /dev/null+++ b/src/services/speaker_links.py@@ -0,0 +1,149 @@+"""Links from transcript segments to saved speakers (speaker_id).++Each named segment of a JSON transcript stores speaker_id next to the+speaker name: the id of one of the recording owner's saved speakers. The name+stays as the display copy, so everything that reads names keeps working; a+rename or merge follows the id, and the API reports the speaker's current+name. A segment whose name matches no saved speaker, and a diarization label+(SPEAKER_00), has no id.++The id is found from, in order: the id the segment already has (when it+still belongs to the owner and its name matches), the voice sample saved for+that diarization label of this recording, and a saved speaker of the same+name (ignoring case). Voice samples are optional: without voice embeddings+the name match links every named speaker.+"""++import json+import re++from src.database import db++LABEL = re.compile(r'^SPEAKER_\d+$', re.IGNORECASE)+++def owner_speakers(user_id):+ """({lowercased name: Speaker}, {id: Speaker}) for one user."""+ from src.models import Speaker+ by_name, by_id = {}, {}+ for speaker in Speaker.query.filter_by(user_id=user_id).order_by(Speaker.id):+ by_id[speaker.id] = speaker+ by_name.setdefault((speaker.name or '').strip().lower(), speaker)+ return by_name, by_id+++def _sample_speakers(recording):+ """{diarization label: speaker id} from the voice samples of the recording."""+ from src.models import SpeakerVoiceSample+ result = {}+ for label, speaker_id in (db.session.query(SpeakerVoiceSample.label, SpeakerVoiceSample.speaker_id)+ .filter(SpeakerVoiceSample.recording_id == recording.id,+ SpeakerVoiceSample.label.isnot(None))):+ result.setdefault(label, speaker_id)+ return result+++def _labels_by_name(recording):+ """{lowercased name: [labels]} from the recording's label map."""+ result = {}+ for label, name in (recording.speaker_label_map or {}).items():+ if isinstance(name, str):+ result.setdefault(name.strip().lower(), []).append(label)+ return result+++def resolve_id(name, current_id, by_name, by_id, samples, labels_by_name):+ """The speaker id for one segment name, or None."""+ if not isinstance(name, str) or not name.strip() or LABEL.match(name.strip()):+ return None+ key = name.strip().lower()+ if current_id in by_id and (by_id[current_id].name or '').strip().lower() == key:+ return current_id+ for label in labels_by_name.get(key, []):+ sid = samples.get(label)+ if sid in by_id and (by_id[sid].name or '').strip().lower() == key:+ return sid+ speaker = by_name.get(key)+ return speaker.id if speaker else None+++def link_list(segments, recording, speakers=None):+ """Set speaker_id on a list of segment dicts in place (a save that is about+ to store them). Returns True when anything changed."""+ if recording.user_id is None or not isinstance(segments, list):+ return False+ by_name, by_id = speakers or owner_speakers(recording.user_id)+ samples = _sample_speakers(recording)+ labels_by_name = _labels_by_name(recording)+ changed = False+ for seg in segments:+ if not isinstance(seg, dict):+ continue+ sid = resolve_id(seg.get('speaker'), seg.get('speaker_id'), by_name, by_id, samples, labels_by_name)+ if sid is None:+ if 'speaker_id' in seg:+ del seg['speaker_id']+ changed = True+ elif seg.get('speaker_id') != sid:+ seg['speaker_id'] = sid+ changed = True+ return changed+++def link_segments(recording, speakers=None):+ """Set speaker_id on every segment of the recording's JSON transcript.++ Returns the new transcription text when anything changed, else None. Does+ not assign it: the caller decides how to write it.+ """+ if not recording.transcription or recording.user_id is None:+ return None+ try:+ segments = json.loads(recording.transcription)+ except (TypeError, ValueError):+ return None+ if not isinstance(segments, list):+ return None+ return json.dumps(segments) if link_list(segments, recording, speakers) else None+++def link_recording(recording):+ """link_segments and assign the result (an ORM change; no commit)."""+ text = link_segments(recording)+ if text is not None:+ recording.transcription = text+++def backfill_all(engine, logger=None, batch=200):+ """Link every stored JSON transcript, once (run_once 0003).++ Writes with plain UPDATE statements: adding the ids is not a change of+ the recording a client should be told about, so it does not move+ updated_at or send webhooks.+ """+ from sqlalchemy import text+ from src.models import Recording+ speakers_cache = {}+ linked = 0+ last_id = 0+ while True:+ rows = (Recording.query.filter(Recording.id > last_id, Recording.transcription.isnot(None))+ .order_by(Recording.id).limit(batch).all())+ if not rows:+ break+ updates = []+ for rec in rows:+ last_id = rec.id+ if rec.user_id not in speakers_cache:+ speakers_cache[rec.user_id] = owner_speakers(rec.user_id)+ new_text = link_segments(rec, speakers_cache[rec.user_id])+ if new_text is not None:+ updates.append({'id': rec.id, 't': new_text})+ db.session.rollback() # nothing above is meant to be flushed+ if updates:+ with engine.begin() as conn:+ conn.execute(text('UPDATE recording SET transcription = :t WHERE id = :id'), updates)+ linked += len(updates)+ if logger:+ logger.info(f"Linked transcript speakers to saved speakers in {linked} recording(s)")+ return linkeddiff --git a/src/services/speaker_merge.py b/src/services/speaker_merge.pyindex 3c8e13f1..78958d82 100644--- a/src/services/speaker_merge.py+++ b/src/services/speaker_merge.py@@ -106,7 +106,8 @@ def merge_speakers(target_id, source_ids, user_id):# recordings of a merged speaker kept showing the old name.renamed = {}for source in sources:- _, changed = rename_speaker_in_recordings(user_id, source.name, target.name)+ _, changed = rename_speaker_in_recordings(user_id, source.name, target.name,+ speaker_id=source.id, new_speaker_id=target.id)for rid, fields in changed.items():renamed.setdefault(rid, set()).update(fields)target.recordings_updated = len(renamed) # for the route's answer, not a column@@ -126,12 +127,14 @@ 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):+def rename_speaker_in_recordings(user_id, old_name, new_name, speaker_id=None, new_speaker_id=None):"""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.+ label map and the Inquire chunks' speaker column. A segment linked to+ speaker_id follows the link (and is linked to new_speaker_id); a segment+ without a link matches by name, ignoring case and surrounding spaces, as+ saved speakers do. Does not commit.Returns (chunks_updated, {recording id: set of the fields changed})."""from src.models import Recording, TranscriptChunk@@ -167,9 +170,17 @@ def rename_speaker_in_recordings(user_id, old_name, new_name):if isinstance(segments, list):hit = Falsefor segment in segments:- if isinstance(segment, dict) and _same_name(segment.get('speaker'), old_name):- segment['speaker'] = new_name- hit = True+ if not isinstance(segment, dict):+ continue+ linked = segment.get('speaker_id')+ if (speaker_id is not None and linked == speaker_id) or \+ (linked is None and _same_name(segment.get('speaker'), old_name)):+ if segment.get('speaker') != new_name:+ segment['speaker'] = new_name+ hit = True+ if new_speaker_id is not None and linked != new_speaker_id:+ segment['speaker_id'] = new_speaker_id+ hit = Trueif hit:recording.transcription = json.dumps(segments)fields.add('transcription')diff --git a/src/services/transcript_segments.py b/src/services/transcript_segments.pyindex a50f111c..eb6cb17a 100644--- a/src/services/transcript_segments.py+++ b/src/services/transcript_segments.py@@ -10,10 +10,22 @@ import jsondef _number(value):+ """Seconds as a float from a number, a numeric string or "[hh:]mm:ss[.f]"."""+ if value is None or isinstance(value, bool):+ return Nonetry:- return None if value is None else float(value)+ return float(value)except (TypeError, ValueError):- return None+ pass+ if isinstance(value, str) and ':' in value:+ try:+ seconds = 0.0+ for part in value.strip().split(':'):+ seconds = seconds * 60 + float(part)+ return seconds+ except ValueError:+ return None+ return Nonedef segments_of(transcription):@@ -42,3 +54,72 @@ def segments_of(transcription):'end_time': _number(seg.get('end_time', seg.get('end'))),})return segments+++def canonical_segments(recording):+ """The documented API shape of a JSON transcript (mailr spec G12), or None+ for a plain-text transcript.++ Every segment has index, speaker, speaker_label, speaker_id, text,+ sentence, start_time and end_time. speaker is the linked saved speaker's+ current name when the segment is linked; speaker_label is the+ diarization label, recovered from the label map after a rename.+ """+ from src.services.speaker_links import (LABEL, _labels_by_name, _sample_speakers, owner_speakers,+ resolve_id)+ import json as _json+ segments = segments_of(recording.transcription)+ if segments is None:+ return None+ try:+ raw = [s for s in _json.loads(recording.transcription) if isinstance(s, dict)]+ except (TypeError, ValueError):+ raw = []+ by_name, by_id = owner_speakers(recording.user_id) if recording.user_id else ({}, {})+ samples = _sample_speakers(recording)+ labels_by_name = _labels_by_name(recording)+ label_of_speaker = {}+ for label, sid in samples.items():+ label_of_speaker.setdefault(sid, label)+ result = []+ for seg, stored in zip(segments, raw):+ name = seg['speaker']+ name_text = name.strip() if isinstance(name, str) else None+ stored_id = stored.get('speaker_id')+ # A valid stored link wins: the name in the segment may be an older+ # spelling of the same person.+ sid = stored_id if stored_id in by_id else resolve_id(name, None, by_name, by_id, samples, labels_by_name)+ if name_text and LABEL.match(name_text):+ label = name_text+ else:+ labels = labels_by_name.get((name_text or '').lower(), [])+ label = labels[0] if labels else label_of_speaker.get(sid)+ result.append({+ 'index': seg['index'],+ 'speaker': by_id[sid].name if sid in by_id else name,+ 'speaker_label': label,+ 'speaker_id': sid,+ 'text': seg['text'],+ 'sentence': seg['text'],+ 'start_time': seg['start_time'],+ 'end_time': seg['end_time'],+ })+ return result+++def window(segments, start=None, end=None, max_segments=None):+ """Segments overlapping [start, end] seconds, at most max_segments.+ Returns (segments, next_start or None)."""+ picked = []+ for seg in segments:+ s_time = seg['start_time']+ e_time = seg['end_time'] if seg['end_time'] is not None else s_time+ if start is not None and (e_time is None or e_time < start):+ continue+ if end is not None and (s_time is None or s_time > end):+ continue+ picked.append(seg)+ if max_segments is not None and len(picked) > max_segments:+ following = picked[max_segments]+ return picked[:max_segments], following['start_time']+ return picked, Nonediff --git a/tests/test_transcript_shape_and_links.py b/tests/test_transcript_shape_and_links.pynew file mode 100644index 00000000..751526e2--- /dev/null+++ b/tests/test_transcript_shape_and_links.py@@ -0,0 +1,183 @@+"""One transcript JSON shape and speaker links (mailr spec G12; speaker ids).++GET /transcript?format=json returns every segment with index, speaker,+speaker_label, speaker_id, text, sentence, start_time and end_time, whatever+key set the transcript was stored with. Named segments store speaker_id, so a+rename or merge follows the saved speaker, and the API shows its current name.++SHARED-DB: the user, token, speakers and recordings are removed afterwards.+"""++import json+import os+import secrets+import sys+from datetime import datetime+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, Speaker, User+from src.utils.token_auth import hash_token++app.config["WTF_CSRF_ENABLED"] = False+KEYS = {"index", "speaker", "speaker_label", "speaker_id", "text", "sentence", "start_time", "end_time"}+++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():+ s = secrets.token_hex(4)+ u = User(username=f"ts_{s}", email=f"ts_{s}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ dana = Speaker(name="Dana", user_id=u.id)+ omar = Speaker(name="Omar Haddad", user_id=u.id)+ db.session.add_all([dana, omar])+ db.session.commit()+ new = Recording(user_id=u.id, title="New keys", status="COMPLETED", original_filename="a.wav",+ speaker_label_map={"SPEAKER_00": "Dana", "SPEAKER_01": "Omar Haddad"},+ transcription=json.dumps([+ {"speaker": "Dana", "sentence": "Budget first.", "start_time": 0.0, "end_time": 3.4},+ {"speaker": "omar haddad", "sentence": "Agreed.", "start_time": 3.4, "end_time": None},+ {"speaker": "SPEAKER_02", "sentence": "Who am I?", "start_time": 5.0, "end_time": 6.0},+ {"speaker": "Visitor", "sentence": "Hello.", "start_time": 7.0, "end_time": 8.0}]))+ old = Recording(user_id=u.id, title="Old keys", status="COMPLETED", original_filename="b.wav",+ transcription=json.dumps([+ {"speaker": "Dana", "text": "Old style.", "start": "00:12.5", "end": "0:15"},+ {"speaker": "Dana", "text": "Second.", "start": 20, "end": 22.5}]))+ plain = Recording(user_id=u.id, title="Plain", status="COMPLETED", original_filename="c.wav",+ transcription="Just text, no segments.")+ plain_token = f"tok-{secrets.token_urlsafe(16)}"+ db.session.add_all([new, old, plain, APIToken(user_id=u.id, token_hash=hash_token(plain_token), name="ts")])+ db.session.commit()+ ids = dict(user=u.id, dana=dana.id, omar=omar.id, new=new.id, old=old.id, plain=plain.id, token=plain_token)+ yield ids+ with app.app_context():+ db.session.rollback()+ Recording.query.filter_by(user_id=ids["user"]).delete()+ Speaker.query.filter_by(user_id=ids["user"]).delete()+ APIToken.query.filter_by(user_id=ids["user"]).delete()+ User.query.filter_by(id=ids["user"]).delete()+ db.session.commit()+++def _transcript(world, rid, query=""):+ with app.test_client() as c:+ resp = c.get(f"/api/v1/recordings/{rid}/transcript?format=json{query}",+ headers={"Authorization": f"Bearer {world['token']}"})+ assert resp.status_code == 200, resp.get_json()+ return resp.get_json()+++def test_every_segment_has_every_key(world):+ for rid in (world["new"], world["old"]):+ body = _transcript(world, rid)+ assert body["kind"] == "segments"+ for seg in body["segments"]:+ assert set(seg) == KEYS+ assert seg["text"] == seg["sentence"] and isinstance(seg["index"], int)+ assert seg["start_time"] is None or isinstance(seg["start_time"], float)+++def test_values_are_normalised(world):+ new = _transcript(world, world["new"])["segments"]+ assert [(s["speaker"], s["speaker_id"], s["speaker_label"]) for s in new] == [+ ("Dana", world["dana"], "SPEAKER_00"),+ ("Omar Haddad", world["omar"], "SPEAKER_01"), # current name, any case in the transcript+ ("SPEAKER_02", None, "SPEAKER_02"),+ ("Visitor", None, None),+ ]+ assert new[1]["end_time"] is None+ old = _transcript(world, world["old"])["segments"]+ assert [(s["text"], s["start_time"], s["end_time"]) for s in old] == [("Old style.", 12.5, 15.0), ("Second.", 20.0, 22.5)]+++def test_plain_text(world):+ body = _transcript(world, world["plain"])+ assert body["kind"] == "plain" and body["segments"] == [] and body["raw"] == "Just text, no segments."+++def test_window(world):+ body = _transcript(world, world["new"], "&start=3&end=6")+ assert [s["index"] for s in body["segments"]] == [0, 1, 2]+ capped = _transcript(world, world["new"], "&start=0&max_segments=2")+ assert [s["index"] for s in capped["segments"]] == [0, 1] and capped["next_start"] == 5.0+ assert "next_start" not in _transcript(world, world["new"], "&max_segments=10")+++# ------------------------------------------------------------ links++def _stored(rid):+ with app.app_context():+ return json.loads(db.session.get(Recording, rid).transcription)+++def test_the_backfill_links_names_without_moving_updated_at(world):+ from src.services.speaker_links import backfill_all+ with app.app_context():+ r = db.session.get(Recording, world["new"])+ r.updated_at = datetime(2020, 1, 1)+ db.session.commit()+ backfill_all(db.engine)+ segs = _stored(world["new"])+ assert [s.get("speaker_id") for s in segs] == [world["dana"], world["omar"], None, None]+ with app.app_context():+ assert db.session.get(Recording, world["new"]).updated_at == datetime(2020, 1, 1)+++def test_saving_names_links_them(world):+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(world["user"])+ with patch("src.api.recordings.reindex_recording_chunks_async"), patch("src.file_exporter.export_recording"), \+ patch("src.services.speaker.update_voice_profiles", return_value=(0, 0)):+ resp = c.post(f"/recording/{world['new']}/update_speakers",+ json={"speaker_map": {"SPEAKER_02": {"name": "Visitor", "isMe": False}}})+ assert resp.status_code == 200+ with app.app_context():+ visitor = Speaker.query.filter_by(user_id=world["user"], name="Visitor").one()+ assert [s.get("speaker_id") for s in _stored(world["new"])][2:] == [visitor.id, visitor.id]+++def test_a_rename_follows_the_link_even_when_the_name_drifted(world):+ from src.services.speaker_links import backfill_all+ with app.app_context():+ backfill_all(db.engine)+ r = db.session.get(Recording, world["new"])+ segs = json.loads(r.transcription)+ segs[0]["speaker"] = "Dana L." # an old spelling, still linked+ r.transcription = json.dumps(segs)+ db.session.commit()+ assert _transcript(world, world["new"])["segments"][0]["speaker"] == "Dana" # linked: current name+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(world["user"])+ with patch("src.api.recordings.reindex_recording_chunks_async"), patch("src.file_exporter.export_recording"):+ assert c.put(f"/speakers/{world['dana']}", json={"name": "Dana Lee"}).status_code == 200+ segs = _stored(world["new"])+ assert (segs[0]["speaker"], segs[0]["speaker_id"]) == ("Dana Lee", world["dana"])+ assert _stored(world["old"])[0]["speaker"] == "Dana Lee" # unlinked: matched by name+++def test_a_merge_moves_the_links(world):+ from src.services.speaker_links import backfill_all+ from src.services.speaker_merge import merge_speakers+ with app.app_context():+ backfill_all(db.engine)+ with patch("src.api.recordings.reindex_recording_chunks_async"), patch("src.file_exporter.export_recording"):+ merge_speakers(world["dana"], [world["omar"]], world["user"])+ segs = _stored(world["new"])+ assert [(s["speaker"], s.get("speaker_id")) for s in segs[:2]] == [("Dana", world["dana"]), ("Dana", world["dana"])]diff --git a/tests/test_upgrade_mailr_api.py b/tests/test_upgrade_mailr_api.pyindex 57bc3a07..1cd8b8be 100644--- a/tests/test_upgrade_mailr_api.py+++ b/tests/test_upgrade_mailr_api.py@@ -107,6 +107,10 @@ def test_recording_updated_at_and_tombstones(tmp_path, fixture):assert {"ix_recording_updated_at", "ix_recording_user_updated"} <= indexesassert "recording_tombstone" in tablesassert ledger == 1 and since and since[0].endswith("Z")+ con = sqlite3.connect(db_path)+ assert con.execute("SELECT count(*) FROM schema_migrations "+ "WHERE migration_id = '0003_link_transcript_speakers'").fetchone()[0] == 1+ con.close()@pytest.mark.parametrize("fixture", FIXTURES, ids=[f[:-4] for f in FIXTURES])