Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Speakers: email and aliases, real speaker ids per recording, working rename in API v1 (mailr spec G6)
Murtaza Nasir1b138e228643
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex e6034c01..3eef39d7 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -1096,6 +1096,8 @@ GET /api/v1/speakers**Scope:** `read`+`?email=` returns the speaker with that address (any case).+**Response:**```json@@ -1107,12 +1109,17 @@ GET /api/v1/speakers"use_count": 45,"last_used": "2024-01-15T14:30:00Z","confidence_score": 0.87,- "has_voice_profile": true+ "has_voice_profile": true,+ "email": "[email protected]",+ "aliases": ["Johnny"],+ "updated_at": "2024-01-15T14:30:00.000000Z"}]}```+`email` and `aliases` are contact details you give your speakers. Only you see them: they are not part of shared recordings, public shares, exports or webhooks, and they are deleted with the speaker.+### Create Speaker```http@@ -1125,10 +1132,14 @@ POST /api/v1/speakers```json{- "name": "Jane Smith"+ "name": "Jane Smith",+ "email": "[email protected]",+ "aliases": ["J. Smith"]}```+`email` and `aliases` are optional.+### Update Speaker```http@@ -1137,13 +1148,15 @@ PUT /api/v1/speakers/{id}**Scope:** `write`-Updates the speaker name and cascades changes to all recordings.+Changes the name, email or aliases; send only what changes. A new name appears in every recording the speaker is in (transcript, participants, search). `email` must be an address (stored in lower case); `null` or `""` removes it. `aliases`: at most 20 names of at most 100 characters, trimmed, duplicates (any case) dropped; `[]` removes them. A name another of your speakers has gives `409`.**Request Body:**```json{- "name": "Jane Doe"+ "name": "Jane Doe",+ "email": "[email protected]",+ "aliases": ["J. Doe"]}```@@ -1163,7 +1176,7 @@ GET /api/v1/recordings/{id}/speakers**Scope:** `read`-Returns speakers in the recording with voice-based identification suggestions.+Returns the people in the recording with voice-based identification suggestions. Each entry is one person: the diarization `label`, the name given to it (`null` while unnamed), the saved speaker it is linked to, and `email` when you own both the recording and the speaker (`null` for anyone else).**Response:**@@ -1174,6 +1187,7 @@ Returns speakers in the recording with voice-based identification suggestions."label": "SPEAKER_00","identified_name": "John Doe","speaker_id": 1,+ "email": "[email protected]","segment_count": 23}],diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 2cc42b11..f47d0e03 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -2609,28 +2609,74 @@ def get_transcription_info():@require_scope('read')@login_requireddef list_speakers():- """List all speakers for the current user."""- speakers = Speaker.query.filter_by(user_id=current_user.id)\- .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\- .all()+ """List all speakers for the current user. ?email= filters by address."""+ query = Speaker.query.filter_by(user_id=current_user.id)+ email = (request.args.get('email') or '').strip().lower()+ if email:+ query = query.filter(db.func.lower(Speaker.email) == email)+ speakers = query.order_by(Speaker.use_count.desc(), Speaker.last_used.desc()).all()+ return jsonify({'speakers': [_speaker_item(s) for s in speakers]})- return jsonify({- 'speakers': [{- 'id': s.id,- 'name': s.name,- 'use_count': s.use_count,- 'last_used': s.last_used.isoformat() if s.last_used else None,- 'confidence_score': s.confidence_score,- 'has_voice_profile': s.average_embedding is not None- } for s in speakers]- })++_EMAIL = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')+++def _speaker_item(s):+ try:+ aliases = json.loads(s.aliases) if s.aliases else []+ except (TypeError, ValueError):+ aliases = []+ changed = s.updated_at or s.created_at+ return {+ 'id': s.id,+ 'name': s.name,+ 'use_count': s.use_count,+ 'last_used': s.last_used.isoformat() if s.last_used else None,+ 'confidence_score': s.confidence_score,+ 'has_voice_profile': s.average_embedding is not None,+ 'email': s.email,+ 'aliases': aliases if isinstance(aliases, list) else [],+ 'updated_at': changed.strftime('%Y-%m-%dT%H:%M:%S.%fZ') if changed else None,+ }+++def _speaker_contact_fields(data, speaker):+ """Apply email and aliases from a request body; returns an error message or None."""+ if 'email' in data:+ email = data['email']+ if email is None or (isinstance(email, str) and not email.strip()):+ speaker.email = None+ elif isinstance(email, str) and len(email.strip()) <= 320 and _EMAIL.match(email.strip()):+ speaker.email = email.strip().lower()+ else:+ return 'email must be an email address'+ if 'aliases' in data:+ aliases = data['aliases']+ if aliases is None:+ aliases = []+ if not isinstance(aliases, list) or not all(isinstance(a, str) for a in aliases):+ return 'aliases must be a list of strings'+ clean, seen = [], set()+ for alias in aliases:+ alias = alias.strip()+ if not alias:+ continue+ if len(alias) > 100:+ return 'each alias must be at most 100 characters'+ if alias.lower() not in seen:+ seen.add(alias.lower())+ clean.append(alias)+ if len(clean) > 20:+ return 'at most 20 aliases'+ speaker.aliases = json.dumps(clean) if clean else None+ return None@api_v1_bp.route('/speakers', methods=['POST'])@require_scope('write')@login_requireddef create_speaker():- """Create a new speaker."""+ """Create a new speaker (name, optional email and aliases)."""data = request.get_json()if not data or not data.get('name'):return jsonify({'error': 'Speaker name is required'}), 400@@ -2648,22 +2694,23 @@ def create_speaker():use_count=0,created_at=datetime.utcnow())+ problem = _speaker_contact_fields(data, speaker)+ if problem:+ return jsonify({'error': problem, 'code': 'invalid_parameter'}), 400db.session.add(speaker)db.session.commit()- return jsonify({- 'id': speaker.id,- 'name': speaker.name,- 'use_count': speaker.use_count,- 'created_at': speaker.created_at.isoformat()- }), 201+ item = _speaker_item(speaker)+ item['created_at'] = speaker.created_at.isoformat()+ return jsonify(item), 201@api_v1_bp.route('/speakers/<int:speaker_id>', methods=['PUT'])@require_scope('write')@login_requireddef update_speaker(speaker_id):- """Update a speaker (cascades name changes to recordings)."""+ """Update a speaker's name, email or aliases. A new name reaches every+ recording the speaker appears in, as in Speaker Management."""speaker = db.session.get(Speaker, speaker_id)if not speaker:return jsonify({'error': 'Speaker not found'}), 404@@ -2675,33 +2722,36 @@ def update_speaker(speaker_id):if not data:return jsonify({'error': 'No data provided'}), 400- old_name = speaker.name- new_name = data.get('name', '').strip()-- if not new_name:- return jsonify({'error': 'Speaker name is required'}), 400-- if new_name != old_name:- # Update speaker name- speaker.name = new_name+ problem = _speaker_contact_fields(data, speaker)+ if problem:+ db.session.rollback()+ return jsonify({'error': problem, 'code': 'invalid_parameter'}), 400- # Update all recordings that have this speaker in their transcription- from src.services.speaker import update_speaker_in_recordings- try:- update_speaker_in_recordings(current_user.id, old_name, new_name)- except Exception as e:- current_app.logger.error(f"Error updating speaker in recordings: {e}")+ renamed = {}+ if 'name' in data:+ new_name = (data.get('name') or '').strip()+ if not new_name:+ db.session.rollback()+ return jsonify({'error': 'Speaker name cannot be empty', 'code': 'invalid_parameter'}), 400+ if new_name != speaker.name:+ clash = Speaker.query.filter_by(user_id=current_user.id, name=new_name).first()+ if clash and clash.id != speaker.id:+ db.session.rollback()+ return jsonify({'error': f'A speaker named "{new_name}" already exists', 'code': 'conflict'}), 409+ from src.services.speaker_merge import rename_speaker_in_recordings+ old_name = speaker.name+ speaker.name = new_name+ _, renamed = rename_speaker_in_recordings(current_user.id, old_name, new_name,+ speaker_id=speaker.id, new_speaker_id=speaker.id)+ elif not any(k in data for k in ('email', 'aliases')):+ return jsonify({'error': 'Nothing to change: give name, email or aliases', 'code': 'invalid_parameter'}), 400db.session.commit()+ if renamed:+ from src.services.speaker_merge import refresh_renamed_recordings+ refresh_renamed_recordings(renamed)- return jsonify({- 'success': True,- 'speaker': {- 'id': speaker.id,- 'name': speaker.name,- 'use_count': speaker.use_count- }- })+ return jsonify({'success': True, 'speaker': _speaker_item(speaker)})@api_v1_bp.route('/speakers/<int:speaker_id>', methods=['DELETE'])@@ -2737,33 +2787,35 @@ def get_recording_speakers(recording_id):if not has_recording_access(recording, current_user):return jsonify({'error': 'Permission denied'}), 403- # Parse transcription to get speakers+ # One entry per person in the transcript: the diarization label (when+ # known), the name it was given and the linked saved speaker. Email only+ # for the speaker's owner (mailr spec G6).+ from src.services.transcript_segments import canonical_segmentsspeakers_in_recording = []- speaker_counts = {}-- if recording.transcription:- try:- segments = json.loads(recording.transcription)- for seg in segments:- speaker = seg.get('speaker', 'Unknown')- speaker_counts[speaker] = speaker_counts.get(speaker, 0) + 1- except (json.JSONDecodeError, TypeError):- pass-- # Build speaker list with identification info- for label, count in speaker_counts.items():- # Check if this speaker label has been identified- identified_name = None- speaker_id = None-- # Look for speaker in user's speakers by checking recordings- # This is a simplified check - actual implementation would check speaker_embeddings- speakers_in_recording.append({- 'label': label,- 'identified_name': identified_name,- 'speaker_id': speaker_id,- 'segment_count': count- })+ entries = {}+ is_owner = recording.user_id == current_user.id+ owned = {}+ for seg in canonical_segments(recording) or []:+ named = seg['speaker'] if seg['speaker'] and seg['speaker'] != seg['speaker_label'] else None+ key = seg['speaker_id'] or seg['speaker_label'] or seg['speaker'] or 'Unknown'+ entry = entries.get(key)+ if entry is None:+ entry = entries[key] = {+ 'label': seg['speaker_label'] or seg['speaker'] or 'Unknown',+ 'identified_name': named,+ 'speaker_id': seg['speaker_id'],+ 'email': None,+ 'segment_count': 0,+ }+ speakers_in_recording.append(entry)+ entry['segment_count'] += 1+ if is_owner:+ ids = [e['speaker_id'] for e in speakers_in_recording if e['speaker_id']]+ if ids:+ owned = {sp.id: sp for sp in Speaker.query.filter(Speaker.id.in_(ids), Speaker.user_id == current_user.id)}+ for entry in speakers_in_recording:+ if entry['speaker_id'] in owned:+ entry['email'] = owned[entry['speaker_id']].email# Get voice-based suggestions. speaker_embeddings maps each SPEAKER_XX# label to one embedding (any dimension); find_matching_speakers takes adiff --git a/src/init_db.py b/src/init_db.pyindex 1dab554b..c8c7c61c 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -258,6 +258,14 @@ def _run_migrations(app, engine):run_once(engine, '0002_backfill_recording_updated_at', _backfill_recording_updated_at,logger=app.logger)+ # Speaker contact details (mailr spec G6).+ if add_column_if_not_exists(engine, 'speaker', 'email', 'VARCHAR(320)'):+ app.logger.info("Added email column to speaker table")+ if add_column_if_not_exists(engine, 'speaker', 'aliases', 'TEXT'):+ app.logger.info("Added aliases column to speaker table")+ if add_column_if_not_exists(engine, 'speaker', 'updated_at', 'DATETIME'):+ app.logger.info("Added updated_at column to speaker table")+ create_index_if_not_exists(engine, 'ix_speaker_user_email', 'speaker', 'user_id, email')# Idempotent API uploads (mailr spec G8).if add_column_if_not_exists(engine, 'recording', 'upload_idempotency_key', 'VARCHAR(100)'):app.logger.info("Added upload_idempotency_key column to recording table")diff --git a/src/models/user.py b/src/models/user.pyindex 39c7d930..ae38529c 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -157,6 +157,11 @@ class Speaker(db.Model):embeddings_history = db.Column(db.JSON, nullable=True) # List of metadata: [{recording_id, timestamp, similarity}, ...]embedding_count = db.Column(db.Integer, default=0) # Number of embeddings collectedconfidence_score = db.Column(db.Float, nullable=True) # 0-1 score based on embedding consistency+ # Contact details the owner gives a speaker (mailr spec G6). Personal data+ # of a third party: shown to the speaker's owner only.+ email = db.Column(db.String(320), nullable=True)+ aliases = db.Column(db.Text, nullable=True) # JSON list of other names+ updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.utcnow)# Relationship to useruser = db.relationship('User', backref=db.backref('speakers', lazy=True, cascade='all, delete-orphan'))diff --git a/tests/test_api_v1_speaker_contacts.py b/tests/test_api_v1_speaker_contacts.pynew file mode 100644index 00000000..24c44a40--- /dev/null+++ b/tests/test_api_v1_speaker_contacts.py@@ -0,0 +1,116 @@+"""Speaker email and aliases, and real speaker ids per recording (mailr spec G6).++SHARED-DB: users, tokens, shares, speakers and recordings are removed afterwards.+"""++import json+import os+import secrets+import sys+from unittest.mock import 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, InternalShare, Recording, Speaker, User+from src.utils.token_auth import hash_token+++def world():+ with app.app_context():+ s = secrets.token_hex(4)+ owner = User(username=f"spc_{s}", email=f"spc_{s}@local.test", password="x")+ guest = User(username=f"spcg_{s}", email=f"spcg_{s}@local.test", password="x")+ db.session.add_all([owner, guest])+ db.session.commit()+ dana = Speaker(name="Dana", user_id=owner.id)+ db.session.add(dana)+ db.session.commit()+ rec = Recording(user_id=owner.id, title="Sync", status="COMPLETED", original_filename="s.wav",+ speaker_label_map={"SPEAKER_00": "Dana"},+ transcription=json.dumps([+ {"speaker": "Dana", "sentence": "Budget.", "start_time": 0.0, "end_time": 2.0},+ {"speaker": "SPEAKER_01", "sentence": "Yes.", "start_time": 2.0, "end_time": 3.0},+ {"speaker": "Dana", "sentence": "Good.", "start_time": 3.0, "end_time": 4.0}]))+ db.session.add(rec)+ db.session.commit()+ db.session.add(InternalShare(recording_id=rec.id, owner_id=owner.id, shared_with_user_id=guest.id))+ tokens = {}+ for who in (owner, guest):+ p = f"tok-{secrets.token_urlsafe(16)}"+ db.session.add(APIToken(user_id=who.id, token_hash=hash_token(p), name="spc"))+ tokens[who.id] = p+ db.session.commit()+ ids = dict(owner=owner.id, guest=guest.id, dana=dana.id, rec=rec.id, tokens=tokens)+ with patch("src.app.ENABLE_INTERNAL_SHARING", True):+ yield ids+ with app.app_context():+ db.session.rollback()+ InternalShare.query.filter_by(recording_id=ids["rec"]).delete()+ Recording.query.filter_by(id=ids["rec"]).delete()+ Speaker.query.filter(Speaker.user_id.in_([ids["owner"], ids["guest"]])).delete(synchronize_session=False)+ APIToken.query.filter(APIToken.user_id.in_([ids["owner"], ids["guest"]])).delete(synchronize_session=False)+ User.query.filter(User.id.in_([ids["owner"], ids["guest"]])).delete(synchronize_session=False)+ db.session.commit()+++def _call(world, method, path, who="owner", **kw):+ with app.test_client() as c:+ return getattr(c, method)(path, headers={"Authorization": f"Bearer {world['tokens'][world[who]]}"}, **kw)+++def test_set_read_filter_and_clear_email(world):+ put = _call(world, "put", f"/api/v1/speakers/{world['dana']}", json={"email": "[email protected]"})+ assert put.status_code == 200 and put.get_json()["speaker"]["email"] == "[email protected]"+ assert put.get_json()["speaker"]["name"] == "Dana" # no name needed+ listed = _call(world, "get", "/api/v1/[email protected]").get_json()["speakers"]+ assert [s["id"] for s in listed] == [world["dana"]] and listed[0]["updated_at"].endswith("Z")+ assert _call(world, "get", "/api/v1/[email protected]").get_json()["speakers"] == []+ cleared = _call(world, "put", f"/api/v1/speakers/{world['dana']}", json={"email": ""})+ assert cleared.get_json()["speaker"]["email"] is None++[email protected]("body", [{"email": "not-an-address"}, {"aliases": ["x" * 101]},+ {"aliases": [f"a{i}" for i in range(21)]}, {"aliases": "Dana L"}, {}])+def test_invalid_contact_fields(world, body):+ resp = _call(world, "put", f"/api/v1/speakers/{world['dana']}", json=body or {"other": 1})+ assert resp.status_code == 400+ with app.app_context():+ assert db.session.get(Speaker, world["dana"]).email is None+++def test_aliases_are_trimmed_and_deduplicated(world):+ resp = _call(world, "put", f"/api/v1/speakers/{world['dana']}", json={"aliases": [" Dana L ", "dana l", "D. Lee", ""]})+ assert resp.get_json()["speaker"]["aliases"] == ["Dana L", "D. Lee"]+ created = _call(world, "post", "/api/v1/speakers", json={"name": "Omar", "email": "[email protected]",+ "aliases": ["O."]})+ assert created.status_code == 201 and created.get_json()["email"] == "[email protected]"+++def test_another_users_speaker_is_refused(world):+ assert _call(world, "put", f"/api/v1/speakers/{world['dana']}", who="guest",+ json={"email": "[email protected]"}).status_code == 403+++def test_a_rename_through_the_api_reaches_the_recordings(world):+ with patch("src.api.recordings.reindex_recording_chunks_async"), patch("src.file_exporter.export_recording"):+ resp = _call(world, "put", f"/api/v1/speakers/{world['dana']}", json={"name": "Dana Lee"})+ assert resp.status_code == 200+ with app.app_context():+ segs = json.loads(db.session.get(Recording, world["rec"]).transcription)+ assert [s["speaker"] for s in segs] == ["Dana Lee", "SPEAKER_01", "Dana Lee"]+++def test_recording_speakers_report_ids_and_email_to_the_owner_only(world):+ _call(world, "put", f"/api/v1/speakers/{world['dana']}", json={"email": "[email protected]"})+ owner_view = _call(world, "get", f"/api/v1/recordings/{world['rec']}/speakers").get_json()["speakers"]+ assert owner_view == [+ {"label": "SPEAKER_00", "identified_name": "Dana", "speaker_id": world["dana"], "email": "[email protected]",+ "segment_count": 2},+ {"label": "SPEAKER_01", "identified_name": None, "speaker_id": None, "email": None, "segment_count": 1},+ ]+ guest_view = _call(world, "get", f"/api/v1/recordings/{world['rec']}/speakers", who="guest").get_json()["speakers"]+ assert guest_view[0]["speaker_id"] == world["dana"] and guest_view[0]["email"] is Nonediff --git a/tests/test_upgrade_mailr_api.py b/tests/test_upgrade_mailr_api.pyindex 1cd8b8be..0fdf61ef 100644--- a/tests/test_upgrade_mailr_api.py+++ b/tests/test_upgrade_mailr_api.py@@ -155,3 +155,23 @@ def test_upload_idempotency_and_external_refs(tmp_path, fixture):assert {"recording_id", "user_id", "system", "kind", "ref", "url", "label"} <= _columns(con, "recording_external_ref")con.close()+[email protected]("fixture", FIXTURES, ids=[f[:-4] for f in FIXTURES])+def test_speaker_contact_columns(tmp_path, fixture):+ """G6: email, aliases and updated_at arrive empty; names stay."""+ db_path, con = _load(tmp_path, fixture)+ if "speaker" not in {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}:+ con.close()+ pytest.skip("speaker table not in this release")+ con.execute('INSERT INTO "user" (id, username, email, password) VALUES (1, ?, ?, ?)', ("u", "[email protected]", "hash"))+ con.execute("INSERT INTO speaker (id, name, user_id) VALUES (4, 'Dana', 1)")+ con.commit()+ con.close()+ _upgrade(db_path)+ _upgrade(db_path)+ con = sqlite3.connect(db_path)+ assert {"email", "aliases", "updated_at"} <= _columns(con, "speaker")+ assert "ix_speaker_user_email" in {r[1] for r in con.execute("PRAGMA index_list('speaker')")}+ assert con.execute("SELECT name, email, aliases FROM speaker WHERE id = 4").fetchone() == ("Dana", None, None)+ con.close()+