Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add speaker API endpoints, extract shared identification service, fix null transcription bug
Murtaza Nasir341f6e04e020
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex eec0c835..81272efe 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -14,6 +14,7 @@ All endpoints require token authentication via:"""import os+import reimport jsonfrom datetime import datetime, date, timedeltafrom typing import Optional@@ -236,6 +237,24 @@ OPENAPI_SPEC = {"/recordings/{id}/speakers": {"get": {"tags": ["Speakers"], "summary": "Get speakers in recording", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Speakers with suggestions"}}}},+ "/recordings/{id}/speakers/assign": {+ "put": {+ "tags": ["Speakers"],+ "summary": "Assign speaker names to transcription",+ "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],+ "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["speaker_map"], "properties": {"speaker_map": {"type": "object", "description": "Map of speaker labels to names. Values can be: string (name) or object {name, isMe}."}, "regenerate_summary": {"type": "boolean", "default": False}}}}}},+ "responses": {"200": {"description": "Speakers assigned"}, "404": {"description": "Recording not found"}, "403": {"description": "Permission denied"}}+ }+ },+ "/recordings/{id}/speakers/identify": {+ "post": {+ "tags": ["Speakers"],+ "summary": "Auto-identify speakers via LLM",+ "description": "Analyzes transcript context to suggest speaker names. Returns suggestions only - does not modify the recording.",+ "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],+ "responses": {"200": {"description": "Speaker identification suggestions"}, "400": {"description": "Transcription not available or unsupported format"}}+ }+ },"/recordings/batch": {"patch": {"tags": ["Batch"], "summary": "Batch update recordings", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["recording_ids", "updates"], "properties": {"recording_ids": {"type": "array", "items": {"type": "integer"}}, "updates": {"type": "object"}}}}}}, "responses": {"200": {"description": "Batch results"}}},"delete": {"tags": ["Batch"], "summary": "Batch delete recordings", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["recording_ids"], "properties": {"recording_ids": {"type": "array", "items": {"type": "integer"}}}}}}}, "responses": {"200": {"description": "Batch results"}}}@@ -286,6 +305,15 @@ OPENAPI_SPEC = {"/speakers/{id}": {"put": {"tags": ["Speakers"], "summary": "Update speaker", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string"}}}}}}, "responses": {"200": {"description": "Speaker updated"}}},"delete": {"tags": ["Speakers"], "summary": "Delete speaker", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Speaker deleted"}}}+ },+ "/settings/auto-summarization": {+ "put": {+ "tags": ["Settings"],+ "summary": "Toggle auto-summarization",+ "description": "Enable or disable auto-summarization for the current user.",+ "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["enabled"], "properties": {"enabled": {"type": "boolean"}}}}}},+ "responses": {"200": {"description": "Setting updated"}}+ }}},"tags": [@@ -297,7 +325,8 @@ OPENAPI_SPEC = {{"name": "Audio", "description": "Audio file operations"},{"name": "Tags", "description": "Tag management"},{"name": "Speakers", "description": "Speaker management"},- {"name": "Batch", "description": "Batch operations"}+ {"name": "Batch", "description": "Batch operations"},+ {"name": "Settings", "description": "User settings"}]}@@ -1526,6 +1555,227 @@ def get_recording_speakers(recording_id):})+@api_v1_bp.route('/recordings/<int:recording_id>/speakers/assign', methods=['PUT'])+@login_required+def assign_speakers(recording_id):+ """+ Assign speaker names to a recording's transcription segments.++ Accepts the same speaker_map format as the web UI, plus convenience+ formats for API callers (plain strings).++ Request body:+ {+ "speaker_map": {+ "SPEAKER_00": "Jane Doe", // string shorthand+ "SPEAKER_01": {"name": "Bob", "isMe": false} // full object+ },+ "regenerate_summary": false+ }+ """+ from src.services.speaker import update_speaker_usage+ from src.services.speaker_embedding_matcher import update_speaker_embedding+ from src.services.speaker_snippets import create_speaker_snippets+ from src.services.job_queue import job_queue++ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ if not has_recording_access(recording, current_user, require_edit=True):+ return jsonify({'error': 'Permission denied'}), 403++ data = request.get_json()+ if not data or 'speaker_map' not in data:+ return jsonify({'error': 'speaker_map is required'}), 400++ raw_speaker_map = data['speaker_map']+ regenerate_summary = data.get('regenerate_summary', False)++ if not isinstance(raw_speaker_map, dict):+ return jsonify({'error': 'speaker_map must be an object'}), 400++ # Normalize values to {name, isMe} format (same as web UI expects)+ speaker_map = {}+ for label, value in raw_speaker_map.items():+ if isinstance(value, str):+ speaker_map[label] = {'name': value.strip(), 'isMe': False}+ elif isinstance(value, dict):+ speaker_map[label] = {+ 'name': value.get('name', '').strip() if value.get('name') else '',+ 'isMe': value.get('isMe', False)+ }+ else:+ return jsonify({'error': f'Invalid value type for speaker "{label}"'}), 400++ # --- Apply names to transcription (same logic as update_speakers in recordings.py) ---+ transcription_text = recording.transcription or ''+ is_json = False+ try:+ transcription_data = json.loads(transcription_text)+ is_json = isinstance(transcription_data, list)+ except (json.JSONDecodeError, TypeError):+ is_json = False++ speaker_names_used = []++ if is_json:+ for segment in transcription_data:+ original_speaker_label = segment.get('speaker')+ if original_speaker_label in speaker_map:+ new_name_info = speaker_map[original_speaker_label]+ 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:+ segment['speaker'] = new_name+ if new_name not in speaker_names_used:+ speaker_names_used.append(new_name)++ recording.transcription = json.dumps(transcription_data)++ # Update participants - exclude unresolved SPEAKER_XX labels+ final_speakers = set()+ for seg in transcription_data:+ speaker = seg.get('speaker')+ if speaker and str(speaker).strip():+ if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):+ final_speakers.add(speaker)+ recording.participants = ', '.join(sorted(list(final_speakers)))+ 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)+ speaker_names_used = new_participants++ # Update speaker usage statistics+ if speaker_names_used:+ update_speaker_usage(speaker_names_used)++ # Update speaker voice embeddings if available+ embeddings_updated = 0+ snippets_created = 0+ if recording.speaker_embeddings and speaker_map:+ try:+ embeddings_data = json.loads(recording.speaker_embeddings) if isinstance(recording.speaker_embeddings, str) else recording.speaker_embeddings++ speaker_label_to_name = {}+ for speaker_label, speaker_info in speaker_map.items():+ name = speaker_info.get('name', '').strip()+ if speaker_info.get('isMe') and not name:+ name = current_user.name or 'Me'+ if name and not re.match(r'^SPEAKER_\d+$', name, re.IGNORECASE):+ speaker_label_to_name[speaker_label] = name++ for speaker_label, embedding in embeddings_data.items():+ if speaker_label in speaker_label_to_name and embedding and len(embedding) == 256:+ speaker_name = speaker_label_to_name[speaker_label]+ speaker_obj = Speaker.query.filter_by(+ user_id=current_user.id,+ name=speaker_name+ ).first()+ if speaker_obj:+ update_speaker_embedding(speaker_obj, embedding, recording.id)+ embeddings_updated += 1++ if speaker_label_to_name:+ snippets_created = create_speaker_snippets(recording.id, speaker_map)+ except Exception as e:+ current_app.logger.error(f"Error updating speaker embeddings: {e}", exc_info=True)++ 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++ return jsonify({+ 'success': True,+ 'message': 'Speakers updated successfully.',+ 'recording': {+ 'id': recording.id,+ 'title': recording.title,+ 'participants': recording.participants,+ 'status': recording.status+ },+ 'summary_queued': summary_queued,+ 'embeddings_updated': embeddings_updated,+ 'snippets_created': snippets_created+ })++ except Exception as e:+ db.session.rollback()+ current_app.logger.error(f"Error assigning speakers for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': str(e)}), 500+++@api_v1_bp.route('/recordings/<int:recording_id>/speakers/identify', methods=['POST'])+@login_required+def identify_speakers(recording_id):+ """+ Trigger LLM-based auto-identification of speakers from transcript context.+ Returns suggestions only - does not modify the recording.++ Uses the shared identification service with JSON schema support,+ name sanitization, and fallback logic.+ """+ from src.services.speaker_identification import identify_speakers_from_transcript++ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ if not has_recording_access(recording, current_user):+ return jsonify({'error': 'Permission denied'}), 403++ if not recording.transcription:+ return jsonify({'error': 'No transcription available for speaker identification'}), 400++ try:+ transcription_data = json.loads(recording.transcription)+ except (json.JSONDecodeError, TypeError):+ return jsonify({'error': 'Transcription format not supported for auto-identification'}), 400++ if not isinstance(transcription_data, list):+ return jsonify({'error': 'Transcription format not supported for auto-identification'}), 400++ speaker_map = identify_speakers_from_transcript(transcription_data, current_user.id)++ if not speaker_map:+ return jsonify({'error': 'No speakers found in transcription'}), 400++ return jsonify({'success': True, 'speaker_map': speaker_map})++ except ValueError as ve:+ return jsonify({'error': str(ve)}), 503+ except Exception as e:+ current_app.logger.error(f"Error during auto speaker identification for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500++# =============================================================================# Processing Operations# =============================================================================@@ -1621,7 +1871,7 @@ def chat_with_recording(recording_id):"""Chat about a recording's content."""from src.services.llm import chat_client, call_chat_completionfrom src.tasks.processing import format_transcription_for_llm- from src.models.system_settings import SystemSetting+ from src.models import SystemSettingrecording = db.session.get(Recording, recording_id)if not recording:@@ -1964,6 +2214,31 @@ def batch_transcribe_recordings():})+# =============================================================================+# Settings+# =============================================================================++@api_v1_bp.route('/settings/auto-summarization', methods=['PUT'])+@login_required+def update_auto_summarization():+ """Toggle auto-summarization for the current user."""+ data = request.get_json()++ if data is None:+ return jsonify({'error': 'Invalid JSON'}), 400++ if 'enabled' not in data:+ return jsonify({'error': 'enabled field is required'}), 400++ current_user.auto_summarization = bool(data['enabled'])+ db.session.commit()++ return jsonify({+ 'success': True,+ 'auto_summarization': current_user.auto_summarization+ })++@api_v1_bp.route('/recordings/upload', methods=['POST'])@login_requireddef upload_recording():diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 9d0d53fa..7691bf55 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -879,6 +879,8 @@ def auto_identify_speakers(recording_id):Automatically identifies speakers in a transcription using an LLM.Strips existing names and re-identifies all speakers from scratch."""+ from src.services.speaker_identification import identify_speakers_from_transcript+try:recording = db.session.get(Recording, recording_id)if not recording:@@ -890,7 +892,6 @@ def auto_identify_speakers(recording_id):if not recording.transcription:return jsonify({'error': 'No transcription available for speaker identification'}), 400- # Parse the transcriptiontry:transcription_data = json.loads(recording.transcription)except (json.JSONDecodeError, TypeError):@@ -899,214 +900,14 @@ def auto_identify_speakers(recording_id):if not isinstance(transcription_data, list):return jsonify({'error': 'Transcription format not supported for auto-identification'}), 400- # Extract unique speakers in order of appearance- seen_speakers = set()- unique_speakers = []- for segment in transcription_data:- speaker = segment.get('speaker')- if speaker and speaker not in seen_speakers:- seen_speakers.add(speaker)- unique_speakers.append(speaker)-- if not unique_speakers:- return jsonify({'error': 'No speakers found in transcription'}), 400+ speaker_map = identify_speakers_from_transcript(transcription_data, current_user.id)- # Create a mapping from current names to SPEAKER_XX labels- speaker_to_label = {}- for idx, speaker in enumerate(unique_speakers):- speaker_to_label[speaker] = f'SPEAKER_{str(idx).zfill(2)}'-- # Create a temporary transcript with SPEAKER_XX labels- temp_transcript = []- for segment in transcription_data:- temp_segment = segment.copy()- original_speaker = segment.get('speaker')- if original_speaker:- temp_segment['speaker'] = speaker_to_label[original_speaker]- temp_transcript.append(temp_segment)-- # Format for LLM directly (don't pass JSON, pass formatted text)- formatted_lines = []- for segment in temp_transcript:- speaker = segment.get('speaker', 'Unknown Speaker')- sentence = segment.get('sentence', '')- formatted_lines.append(f"[{speaker}]: {sentence}")- formatted_transcription = "\n".join(formatted_lines)-- # Get all SPEAKER_XX labels- speaker_labels = list(speaker_to_label.values())-- current_app.logger.info(f"[Auto-Identify] Formatted transcript (first 500 chars): {formatted_transcription[:500]}")- current_app.logger.info(f"[Auto-Identify] Speaker labels: {speaker_labels}")-- # Call identify_unidentified_speakers_from_text but pass the formatted text directly- # We need to bypass format_transcription_for_llm since we already formatted it- if not speaker_labels:+ if not speaker_map:return jsonify({'error': 'No speakers found in transcription'}), 400- # Get configurable transcript length limit- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)- if transcript_limit == -1:- transcript_text = formatted_transcription- else:- transcript_text = formatted_transcription[:transcript_limit]-- prompt = f"""Analyze the following conversation transcript and identify the names of the speakers based on the context and content of their dialogue.--The speakers that need to be identified are: {', '.join(speaker_labels)}--Look for clues in the conversation such as:-- Names mentioned by other speakers when addressing someone-- Self-introductions or references to their own name-- Context clues about roles, relationships, or positions-- Any direct mentions of names in the dialogue--Here is the complete conversation transcript:--{transcript_text}--Based on the conversation above, identify the most likely real names for the speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.--Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined from the conversation context, use an empty string "".--Example format:-{{- "SPEAKER_01": "Jane Smith",- "SPEAKER_03": "Bob Johnson",- "SPEAKER_05": ""-}}--JSON Response:-"""-- try:- from src.services.llm import call_llm_completion- current_app.logger.info(f"[Auto-Identify] Calling LLM directly with prompt")-- use_schema = os.environ.get('AUTO_IDENTIFY_RESPONSE_SCHEMA', '').strip() in ('1', 'true', 'yes')- system_msg = "You are an expert in analyzing conversation transcripts to identify speakers based on contextual clues in the dialogue. Analyze the conversation carefully to find names mentioned when speakers address each other or introduce themselves. Your response must be a single, valid JSON object containing only the requested speaker identifications."-- response_content = None- if use_schema:- # Build JSON schema response format with constrained keys- schema_properties = {label: {"type": "string"} for label in speaker_labels}- schema_response_format = {- "type": "json_schema",- "json_schema": {- "name": "speaker_identification",- "strict": True,- "schema": {- "type": "object",- "properties": schema_properties,- "required": speaker_labels,- "additionalProperties": False- }- }- }- schema_prompt = prompt + f"\n\nIMPORTANT: Your JSON response must contain exactly these keys: {', '.join(speaker_labels)}"- try:- current_app.logger.info("[Auto-Identify] Trying json_schema response format")- completion = call_llm_completion(- messages=[- {"role": "system", "content": system_msg},- {"role": "user", "content": schema_prompt}- ],- temperature=0.2,- response_format=schema_response_format,- user_id=current_user.id,- operation_type='speaker_identification'- )- response_content = completion.choices[0].message.content- current_app.logger.info(f"[Auto-Identify] LLM Raw Response (schema mode): {response_content}")- except Exception as schema_err:- current_app.logger.warning(f"[Auto-Identify] json_schema mode failed, falling back to json_object: {schema_err}")- response_content = None-- if response_content is None:- completion = call_llm_completion(- messages=[- {"role": "system", "content": system_msg},- {"role": "user", "content": prompt}- ],- temperature=0.2,- response_format={"type": "json_object"},- user_id=current_user.id,- operation_type='speaker_identification'- )- response_content = completion.choices[0].message.content- current_app.logger.info(f"[Auto-Identify] LLM Raw Response: {response_content}")-- from src.utils import safe_json_loads- identified_map = safe_json_loads(response_content, {})- current_app.logger.info(f"[Auto-Identify] Parsed identified_map: {identified_map}")-- # --- Sanitize identified_map ---- speaker_label_re = re.compile(r'^SPEAKER_\d{2}$')-- # Detect inverted map ({name: "SPEAKER_XX"}) and flip it- if identified_map and all(- speaker_label_re.match(str(v)) for v in identified_map.values() if v- ) and not any(speaker_label_re.match(str(k)) for k in identified_map.keys()):- current_app.logger.warning("[Auto-Identify] Detected inverted map, flipping keys/values")- identified_map = {v: k for k, v in identified_map.items() if v}-- sanitized = {}- for speaker_label, identified_name in identified_map.items():- # Skip entries whose key isn't a valid SPEAKER_XX label- if not speaker_label_re.match(str(speaker_label)):- continue- if not identified_name or not isinstance(identified_name, str):- sanitized[speaker_label] = ""- continue-- name = identified_name.strip()-- # Clear generic placeholders- if name.lower() in ["unknown", "n/a", "not available", "unclear", "unidentified", ""]:- sanitized[speaker_label] = ""- continue-- # Clear label-to-label entries (e.g. "SPEAKER_01": "SPEAKER_02")- if speaker_label_re.match(name):- sanitized[speaker_label] = ""- continue-- # Strip parenthetical content: "John (the host)" → "John"- name = re.sub(r'\s*\([^)]*\)', '', name).strip()-- # Take first name segment before comma, semicolon, or slash- name = re.split(r'[,;/]', name)[0].strip()-- # Collapse whitespace- name = re.sub(r'\s+', ' ', name)-- # Final check: if result still matches SPEAKER_XX, clear it- if speaker_label_re.match(name) or not name:- sanitized[speaker_label] = ""- continue-- sanitized[speaker_label] = name-- identified_map = sanitized- current_app.logger.info(f"[Auto-Identify] Sanitized identified_map: {identified_map}")- except Exception as e:- current_app.logger.error(f"[Auto-Identify] Error calling LLM: {e}", exc_info=True)- return jsonify({'error': f'Failed to identify speakers: {str(e)}'}), 500- current_app.logger.info(f"[Auto-Identify] LLM returned identified_map: {identified_map}")-- # Map back to original speaker IDs- final_speaker_map = {}- for original_speaker, temp_label in speaker_to_label.items():- if temp_label in identified_map:- final_speaker_map[original_speaker] = identified_map[temp_label]-- current_app.logger.info(f"[Auto-Identify] Final speaker_map to return: {final_speaker_map}")- current_app.logger.info(f"[Auto-Identify] Speaker mapping: {speaker_to_label}")-- return jsonify({'success': True, 'speaker_map': final_speaker_map})+ return jsonify({'success': True, 'speaker_map': speaker_map})except ValueError as ve:- # Handle cases where API key is not setreturn jsonify({'error': str(ve)}), 503except Exception as e:current_app.logger.error(f"Error during auto speaker identification for recording {recording_id}: {e}", exc_info=True)diff --git a/src/services/speaker_identification.py b/src/services/speaker_identification.pynew file mode 100644index 00000000..64092c6c--- /dev/null+++ b/src/services/speaker_identification.py@@ -0,0 +1,229 @@+"""+Shared speaker identification service.++Provides LLM-based speaker identification from transcript context,+used by both the web UI (recordings.py) and REST API (api_v1.py).+"""++import os+import re+import json+from flask import current_app+++def identify_speakers_from_transcript(transcription_data, user_id):+ """+ Identify speakers in a transcription using an LLM.++ Args:+ transcription_data: List of transcript segments (already parsed JSON).+ user_id: Current user's ID (for token tracking).++ Returns:+ dict mapping original speaker labels to identified names.+ Values are empty string "" for unidentified speakers.++ Raises:+ ValueError: If LLM API key is not configured.+ Exception: On LLM call failure.+ """+ from src.services.llm import call_llm_completion+ from src.utils import safe_json_loads+ from src.models import SystemSetting++ # Extract unique speakers in order of appearance+ seen_speakers = set()+ unique_speakers = []+ for segment in transcription_data:+ speaker = segment.get('speaker')+ if speaker and speaker not in seen_speakers:+ seen_speakers.add(speaker)+ unique_speakers.append(speaker)++ if not unique_speakers:+ return {}++ # Normalize all labels to SPEAKER_XX format for the LLM+ speaker_to_label = {}+ for idx, speaker in enumerate(unique_speakers):+ speaker_to_label[speaker] = f'SPEAKER_{str(idx).zfill(2)}'++ # Create temporary transcript with normalized labels+ formatted_lines = []+ for segment in transcription_data:+ original_speaker = segment.get('speaker')+ label = speaker_to_label.get(original_speaker, 'Unknown Speaker')+ sentence = segment.get('sentence', '')+ formatted_lines.append(f"[{label}]: {sentence}")+ formatted_transcription = "\n".join(formatted_lines)++ speaker_labels = list(speaker_to_label.values())++ current_app.logger.info(f"[Auto-Identify] Formatted transcript (first 500 chars): {formatted_transcription[:500]}")+ current_app.logger.info(f"[Auto-Identify] Speaker labels: {speaker_labels}")++ # Apply configurable transcript length limit+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if transcript_limit == -1:+ transcript_text = formatted_transcription+ else:+ transcript_text = formatted_transcription[:transcript_limit]++ prompt = f"""Analyze the following conversation transcript and identify the names of the speakers based on the context and content of their dialogue.++The speakers that need to be identified are: {', '.join(speaker_labels)}++Look for clues in the conversation such as:+- Names mentioned by other speakers when addressing someone+- Self-introductions or references to their own name+- Context clues about roles, relationships, or positions+- Any direct mentions of names in the dialogue++Here is the complete conversation transcript:++{transcript_text}++Based on the conversation above, identify the most likely real names for the speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.++Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined from the conversation context, use an empty string "".++Example format:+{{+ "SPEAKER_01": "Jane Smith",+ "SPEAKER_03": "Bob Johnson",+ "SPEAKER_05": ""+}}++JSON Response:+"""++ current_app.logger.info("[Auto-Identify] Calling LLM")++ use_schema = os.environ.get('AUTO_IDENTIFY_RESPONSE_SCHEMA', '').strip() in ('1', 'true', 'yes')+ system_msg = (+ "You are an expert in analyzing conversation transcripts to identify speakers "+ "based on contextual clues in the dialogue. Analyze the conversation carefully "+ "to find names mentioned when speakers address each other or introduce themselves. "+ "Your response must be a single, valid JSON object containing only the requested "+ "speaker identifications."+ )++ response_content = None+ if use_schema:+ # Build JSON schema response format with constrained keys+ schema_properties = {label: {"type": "string"} for label in speaker_labels}+ schema_response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "speaker_identification",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": schema_properties,+ "required": speaker_labels,+ "additionalProperties": False+ }+ }+ }+ schema_prompt = prompt + f"\n\nIMPORTANT: Your JSON response must contain exactly these keys: {', '.join(speaker_labels)}"+ try:+ current_app.logger.info("[Auto-Identify] Trying json_schema response format")+ completion = call_llm_completion(+ messages=[+ {"role": "system", "content": system_msg},+ {"role": "user", "content": schema_prompt}+ ],+ temperature=0.2,+ response_format=schema_response_format,+ user_id=user_id,+ operation_type='speaker_identification'+ )+ response_content = completion.choices[0].message.content+ current_app.logger.info(f"[Auto-Identify] LLM Raw Response (schema mode): {response_content}")+ except Exception as schema_err:+ current_app.logger.warning(f"[Auto-Identify] json_schema mode failed, falling back to json_object: {schema_err}")+ response_content = None++ if response_content is None:+ completion = call_llm_completion(+ messages=[+ {"role": "system", "content": system_msg},+ {"role": "user", "content": prompt}+ ],+ temperature=0.2,+ response_format={"type": "json_object"},+ user_id=user_id,+ operation_type='speaker_identification'+ )+ response_content = completion.choices[0].message.content+ current_app.logger.info(f"[Auto-Identify] LLM Raw Response: {response_content}")++ identified_map = safe_json_loads(response_content, {})+ current_app.logger.info(f"[Auto-Identify] Parsed identified_map: {identified_map}")++ # --- Sanitize identified_map ---+ identified_map = _sanitize_identified_map(identified_map, speaker_labels)+ current_app.logger.info(f"[Auto-Identify] Sanitized identified_map: {identified_map}")++ # Map back to original speaker labels+ final_speaker_map = {}+ for original_speaker, temp_label in speaker_to_label.items():+ if temp_label in identified_map:+ final_speaker_map[original_speaker] = identified_map[temp_label]++ current_app.logger.info(f"[Auto-Identify] Final speaker_map: {final_speaker_map}")+ return final_speaker_map+++def _sanitize_identified_map(identified_map, speaker_labels):+ """+ Clean up LLM output: handle inverted maps, strip commentary,+ clear placeholders, etc.+ """+ speaker_label_re = re.compile(r'^SPEAKER_\d{2}$')++ # Detect inverted map ({name: "SPEAKER_XX"}) and flip it+ if identified_map and all(+ speaker_label_re.match(str(v)) for v in identified_map.values() if v+ ) and not any(speaker_label_re.match(str(k)) for k in identified_map.keys()):+ current_app.logger.warning("[Auto-Identify] Detected inverted map, flipping keys/values")+ identified_map = {v: k for k, v in identified_map.items() if v}++ sanitized = {}+ for speaker_label, identified_name in identified_map.items():+ # Skip entries whose key isn't a valid SPEAKER_XX label+ if not speaker_label_re.match(str(speaker_label)):+ continue+ if not identified_name or not isinstance(identified_name, str):+ sanitized[speaker_label] = ""+ continue++ name = identified_name.strip()++ # Clear generic placeholders+ if name.lower() in ["unknown", "n/a", "not available", "unclear", "unidentified", ""]:+ sanitized[speaker_label] = ""+ continue++ # Clear label-to-label entries (e.g. "SPEAKER_01": "SPEAKER_02")+ if speaker_label_re.match(name):+ sanitized[speaker_label] = ""+ continue++ # Strip parenthetical content: "John (the host)" -> "John"+ name = re.sub(r'\s*\([^)]*\)', '', name).strip()++ # Take first name segment before comma, semicolon, or slash+ name = re.split(r'[,;/]', name)[0].strip()++ # Collapse whitespace+ name = re.sub(r'\s+', ' ', name)++ # Final check: if result still matches SPEAKER_XX, clear it+ if speaker_label_re.match(name) or not name:+ sanitized[speaker_label] = ""+ continue++ sanitized[speaker_label] = name++ return sanitizeddiff --git a/tests/test_api_v1_speakers.py b/tests/test_api_v1_speakers.pynew file mode 100644index 00000000..2b616c92--- /dev/null+++ b/tests/test_api_v1_speakers.py@@ -0,0 +1,971 @@+#!/usr/bin/env python3+"""+Test suite for Speaker API v1 endpoints.++Covers:+ - PUT /recordings/<id>/speakers/assign (17 tests)+ - POST /recordings/<id>/speakers/identify (10 tests)+ - PUT /settings/auto-summarization (5 tests)+ - Regression for GET /speakers and GET /recordings/<id>/speakers (2 tests)++Pattern follows tests/test_api_v1_upload.py — standalone, no pytest fixtures.+"""++import json+import secrets+import sys+import os+from unittest.mock import patch, MagicMock++# Add parent directory so we can import the app+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import User, APIToken, Recording, Speaker+from src.utils.token_auth import hash_token++# ---------------------------------------------------------------------------+# Test data constants+# ---------------------------------------------------------------------------++SAMPLE_TRANSCRIPTION_JSON = json.dumps([+ {"speaker": "SPEAKER_00", "sentence": "Hi, I'm Alice."},+ {"speaker": "SPEAKER_01", "sentence": "Hello Alice, I'm Bob."},+ {"speaker": "SPEAKER_00", "sentence": "Nice to meet you, Bob."},+])++SAMPLE_TRANSCRIPTION_TEXT = (+ "[SPEAKER_00]: Hi, I'm Alice.\n"+ "[SPEAKER_01]: Hello Alice, I'm Bob.\n"+ "[SPEAKER_00]: Nice to meet you, Bob."+)++SAMPLE_EMBEDDINGS = json.dumps({+ "SPEAKER_00": [0.1] * 256,+ "SPEAKER_01": [0.2] * 256,+})++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _get_or_create_test_user(suffix=""):+ """Get or create a test user. Returns (user, created_bool)."""+ username = f"speaker_test_user{suffix}"+ user = User.query.filter_by(username=username).first()+ created = False+ if not user:+ user = User(+ username=username,+ email=f"{username}@local.test",+ name="Test User" if not suffix else None,+ )+ db.session.add(user)+ db.session.commit()+ created = True+ return user, created+++def _create_api_token(user):+ """Create a fresh API token. Returns (token_record, plaintext)."""+ plaintext = f"test-token-{secrets.token_urlsafe(16)}"+ token = APIToken(+ user_id=user.id,+ token_hash=hash_token(plaintext),+ name="test-api-token",+ )+ db.session.add(token)+ db.session.commit()+ return token, plaintext+++def _create_test_recording(user, transcription=None, speaker_embeddings=None, status="COMPLETED"):+ """Create a Recording owned by *user*."""+ rec = Recording(+ user_id=user.id,+ title="Test Recording",+ status=status,+ transcription=transcription,+ speaker_embeddings=speaker_embeddings,+ )+ db.session.add(rec)+ db.session.commit()+ return rec+++def _create_test_speaker(user, name="Alice"):+ """Create a Speaker owned by *user*."""+ speaker = Speaker(name=name, user_id=user.id)+ db.session.add(speaker)+ db.session.commit()+ return speaker+++def _cleanup(*objects):+ """Delete DB objects in reverse order, committing once."""+ for obj in reversed(objects):+ try:+ db.session.delete(obj)+ except Exception:+ db.session.rollback()+ try:+ merged = db.session.merge(obj)+ db.session.delete(merged)+ except Exception:+ pass+ db.session.commit()+++# =========================================================================+# Group 1: PUT /recordings/<id>/speakers/assign (17 tests)+# =========================================================================+++def test_assign_no_auth():+ """No token -> 302 redirect (Flask-Login)."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ json={"speaker_map": {}})+ assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec)+ if cu:+ _cleanup(user)+++def test_assign_recording_not_found():+ """Nonexistent recording ID -> 404."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.put("/api/v1/recordings/999999/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {}})+ assert resp.status_code == 404, f"Expected 404, got {resp.status_code}"+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++def test_assign_wrong_user_recording():+ """Other user's recording -> 403."""+ with app.app_context():+ owner, co = _get_or_create_test_user("_owner")+ other, cu = _get_or_create_test_user("_other")+ token_rec, token = _create_api_token(other)+ rec = _create_test_recording(owner, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice"}})+ assert resp.status_code == 403, f"Expected 403, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(other)+ if co:+ _cleanup(owner)+++def test_assign_missing_speaker_map():+ """Body {} -> 400 'speaker_map is required'."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ body = resp.get_json()+ assert "speaker_map" in body.get("error", "").lower(), f"Unexpected error: {body}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_invalid_speaker_map_type():+ """speaker_map: 'string' -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": "not a dict"})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_string_value_json_transcript():+ """Happy path: string names update JSON segments + participants."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice", "SPEAKER_01": "Bob"}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("success") is True+ # Verify participants+ participants = body["recording"]["participants"]+ assert "Alice" in participants and "Bob" in participants+ # Verify transcription was updated+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "Alice"+ assert segments[1]["speaker"] == "Bob"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_object_value_with_name():+ """Happy path: {name, isMe} object format."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {+ "SPEAKER_00": {"name": "Alice", "isMe": False},+ }})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "Alice"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_is_me_flag_with_user_name():+ """isMe: true resolves to user.name."""+ with app.app_context():+ user, cu = _get_or_create_test_user() # user.name == "Test User"+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {+ "SPEAKER_00": {"name": "", "isMe": True},+ }})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "Test User", f"Got {segments[0]['speaker']}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_is_me_flag_without_user_name():+ """isMe: true falls back to 'Me' when user.name is None."""+ with app.app_context():+ user, cu = _get_or_create_test_user("_noname")+ # Ensure user.name is None+ user.name = None+ db.session.commit()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {+ "SPEAKER_00": {"name": "", "isMe": True},+ }})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "Me", f"Got {segments[0]['speaker']}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_plain_text_transcript():+ """Replaces [SPEAKER_XX] in plain text format."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_TEXT)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice", "SPEAKER_01": "Bob"}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ db.session.refresh(rec)+ assert "[Alice]" in rec.transcription+ assert "[Bob]" in rec.transcription+ assert "[SPEAKER_00]" not in rec.transcription+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_speaker_xx_filtered_from_participants():+ """Unresolved SPEAKER_XX labels excluded from participants."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ # Only assign one speaker - SPEAKER_01 stays unresolved+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice"}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ participants = body["recording"]["participants"]+ assert "SPEAKER_01" not in participants, f"SPEAKER_01 should be filtered: {participants}"+ assert "Alice" in participants+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_invalid_value_type():+ """Array value -> 400 'Invalid value type'."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": [1, 2, 3]}})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ body = resp.get_json()+ assert "invalid value type" in body.get("error", "").lower(), f"Unexpected: {body}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_empty_speaker_map():+ """Empty speaker_map {} -> 200 with no changes."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("success") is True+ # Transcription should be unchanged+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "SPEAKER_00"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_regenerate_summary():+ """regenerate_summary: true -> job_queue.enqueue called, summary_queued: true."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ mock_jq = MagicMock()+ mock_jq.enqueue = MagicMock(return_value="job-123")+ with patch("src.services.job_queue.job_queue", mock_jq):+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={+ "speaker_map": {"SPEAKER_00": "Alice"},+ "regenerate_summary": True,+ })+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("summary_queued") is True+ mock_jq.enqueue.assert_called_once()+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_embeddings_updated():+ """With speaker_embeddings -> update_speaker_embedding called, counts returned."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(+ user,+ transcription=SAMPLE_TRANSCRIPTION_JSON,+ speaker_embeddings=SAMPLE_EMBEDDINGS,+ )+ speaker = _create_test_speaker(user, "Alice")+ client = app.test_client()+ try:+ mock_update = MagicMock()+ mock_snippets = MagicMock(return_value=2)+ with patch("src.services.speaker_embedding_matcher.update_speaker_embedding", mock_update), \+ patch("src.services.speaker_snippets.create_speaker_snippets", mock_snippets):+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice"}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("embeddings_updated") >= 1, f"embeddings_updated: {body}"+ mock_update.assert_called()+ return True+ finally:+ _cleanup(rec, speaker, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_no_transcription():+ """Recording without transcription -> speakers applied to empty content gracefully."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=None)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": "Alice"}})+ # Should succeed (or at least not 500)+ assert resp.status_code in (200, 400), f"Expected 200/400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_assign_whitespace_name_trimmed():+ """Names with leading/trailing whitespace get trimmed."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",+ headers={"X-API-Token": token},+ json={"speaker_map": {"SPEAKER_00": " Alice "}})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ db.session.refresh(rec)+ segments = json.loads(rec.transcription)+ assert segments[0]["speaker"] == "Alice", f"Name not trimmed: '{segments[0]['speaker']}'"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++# =========================================================================+# Group 2: POST /recordings/<id>/speakers/identify (10 tests)+# =========================================================================+++def test_identify_no_auth():+ """No token -> 302."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify")+ assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec)+ if cu:+ _cleanup(user)+++def test_identify_recording_not_found():+ """Nonexistent ID -> 404."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.post("/api/v1/recordings/999999/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 404, f"Expected 404, got {resp.status_code}"+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++def test_identify_wrong_user_recording():+ """Other user's recording -> 403."""+ with app.app_context():+ owner, co = _get_or_create_test_user("_id_owner")+ other, cu = _get_or_create_test_user("_id_other")+ token_rec, token = _create_api_token(other)+ rec = _create_test_recording(owner, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 403, f"Expected 403, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(other)+ if co:+ _cleanup(owner)+++def test_identify_no_transcription():+ """No transcription -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=None)+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_non_json_transcription():+ """Plain text -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_TEXT)+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_json_but_not_list():+ """Dict JSON -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=json.dumps({"key": "value"}))+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_happy_path():+ """Mock LLM returns names -> 200 with speaker_map."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ # Build a mock LLM completion response+ mock_completion = MagicMock()+ mock_completion.choices = [MagicMock()]+ mock_completion.choices[0].message.content = json.dumps({+ "SPEAKER_00": "Alice",+ "SPEAKER_01": "Bob",+ })++ with patch("src.services.llm.call_llm_completion", return_value=mock_completion), \+ patch("src.models.system.SystemSetting") as mock_ss:+ mock_ss.get_setting.return_value = 30000+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})++ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("success") is True+ sm = body.get("speaker_map", {})+ assert sm.get("SPEAKER_00") == "Alice"+ assert sm.get("SPEAKER_01") == "Bob"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_post_processing_unknown_values():+ """'Unknown'/'N/A' cleared to ''."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ mock_completion = MagicMock()+ mock_completion.choices = [MagicMock()]+ mock_completion.choices[0].message.content = json.dumps({+ "SPEAKER_00": "Unknown",+ "SPEAKER_01": "N/A",+ })++ with patch("src.services.llm.call_llm_completion", return_value=mock_completion), \+ patch("src.models.system.SystemSetting") as mock_ss:+ mock_ss.get_setting.return_value = 30000+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})++ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ sm = body.get("speaker_map", {})+ assert sm.get("SPEAKER_00") == "", f"Expected empty, got {sm.get('SPEAKER_00')}"+ assert sm.get("SPEAKER_01") == "", f"Expected empty, got {sm.get('SPEAKER_01')}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_no_speakers_in_transcript():+ """Segments without speaker field -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ no_speakers = json.dumps([{"sentence": "Hello"}, {"sentence": "World"}])+ rec = _create_test_recording(user, transcription=no_speakers)+ client = app.test_client()+ try:+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_identify_llm_error():+ """LLM raises exception -> 500."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ with patch("src.services.llm.call_llm_completion",+ side_effect=RuntimeError("LLM down")), \+ patch("src.models.system.SystemSetting") as mock_ss:+ mock_ss.get_setting.return_value = 30000+ resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",+ headers={"X-API-Token": token})+ assert resp.status_code == 500, f"Expected 500, got {resp.status_code}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++# =========================================================================+# Group 3: PUT /settings/auto-summarization (5 tests)+# =========================================================================+++def test_auto_summarization_no_auth():+ """No token -> 302."""+ with app.app_context():+ client = app.test_client()+ resp = client.put("/api/v1/settings/auto-summarization",+ json={"enabled": True})+ assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"+ return True+++def test_auto_summarization_missing_enabled():+ """Body {} -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.put("/api/v1/settings/auto-summarization",+ headers={"X-API-Token": token},+ json={})+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ body = resp.get_json()+ assert "enabled" in body.get("error", "").lower(), f"Unexpected: {body}"+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++def test_auto_summarization_invalid_json():+ """Non-JSON body -> 400."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.put("/api/v1/settings/auto-summarization",+ headers={"X-API-Token": token,+ "Content-Type": "application/json"},+ data="not valid json")+ assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++def test_auto_summarization_enable():+ """enabled: true -> updates user, returns true."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ user.auto_summarization = False+ db.session.commit()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.put("/api/v1/settings/auto-summarization",+ headers={"X-API-Token": token},+ json={"enabled": True})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("auto_summarization") is True+ db.session.refresh(user)+ assert user.auto_summarization is True+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++def test_auto_summarization_disable():+ """enabled: false -> updates user, returns false."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ user.auto_summarization = True+ db.session.commit()+ token_rec, token = _create_api_token(user)+ client = app.test_client()+ try:+ resp = client.put("/api/v1/settings/auto-summarization",+ headers={"X-API-Token": token},+ json={"enabled": False})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ assert body.get("auto_summarization") is False+ db.session.refresh(user)+ assert user.auto_summarization is False+ return True+ finally:+ _cleanup(token_rec)+ if cu:+ _cleanup(user)+++# =========================================================================+# Group 4: Regression tests (2 tests)+# =========================================================================+++def test_regression_get_speakers_list():+ """GET /speakers still returns user's speakers."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ speaker = _create_test_speaker(user, "Regression Speaker")+ client = app.test_client()+ try:+ resp = client.get("/api/v1/speakers",+ headers={"X-API-Token": token})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ names = [s["name"] for s in body.get("speakers", [])]+ assert "Regression Speaker" in names, f"Speaker not found: {names}"+ return True+ finally:+ _cleanup(speaker, token_rec)+ if cu:+ _cleanup(user)+++def test_regression_get_recording_speakers():+ """GET /recordings/<id>/speakers still returns transcript speakers."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = _create_test_recording(user, transcription=SAMPLE_TRANSCRIPTION_JSON)+ client = app.test_client()+ try:+ with patch("src.services.speaker_embedding_matcher.find_matching_speakers", return_value={}):+ resp = client.get(f"/api/v1/recordings/{rec.id}/speakers",+ headers={"X-API-Token": token})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ body = resp.get_json()+ labels = [s["label"] for s in body.get("speakers", [])]+ assert "SPEAKER_00" in labels and "SPEAKER_01" in labels, f"Labels: {labels}"+ return True+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++# =========================================================================+# Runner+# =========================================================================++ALL_TESTS = [+ # Group 1: assign+ test_assign_no_auth,+ test_assign_recording_not_found,+ test_assign_wrong_user_recording,+ test_assign_missing_speaker_map,+ test_assign_invalid_speaker_map_type,+ test_assign_string_value_json_transcript,+ test_assign_object_value_with_name,+ test_assign_is_me_flag_with_user_name,+ test_assign_is_me_flag_without_user_name,+ test_assign_plain_text_transcript,+ test_assign_speaker_xx_filtered_from_participants,+ test_assign_invalid_value_type,+ test_assign_empty_speaker_map,+ test_assign_regenerate_summary,+ test_assign_embeddings_updated,+ test_assign_no_transcription,+ test_assign_whitespace_name_trimmed,+ # Group 2: identify+ test_identify_no_auth,+ test_identify_recording_not_found,+ test_identify_wrong_user_recording,+ test_identify_no_transcription,+ test_identify_non_json_transcription,+ test_identify_json_but_not_list,+ test_identify_happy_path,+ test_identify_post_processing_unknown_values,+ test_identify_no_speakers_in_transcript,+ test_identify_llm_error,+ # Group 3: auto-summarization+ test_auto_summarization_no_auth,+ test_auto_summarization_missing_enabled,+ test_auto_summarization_invalid_json,+ test_auto_summarization_enable,+ test_auto_summarization_disable,+ # Group 4: regression+ test_regression_get_speakers_list,+ test_regression_get_recording_speakers,+]+++def main():+ print(f"Running {len(ALL_TESTS)} Speaker API tests...\n")+ passed = 0+ failed = 0+ errors = []++ for test_fn in ALL_TESTS:+ name = test_fn.__name__+ try:+ result = test_fn()+ if result:+ print(f" PASS {name}")+ passed += 1+ else:+ print(f" FAIL {name} (returned False)")+ failed += 1+ errors.append(name)+ except Exception as e:+ print(f" ERROR {name}: {e}")+ failed += 1+ errors.append(name)++ print(f"\n{'=' * 60}")+ print(f"Results: {passed} passed, {failed} failed out of {len(ALL_TESTS)}")+ if errors:+ print("Failed tests:")+ for e in errors:+ print(f" - {e}")+ print('=' * 60)+ sys.exit(0 if failed == 0 else 1)+++if __name__ == "__main__":+ main()