Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add contextual speaker auto-labelling for connectors without voice embeddings: branch per-recording (embeddings -> voice match, none -> LLM match constrained to saved profiles), prefix-cache-friendly transcript-first prompt with an admin-editable guidance suffix, show the auto-label toggle for embedding-less connectors while hiding the confidence threshold, and clear stale embeddings on reprocess
Murtaza Nasir7b5b41664dd5
diff --git a/src/api/auth.py b/src/api/auth.pyindex 84d5b11e..f14af1f9 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -698,18 +698,36 @@ def account():connector_supports_diarization = USE_ASR_ENDPOINT # Default to USE_ASR_ENDPOINT for backwards compatconnector_supports_hotwords = USE_ASR_ENDPOINTconnector_supports_initial_prompt = USE_ASR_ENDPOINT+ connector_supports_speaker_embeddings = ASR_RETURN_SPEAKER_EMBEDDINGSif USE_NEW_TRANSCRIPTION_ARCHITECTURE:try:from src.services.transcription import get_registry+ from src.services.transcription.base import TranscriptionCapabilityregistry = get_registry()connector = registry.get_active_connector()if connector:connector_supports_diarization = connector.supports_diarizationconnector_supports_hotwords = connector.supports_hotwordsconnector_supports_initial_prompt = connector.supports_initial_prompt+ # Query the live instance: the asr_endpoint connector adds the+ # SPEAKER_EMBEDDINGS capability conditionally (only when its env+ # flag is on), so the class-level set would be wrong.+ connector_supports_speaker_embeddings = connector.supports(+ TranscriptionCapability.SPEAKER_EMBEDDINGS+ )except Exception as e:current_app.logger.warning(f"Could not get connector capabilities: {e}")+ # Speaker auto-labelling comes in two flavours. When the connector returns+ # voice embeddings, matching is biometric and tuned by a confidence+ # threshold. When it diarizes but returns no embeddings, we fall back to a+ # contextual LLM match; the toggle should still be offered in that case (the+ # threshold does not apply). Surfacing both lets the account page show the+ # toggle for embedding-less connectors, where it used to be hidden.+ contextual_labelling_available = (+ connector_supports_diarization and not connector_supports_speaker_embeddings+ )+# Check if user is a team admin and get their admin groupsadmin_memberships = GroupMembership.query.filter_by(user_id=current_user.id,@@ -761,7 +779,8 @@ def account():sso_subject=current_user.sso_subject,has_password=bool(current_user.password),password_login_disabled=password_login_disabled,- speaker_embeddings_enabled=ASR_RETURN_SPEAKER_EMBEDDINGS,+ speaker_embeddings_enabled=connector_supports_speaker_embeddings,+ contextual_labelling_available=contextual_labelling_available,auto_speaker_labelling=current_user.auto_speaker_labelling,auto_speaker_labelling_threshold=current_user.auto_speaker_labelling_threshold or 'medium',admin_disabled_auto_summarization=admin_disabled_auto_summarization,diff --git a/src/config/prompts.py b/src/config/prompts.pyindex 4a69c222..1bba31ff 100644--- a/src/config/prompts.py+++ b/src/config/prompts.py@@ -30,3 +30,15 @@ Example Format:....//and so on and so forth. Make sure not to miss any nuance or details."""+++# The admin-editable instruction body for CONTEXTUAL speaker labelling — used+# when a recording has no voice embeddings and the app falls back to naming+# speakers from the transcript, constrained to the user's saved speaker+# profiles. This is only the guidance paragraph; the code appends the concrete+# candidate list, the speaker labels, and the strict JSON output contract after+# it, so those cannot be broken by an edit here. It is deliberately the trailing+# (variable) part of a transcript-first prompt so it stays prefix-cache friendly+# (see PREFIX_CACHE_OPTIMIZED_PROMPTS): the transcript is the stable prefix, this+# guidance is the editable suffix.+DEFAULT_CONTEXTUAL_SPEAKER_PROMPT = """Work out which of the known speaker profiles each speaker label most likely corresponds to, using clues in the conversation such as the names people are addressed by, self-introductions, and references to roles or relationships. Only assign a known profile when the conversation clearly supports it; if you are not confident about a speaker, leave that speaker unassigned with an empty string. Never invent a name that is not in the known profiles list."""diff --git a/src/init_db.py b/src/init_db.pyindex f89d076b..a4e4d941 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -739,7 +739,17 @@ def initialize_database(app):setting_type='string')app.logger.info("Initialized admin_default_summary_prompt setting")-++ if not SystemSetting.query.filter_by(key='admin_default_contextual_speaker_prompt').first():+ from src.config.prompts import DEFAULT_CONTEXTUAL_SPEAKER_PROMPT+ SystemSetting.set_setting(+ key='admin_default_contextual_speaker_prompt',+ value=DEFAULT_CONTEXTUAL_SPEAKER_PROMPT,+ description='Guidance for contextual speaker labelling, used when a recording has no voice embeddings and speakers are named from the transcript, constrained to the user\'s saved profiles. Only the guidance is editable; the candidate list and JSON format are fixed in code.',+ setting_type='string'+ )+ app.logger.info("Initialized admin_default_contextual_speaker_prompt setting")+if not SystemSetting.query.filter_by(key='recording_disclaimer').first():SystemSetting.set_setting(key='recording_disclaimer',diff --git a/src/services/speaker_identification.py b/src/services/speaker_identification.pyindex 64092c6c..28fc52c7 100644--- a/src/services/speaker_identification.py+++ b/src/services/speaker_identification.py@@ -11,13 +11,18 @@ import jsonfrom flask import current_app-def identify_speakers_from_transcript(transcription_data, user_id):+def identify_speakers_from_transcript(transcription_data, user_id, candidate_names=None):"""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).+ candidate_names: Optional list of the user's saved speaker-profile names.+ When provided (contextual auto-labelling for connectors that return+ no voice embeddings), the model may only assign these exact names or+ an empty string, and the prompt switches to a prefix-cache-friendly+ transcript-first layout with an admin-editable guidance suffix.Returns:dict mapping original speaker labels to identified names.@@ -69,7 +74,61 @@ def identify_speakers_from_transcript(transcription_data, user_id):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.+ # Optional candidate constraint: when the caller supplies the user's saved+ # speaker profiles (contextual auto-labelling for connectors that return no+ # voice embeddings), the model may only assign those exact names. The prompt+ # is laid out transcript-first with the editable guidance + candidate list as+ # the trailing suffix, so it stays prefix-cache friendly and only the suffix+ # is admin-editable (see DEFAULT_CONTEXTUAL_SPEAKER_PROMPT).+ candidates = [str(name).strip() for name in (candidate_names or []) if str(name).strip()]++ if candidates:+ from src.config.prompts import DEFAULT_CONTEXTUAL_SPEAKER_PROMPT+ try:+ from src.tasks.processing import (+ PREFIX_CACHE_OPTIMIZED_PROMPTS, _SHARED_LLM_SYSTEM_MSG, _shared_user_prefix,+ )+ except Exception:+ PREFIX_CACHE_OPTIMIZED_PROMPTS = False+ _SHARED_LLM_SYSTEM_MSG = None+ _shared_user_prefix = None++ guidance = SystemSetting.get_setting(+ 'admin_default_contextual_speaker_prompt', DEFAULT_CONTEXTUAL_SPEAKER_PROMPT+ ) or DEFAULT_CONTEXTUAL_SPEAKER_PROMPT++ # Everything after the transcript. The concrete candidate list, the+ # speaker labels, and the strict JSON contract are code-controlled so an+ # admin edit to `guidance` cannot break the output format or the+ # exact-name constraint.+ suffix = (+ f"{guidance}\n\n"+ f"Known speaker profiles you may assign: {', '.join(candidates)}\n"+ f"Speakers to identify: {', '.join(speaker_labels)}\n\n"+ "Respond with a single JSON object whose keys are the speaker labels and whose "+ "values are the assigned profile name (copied exactly from the list above) or an "+ 'empty string "" when no profile clearly matches.\n\n'+ "Example format:\n"+ "{\n"+ ' "SPEAKER_01": "Jane Smith",\n'+ ' "SPEAKER_03": ""\n'+ "}\n\n"+ "JSON Response:\n"+ )+ if PREFIX_CACHE_OPTIMIZED_PROMPTS and _shared_user_prefix:+ # Reuse the shared transcript-first prefix so the layout matches the+ # title/summary calls when prefix caching is enabled.+ system_msg = _SHARED_LLM_SYSTEM_MSG+ prompt = _shared_user_prefix(transcript_text) + suffix+ else:+ system_msg = (+ "You assign speakers in a transcript to a fixed list of known people, "+ "using only contextual clues in the dialogue. Your response must be a "+ "single, valid JSON object and must only use names from the provided list."+ )+ prompt = f'Transcript:\n"""\n{transcript_text}\n"""\n\n' + suffix+ else:+ 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)}@@ -96,17 +155,17 @@ Example format:JSON Response:"""+ 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."+ )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 = Noneif use_schema:@@ -162,7 +221,7 @@ JSON Response:current_app.logger.info(f"[Auto-Identify] Parsed identified_map: {identified_map}")# --- Sanitize identified_map ---- identified_map = _sanitize_identified_map(identified_map, speaker_labels)+ identified_map = _sanitize_identified_map(identified_map, speaker_labels, candidate_names=candidates)current_app.logger.info(f"[Auto-Identify] Sanitized identified_map: {identified_map}")# Map back to original speaker labels@@ -175,10 +234,16 @@ JSON Response:return final_speaker_map-def _sanitize_identified_map(identified_map, speaker_labels):+def _sanitize_identified_map(identified_map, speaker_labels, candidate_names=None):"""Clean up LLM output: handle inverted maps, strip commentary,clear placeholders, etc.++ When candidate_names is given (contextual auto-labelling), the result is+ constrained to those exact saved names (case-insensitive match) or an empty+ string — the model cannot introduce a name that isn't a saved profile, and+ the generic name-cleanup below is skipped so punctuated saved names like+ "Smith, John" survive intact."""speaker_label_re = re.compile(r'^SPEAKER_\d{2}$')@@ -189,6 +254,12 @@ def _sanitize_identified_map(identified_map, speaker_labels):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}+ allowed = {+ str(name).strip().casefold(): str(name).strip()+ for name in (candidate_names or [])+ if str(name).strip()+ }+sanitized = {}for speaker_label, identified_name in identified_map.items():# Skip entries whose key isn't a valid SPEAKER_XX label@@ -200,6 +271,12 @@ def _sanitize_identified_map(identified_map, speaker_labels):name = identified_name.strip()+ # Contextual mode: accept only an exact saved-profile name (preserving+ # its original casing/punctuation), otherwise leave the speaker blank.+ if allowed:+ sanitized[speaker_label] = allowed.get(name.casefold(), "")+ continue+# Clear generic placeholdersif name.lower() in ["unknown", "n/a", "not available", "unclear", "unidentified", ""]:sanitized[speaker_label] = ""@@ -227,3 +304,79 @@ def _sanitize_identified_map(identified_map, speaker_labels):sanitized[speaker_label] = namereturn sanitized+++def apply_contextual_auto_labels(recording, user):+ """Opt-in contextual speaker labelling for recordings without embeddings.++ Called from the transcription pipeline only when the recording has no voice+ embeddings (so the embedding matcher cannot run) and the user has enabled+ auto speaker labelling. Asks the LLM to map the diarized speaker labels to+ the user's saved speaker profiles, constrained to those exact names, applies+ the accepted matches to the transcription, and creates representative+ snippets for the matched speakers. Returns the applied {SPEAKER_XX: name}+ map (empty dict when nothing was applied). Never raises: any failure is+ logged and swallowed so it cannot fail the transcription.+ """+ if not user.auto_speaker_labelling or not recording.transcription:+ return {}++ from src.models import Speaker+ from src.services.speaker_embedding_matcher import apply_speaker_names_to_transcription+ from src.services.speaker_snippets import create_speaker_snippets++ candidates = [+ speaker.name+ for speaker in Speaker.query.filter_by(user_id=user.id).order_by(Speaker.name.asc()).all()+ if speaker.name+ ]+ if not candidates:+ current_app.logger.info(+ "[Auto-Identify] User %s has no saved speaker profiles; skipping contextual labelling",+ user.id,+ )+ return {}++ try:+ transcription_data = json.loads(recording.transcription)+ except (json.JSONDecodeError, TypeError):+ current_app.logger.warning(+ "[Auto-Identify] Recording %s transcription is not parseable JSON; skipping", recording.id+ )+ return {}+ if not isinstance(transcription_data, list):+ return {}++ try:+ speaker_map = identify_speakers_from_transcript(+ transcription_data, user.id, candidate_names=candidates+ )+ except Exception as error:+ current_app.logger.warning(+ "[Auto-Identify] Contextual identification failed for recording %s: %s", recording.id, error+ )+ return {}++ speaker_map = {label: name for label, name in speaker_map.items() if name}+ if not speaker_map:+ current_app.logger.info(+ "[Auto-Identify] No saved speaker matched recording %s contextually", recording.id+ )+ return {}++ if not apply_speaker_names_to_transcription(recording, speaker_map):+ return {}++ try:+ snippet_map = {label: {"name": name, "isMe": False} for label, name in speaker_map.items()}+ create_speaker_snippets(recording.id, snippet_map)+ except Exception as error:+ # Snippets are a convenience; a failure here must not undo the labelling.+ current_app.logger.warning(+ "[Auto-Identify] Could not create snippets for recording %s: %s", recording.id, error+ )++ current_app.logger.info(+ "[Auto-Identify] Applied contextual speaker matches to recording %s: %s", recording.id, speaker_map+ )+ return speaker_mapdiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 23fea348..2533b378 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -2066,9 +2066,15 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_filerecording.transcription = transcription_textcurrent_app.logger.info(f"Transcription completed: {len(transcription_text)} characters")- # Store speaker embeddings if available- if response.speaker_embeddings:- recording.speaker_embeddings = response.speaker_embeddings+ # Replace speaker embeddings on every successful+ # transcription. Embeddings are keyed to THIS run's+ # speaker labels, so an earlier run's embeddings go stale+ # when the transcript is re-derived; clearing them when+ # the new response has none prevents a prior connector's+ # embeddings from driving voice matches after reprocessing+ # with an embedding-less connector.+ recording.speaker_embeddings = response.speaker_embeddings or None+ if recording.speaker_embeddings:current_app.logger.info(f"Stored speaker embeddings for speakers: {list(response.speaker_embeddings.keys())}")# If we reach here, transcription succeeded@@ -2214,36 +2220,50 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file# Don't fail transcription if usage tracking failscurrent_app.logger.warning(f"Failed to record transcription usage: {usage_err}")- # Apply auto speaker labelling if enabled and embeddings available- if recording.speaker_embeddings:- try:- from src.services.speaker_embedding_matcher import (- apply_auto_speaker_labels,- apply_speaker_names_to_transcription,- update_speaker_profiles_from_recording- )-- user = db.session.get(User, recording.user_id)- if user and user.auto_speaker_labelling:- current_app.logger.info(f"Applying auto speaker labelling for recording {recording.id}")- speaker_map = apply_auto_speaker_labels(recording, user)+ # Apply opt-in speaker labelling. Voice embeddings are the preferred+ # path; when the recording has none (an embedding-less connector, or+ # a chunked file whose embeddings were dropped) we fall back to a+ # contextual LLM match constrained to the user's saved speaker names.+ # The branch is per recording, not per connector, so it also covers+ # embedding-capable connectors that happened to return none.+ label_user = db.session.get(User, recording.user_id)+ if label_user and label_user.auto_speaker_labelling:+ if recording.speaker_embeddings:+ try:+ from src.services.speaker_embedding_matcher import (+ apply_auto_speaker_labels,+ apply_speaker_names_to_transcription,+ update_speaker_profiles_from_recording+ )+ current_app.logger.info(f"Applying embedding auto speaker labelling for recording {recording.id}")+ speaker_map = apply_auto_speaker_labels(recording, label_user)if speaker_map:current_app.logger.info(f"Auto-matched speakers: {speaker_map}")- # Apply names to transcriptionif apply_speaker_names_to_transcription(recording, speaker_map):current_app.logger.info(f"Applied speaker names to transcription")- # Update speaker profiles with new embeddings- updated_count = update_speaker_profiles_from_recording(recording, speaker_map, user)+ updated_count = update_speaker_profiles_from_recording(recording, speaker_map, label_user)if updated_count > 0:current_app.logger.info(f"Updated {updated_count} speaker profiles with new embeddings")else:current_app.logger.warning(f"Failed to apply speaker names to transcription for recording {recording.id}")else:- current_app.logger.info(f"No speakers matched for auto-labelling")- except Exception as auto_label_err:- # Don't fail transcription if auto-labelling fails- current_app.logger.warning(f"Failed to apply auto speaker labelling: {auto_label_err}")+ current_app.logger.info(f"No speakers matched for embedding auto-labelling")+ except Exception as auto_label_err:+ # Don't fail transcription if auto-labelling fails+ current_app.logger.warning(f"Failed to apply embedding speaker labelling: {auto_label_err}")+ else:+ try:+ from src.services.speaker_identification import apply_contextual_auto_labels+ current_app.logger.info(f"Applying contextual auto speaker labelling for recording {recording.id}")+ contextual_map = apply_contextual_auto_labels(recording, label_user)+ if not contextual_map:+ current_app.logger.info(f"No saved speaker matched recording {recording.id} contextually")+ except Exception as auto_label_err:+ # apply_contextual_auto_labels is already failure-isolated;+ # this guard is belt-and-suspenders so labelling never+ # fails the transcription.+ current_app.logger.warning(f"Failed to apply contextual speaker labelling: {auto_label_err}")# Check if auto-summarization is disabled (admin setting or user preference)admin_setting = SystemSetting.get_setting('disable_auto_summarization', False)diff --git a/templates/account.html b/templates/account.htmlindex 5770a89c..f07d2d93 100644--- a/templates/account.html+++ b/templates/account.html@@ -1085,21 +1085,31 @@<h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-1" data-i18n="accountTabs.speakersManagement">Speakers Management</h2><p class="text-sm text-[var(--text-secondary)] hidden sm:block" data-i18n="speakersManagement.description">Manage your saved speakers. These are automatically saved when you use speaker names in your recordings.</p></div>- {% if speaker_embeddings_enabled %}- <div class="flex items-center gap-2 sm:gap-3 ml-4 flex-shrink-0" title="Automatically label speakers in new recordings when voice profiles match">+ {% if speaker_embeddings_enabled or contextual_labelling_available %}+ <div class="flex items-center gap-2 sm:gap-3 ml-4 flex-shrink-0" title="{% if speaker_embeddings_enabled %}Automatically label speakers in new recordings when saved voice profiles match{% else %}Automatically label speakers in new recordings from the conversation context{% endif %}"><span class="text-sm text-[var(--text-secondary)] hidden sm:inline" data-i18n="account.autoLabel">Auto-label</span><label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" id="autoSpeakerLabellingToggle" class="sr-only peer" {% if auto_speaker_labelling %}checked{% endif %}><div class="w-11 h-6 bg-[var(--bg-tertiary)] peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[var(--border-focus)] rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-[var(--text-muted)] after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--bg-accent)] peer-checked:after:bg-white"></div></label>+ {# Confidence threshold only tunes embedding (voice) matching; the contextual LLM path has no similarity score, so it is hidden there. #}+ {% if speaker_embeddings_enabled %}<select id="autoSpeakerLabellingThreshold" class="text-sm bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-md px-2 py-1 text-[var(--text-primary)] focus:ring-2 focus:ring-[var(--border-focus)] disabled:opacity-50 disabled:cursor-not-allowed" {% if not auto_speaker_labelling %}disabled{% endif %}><option value="high" {% if auto_speaker_labelling_threshold == 'high' %}selected{% endif %}>High</option><option value="medium" {% if auto_speaker_labelling_threshold == 'medium' %}selected{% endif %}>Medium</option><option value="low" {% if auto_speaker_labelling_threshold == 'low' %}selected{% endif %}>Low</option></select>+ {% endif %}</div>{% endif %}</div>+ {% if contextual_labelling_available and not speaker_embeddings_enabled %}+ <div class="flex-shrink-0 -mt-2 mb-4">+ <p class="text-xs text-[var(--text-muted)] leading-snug">+ Speakers are matched from the conversation context because your transcription engine does not provide voice fingerprints. This can be quite inaccurate, depending on how much the conversation reveals about who is speaking and how well your model separates speakers. For the most accurate, voice-based speaker matching, the WhisperX ASR container is recommended.+ </p>+ </div>+ {% endif %}<!-- Top toolbar with bulk actions --><div class="flex-shrink-0 flex flex-wrap justify-between items-center gap-2 py-2 sm:py-3 px-3 sm:px-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] mb-3">diff --git a/templates/admin.html b/templates/admin.htmlindex 2e46853d..f1862913 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -956,6 +956,42 @@</div></div>+ <!-- Contextual speaker labelling: guidance used when a recording has+ no voice embeddings and speakers are named from the transcript,+ constrained to the user's saved profiles. Only this guidance is+ editable; the candidate list and JSON output contract are fixed in+ code. It is the trailing (variable) part of a transcript-first+ prompt, so editing it does not disturb prefix caching. -->+ <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">+ <h4 class="text-md font-medium text-[var(--text-secondary)] mb-1">Contextual Speaker Labelling Prompt</h4>+ <p class="text-sm text-[var(--text-muted)] mb-4">+ Guidance the model follows when it labels speakers from the conversation context, used only for transcription engines that diarize without returning voice fingerprints. The list of the user's saved speaker names and the JSON output format are added automatically after this text. Leave blank to use the built-in default.+ </p>+ <div class="mb-4">+ <textarea+ v-model="contextualSpeakerPrompt"+ rows="5"+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"+ placeholder="Leave blank to use the built-in default guidance.">+ </textarea>+ </div>+ <div class="flex justify-end items-center">+ <button @click="saveContextualSpeakerPrompt"+ :disabled="isSavingContextualPrompt"+ class="btn btn--primary">+ <i v-if="isSavingContextualPrompt" class="fas fa-spinner fa-spin mr-2"></i>+ <i v-else class="fas fa-save mr-2"></i>+ ${ isSavingContextualPrompt ? t('adminDashboard.saving') : t('buttons.saveChanges') }+ </button>+ </div>+ <div v-if="contextualPromptSaveMessage" class="mt-4">+ <div :class="contextualPromptSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"+ class="p-3 rounded-md text-sm">+ ${ contextualPromptSaveMessage }+ </div>+ </div>+ </div>+<div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]"><h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.promptHierarchy')}</h4><p class="text-sm text-[var(--text-muted)] mb-3">@@ -2087,6 +2123,9 @@ Summarization Instructions:// raw card isn't a redundant second editor.'admin_default_initial_prompt','admin_default_hotwords',+ // Managed by the dedicated contextual-speaker-prompt editor+ // in the Default Prompts tab.+ 'admin_default_contextual_speaker_prompt',]);const displayedSettings = computed(() =>(settings.value || []).filter(s => !HIDDEN_SETTING_KEYS.has(s.key))@@ -2311,6 +2350,11 @@ Summarization Instructions:const isSavingHints = ref(false);const hintsSaveMessage = ref('');const hintsSaveError = ref(false);+ // Contextual speaker-labelling guidance (managed in this tab)+ const contextualSpeakerPrompt = ref('');+ const isSavingContextualPrompt = ref(false);+ const contextualPromptSaveMessage = ref('');+ const contextualPromptSaveError = ref(false);const originalDefaultPrompt = `Generate a comprehensive summary that includes the following sections:- **Key Issues Discussed**: A bulleted list of the main topics- **Key Decisions Made**: A bulleted list of any decisions reached@@ -3455,6 +3499,8 @@ Summarization Instructions:defaultInitialPrompt.value = ipSetting ? (ipSetting.value || '') : '';const hwSetting = settingsData.find(s => s.key === 'admin_default_hotwords');defaultHotwords.value = hwSetting ? (hwSetting.value || '') : '';+ const cspSetting = settingsData.find(s => s.key === 'admin_default_contextual_speaker_prompt');+ contextualSpeakerPrompt.value = cspSetting ? (cspSetting.value || '') : '';} catch (error) {console.error('Error loading default prompt:', error);promptSaveMessage.value = t('adminDashboard.errors.failedToLoadPrompt');@@ -3553,6 +3599,40 @@ Summarization Instructions:promptSaveMessage.value = t('adminDashboard.promptResetMessage');promptSaveError.value = false;};++ const saveContextualSpeakerPrompt = async () => {+ isSavingContextualPrompt.value = true;+ contextualPromptSaveMessage.value = '';+ contextualPromptSaveError.value = false;+ try {+ const response = await fetch('/admin/settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content+ },+ body: JSON.stringify({+ key: 'admin_default_contextual_speaker_prompt',+ value: contextualSpeakerPrompt.value,+ description: 'Guidance for contextual speaker labelling (used when a recording has no voice embeddings). Only the guidance is editable; the candidate list and JSON format are fixed in code. Leave blank to use the built-in default.',+ setting_type: 'string'+ })+ });+ if (!response.ok) throw new Error('Failed to save prompt');+ // Keep the cached settings row in sync.+ const row = (settings.value || []).find(s => s.key === 'admin_default_contextual_speaker_prompt');+ if (row) row.value = contextualSpeakerPrompt.value;+ contextualPromptSaveMessage.value = t('adminDashboard.promptSavedSuccessfully');+ contextualPromptSaveError.value = false;+ setTimeout(() => { contextualPromptSaveMessage.value = ''; }, 3000);+ } catch (error) {+ console.error('Error saving contextual speaker prompt:', error);+ contextualPromptSaveMessage.value = t('adminDashboard.errors.failedToSavePrompt');+ contextualPromptSaveError.value = true;+ } finally {+ isSavingContextualPrompt.value = false;+ }+ };const loadInquireStatus = async () => {try {@@ -3858,7 +3938,11 @@ Summarization Instructions:isSavingHints,hintsSaveMessage,hintsSaveError,-+ contextualSpeakerPrompt,+ isSavingContextualPrompt,+ contextualPromptSaveMessage,+ contextualPromptSaveError,+// ComputedfilteredUsers,availableUsers,@@ -3938,7 +4022,8 @@ Summarization Instructions:loadDefaultPrompt,saveDefaultPrompt,resetDefaultPrompt,- saveDefaultHints+ saveDefaultHints,+ saveContextualSpeakerPrompt};},delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2diff --git a/tests/test_contextual_speaker_labelling.py b/tests/test_contextual_speaker_labelling.pynew file mode 100644index 00000000..c95ec3ad--- /dev/null+++ b/tests/test_contextual_speaker_labelling.py@@ -0,0 +1,193 @@+"""Contextual (embedding-less) speaker auto-labelling.++Covers the candidate-constrained LLM path added for connectors that diarize but+return no voice embeddings: exact-name constraint, the prefix-cache-friendly+transcript-first layout, the admin-editable guidance suffix, and the opt-in+apply_contextual_auto_labels orchestration. The manual identify path (no+candidates) must remain unconstrained.+"""++import json+import os+import sys+from types import SimpleNamespace+from unittest.mock import Mock, patch++from flask import Flask++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.services.speaker_identification import (+ identify_speakers_from_transcript,+ apply_contextual_auto_labels,+ _sanitize_identified_map,+)+from src.config.prompts import DEFAULT_CONTEXTUAL_SPEAKER_PROMPT+++TRANSCRIPT = [+ {"speaker": "S01", "sentence": "Maha, can you review this?"},+ {"speaker": "S02", "sentence": "Yes, I will send it today."},+]+++def _completion(content):+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))])+++def _settings(contextual_prompt=None, transcript_limit=30000):+ """Side effect for SystemSetting.get_setting keyed by setting name."""+ def _get(key, default=None):+ if key == 'transcript_length_limit':+ return transcript_limit+ if key == 'admin_default_contextual_speaker_prompt':+ return contextual_prompt+ return default+ return _get+++def _speaker_model(names):+ query = Mock()+ query.filter_by.return_value.order_by.return_value.all.return_value = [+ SimpleNamespace(name=name) for name in names+ ]+ return SimpleNamespace(query=query, name=SimpleNamespace(asc=lambda: "speaker-name"))+++# --- sanitizer constraint ---++def test_sanitizer_constrains_to_saved_names_and_preserves_punctuation():+ app = Flask(__name__)+ with app.app_context():+ out = _sanitize_identified_map(+ {"SPEAKER_00": "maha", "SPEAKER_01": "Nobody", "SPEAKER_02": "Smith, John"},+ ["SPEAKER_00", "SPEAKER_01", "SPEAKER_02"],+ candidate_names=["Maha", "Smith, John"],+ )+ assert out == {"SPEAKER_00": "Maha", "SPEAKER_01": "", "SPEAKER_02": "Smith, John"}+++# --- prompt / constraint behaviour ---++def test_candidates_constrain_output_and_appear_in_prompt(monkeypatch):+ monkeypatch.delenv("AUTO_IDENTIFY_RESPONSE_SCHEMA", raising=False)+ app = Flask(__name__)+ with app.app_context(), patch(+ "src.services.llm.call_llm_completion",+ return_value=_completion('{"SPEAKER_00":"Maha","SPEAKER_01":"Jill"}'),+ ) as call_llm, patch("src.models.SystemSetting.get_setting", side_effect=_settings()):+ result = identify_speakers_from_transcript(+ TRANSCRIPT, user_id=1, candidate_names=["Jael", "Maha", "Siva"]+ )+ # "Jill" is not a saved profile, so it is dropped.+ assert result == {"S01": "Maha", "S02": ""}+ prompt = call_llm.call_args.kwargs["messages"][1]["content"]+ assert "Known speaker profiles you may assign: Jael, Maha, Siva" in prompt+ assert DEFAULT_CONTEXTUAL_SPEAKER_PROMPT in prompt+++def test_manual_path_is_unconstrained(monkeypatch):+ monkeypatch.delenv("AUTO_IDENTIFY_RESPONSE_SCHEMA", raising=False)+ app = Flask(__name__)+ with app.app_context(), patch(+ "src.services.llm.call_llm_completion",+ return_value=_completion('{"SPEAKER_00":"Maha","SPEAKER_01":"Jill"}'),+ ), patch("src.models.SystemSetting.get_setting", side_effect=_settings()):+ result = identify_speakers_from_transcript(TRANSCRIPT, user_id=1)+ assert result == {"S01": "Maha", "S02": "Jill"}+++def test_admin_prompt_override_replaces_default_guidance(monkeypatch):+ monkeypatch.delenv("AUTO_IDENTIFY_RESPONSE_SCHEMA", raising=False)+ app = Flask(__name__)+ custom = "CUSTOM-ADMIN-GUIDANCE-XYZ do your best."+ with app.app_context(), patch(+ "src.services.llm.call_llm_completion",+ return_value=_completion('{"SPEAKER_00":""}'),+ ) as call_llm, patch(+ "src.models.SystemSetting.get_setting", side_effect=_settings(contextual_prompt=custom)+ ):+ identify_speakers_from_transcript(TRANSCRIPT, user_id=1, candidate_names=["Maha"])+ prompt = call_llm.call_args.kwargs["messages"][1]["content"]+ assert custom in prompt+ assert DEFAULT_CONTEXTUAL_SPEAKER_PROMPT not in prompt+++def test_prefix_cache_layout_puts_transcript_first_and_guidance_last(monkeypatch):+ monkeypatch.delenv("AUTO_IDENTIFY_RESPONSE_SCHEMA", raising=False)+ from src.tasks.processing import _SHARED_LLM_SYSTEM_MSG+ app = Flask(__name__)+ with app.app_context(), patch(+ "src.tasks.processing.PREFIX_CACHE_OPTIMIZED_PROMPTS", True+ ), patch(+ "src.services.llm.call_llm_completion",+ return_value=_completion('{"SPEAKER_00":"Maha"}'),+ ) as call_llm, patch("src.models.SystemSetting.get_setting", side_effect=_settings()):+ identify_speakers_from_transcript(TRANSCRIPT, user_id=1, candidate_names=["Maha"])+ messages = call_llm.call_args.kwargs["messages"]+ # System message matches the shared one used by title/summary.+ assert messages[0]["content"] == _SHARED_LLM_SYSTEM_MSG+ user_msg = messages[1]["content"]+ # Transcript-first shared prefix, guidance suffix strictly after it.+ assert user_msg.startswith('Transcript:\n"""\n')+ assert user_msg.index("Known speaker profiles") > user_msg.index('"""')+++# --- apply_contextual_auto_labels orchestration ---++def test_apply_is_opt_in():+ recording = SimpleNamespace(id=9, transcription=json.dumps(TRANSCRIPT))+ user = SimpleNamespace(id=1, auto_speaker_labelling=False)+ with patch(+ "src.services.speaker_identification.identify_speakers_from_transcript"+ ) as ident:+ assert apply_contextual_auto_labels(recording, user) == {}+ ident.assert_not_called()+++def test_apply_skips_users_without_profiles():+ recording = SimpleNamespace(id=9, transcription=json.dumps(TRANSCRIPT))+ user = SimpleNamespace(id=1, auto_speaker_labelling=True)+ with Flask(__name__).app_context(), patch(+ "src.models.Speaker", _speaker_model([])+ ), patch(+ "src.services.speaker_identification.identify_speakers_from_transcript"+ ) as ident:+ assert apply_contextual_auto_labels(recording, user) == {}+ ident.assert_not_called()+++def test_apply_applies_only_saved_matches_and_creates_snippets():+ recording = SimpleNamespace(id=9, transcription=json.dumps(TRANSCRIPT))+ user = SimpleNamespace(id=1, auto_speaker_labelling=True)+ with Flask(__name__).app_context(), patch(+ "src.models.Speaker", _speaker_model(["Jael", "Maha", "Siva"])+ ), patch(+ "src.services.speaker_identification.identify_speakers_from_transcript",+ return_value={"S01": "Maha", "S02": ""},+ ) as ident, patch(+ "src.services.speaker_embedding_matcher.apply_speaker_names_to_transcription",+ return_value=True,+ ) as apply_names, patch(+ "src.services.speaker_snippets.create_speaker_snippets"+ ) as snippets:+ result = apply_contextual_auto_labels(recording, user)+ assert result == {"S01": "Maha"}+ assert ident.call_args.kwargs["candidate_names"] == ["Jael", "Maha", "Siva"]+ apply_names.assert_called_once_with(recording, {"S01": "Maha"})+ snippets.assert_called_once_with(9, {"S01": {"name": "Maha", "isMe": False}})+++def test_apply_failure_is_isolated():+ recording = SimpleNamespace(id=9, transcription=json.dumps(TRANSCRIPT))+ user = SimpleNamespace(id=1, auto_speaker_labelling=True)+ with Flask(__name__).app_context(), patch(+ "src.models.Speaker", _speaker_model(["Maha"])+ ), patch(+ "src.services.speaker_identification.identify_speakers_from_transcript",+ side_effect=RuntimeError("LLM unavailable"),+ ), patch(+ "src.services.speaker_embedding_matcher.apply_speaker_names_to_transcription"+ ) as apply_names:+ assert apply_contextual_auto_labels(recording, user) == {}+ apply_names.assert_not_called()