Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
auto id speakers
Murtaza Nasir86ba8686d9a6
diff --git a/app.py b/app.pyindex 77b8134f..36349b40 100644--- a/app.py+++ b/app.py@@ -1,7 +1,11 @@# Speakr - Audio Transcription and Summarization Appimport osimport sys-from flask import Flask, render_template, request, jsonify, send_file, Markup, redirect, url_for, flash+from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for, flash+try:+ from flask import Markup+except ImportError:+ from markupsafe import Markupfrom flask_sqlalchemy import SQLAlchemyfrom datetime import datetimefrom openai import OpenAI # Keep using the OpenAI library@@ -705,6 +709,168 @@ def update_speakers(recording_id):app.logger.error(f"Error updating speakers for recording {recording_id}: {e}", exc_info=True)return jsonify({'error': str(e)}), 500+def identify_speakers_from_text(transcription):+ """+ Uses an LLM to identify speakers from a transcription.+ """+ if not TEXT_MODEL_API_KEY:+ raise ValueError("TEXT_MODEL_API_KEY not configured.")++ # Extract existing speaker labels (e.g., SPEAKER_00, SPEAKER_01) in order of appearance+ all_labels = re.findall(r'\[(SPEAKER_\d+)\]', transcription)+ seen = set()+ speaker_labels = [x for x in all_labels if not (x in seen or seen.add(x))]++ if not speaker_labels:+ return {}++ prompt = f"""Analyze the following transcription and identify the names of the speakers. The speakers are labeled as {', '.join(speaker_labels)}. Based on the context of the conversation, determine the most likely name for each speaker label.++Transcription:+---+{transcription[:28000]}+---++Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_00") and values are the identified full names. If a name cannot be determined, use the value "Unknown".++Example:+{{+ "SPEAKER_00": "John Doe",+ "SPEAKER_01": "Jane Smith",+ "SPEAKER_02": "Unknown"+}}++JSON Response:+"""++ try:+ completion = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=[+ {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers. Your response must be a single, valid JSON object."},+ {"role": "user", "content": prompt}+ ],+ temperature=0.2,+ response_format={"type": "json_object"}+ )+ response_content = completion.choices[0].message.content+ speaker_map = json.loads(response_content)++ # Post-process the map to replace "Unknown" with an empty string+ for speaker_label, identified_name in speaker_map.items():+ if identified_name.strip().lower() == "unknown":+ speaker_map[speaker_label] = ""++ return speaker_map+ except Exception as e:+ app.logger.error(f"Error calling LLM for speaker identification: {e}")+ raise++def identify_unidentified_speakers_from_text(transcription, unidentified_speakers):+ """+ Uses an LLM to identify only the unidentified speakers from a transcription.+ """+ if not TEXT_MODEL_API_KEY:+ raise ValueError("TEXT_MODEL_API_KEY not configured.")++ if not unidentified_speakers:+ return {}++ prompt = f"""Analyze the following transcription and identify the names of the UNIDENTIFIED speakers only. The unidentified speakers are labeled as {', '.join(unidentified_speakers)}. Based on the context of the conversation, determine the most likely name for each of these speaker labels.++Note: Only identify the speakers listed above. Other speakers in the transcription may already be identified and should be ignored.++Transcription:+---+{transcription[:28000]}+---++Respond with a single JSON object where keys are the unidentified speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined, use the value "Unknown".++Example:+{{+ "SPEAKER_01": "Jane Smith",+ "SPEAKER_03": "Unknown"+}}++JSON Response:+"""++ try:+ completion = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=[+ {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers. Your response must be a single, valid JSON object containing only the requested unidentified speakers."},+ {"role": "user", "content": prompt}+ ],+ temperature=0.2,+ response_format={"type": "json_object"}+ )+ response_content = completion.choices[0].message.content+ speaker_map = json.loads(response_content)++ # Post-process the map to replace "Unknown" with an empty string+ for speaker_label, identified_name in speaker_map.items():+ if identified_name.strip().lower() == "unknown":+ speaker_map[speaker_label] = ""++ return speaker_map+ except Exception as e:+ app.logger.error(f"Error calling LLM for speaker identification: {e}")+ raise+[email protected]('/recording/<int:recording_id>/auto_identify_speakers', methods=['POST'])+@login_required+def auto_identify_speakers(recording_id):+ """+ Automatically identifies speakers in a transcription using an LLM.+ Only identifies speakers that haven't been identified yet.+ """+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to modify this recording'}), 403++ if not recording.transcription:+ return jsonify({'error': 'No transcription available for speaker identification'}), 400++ # Get the current speaker map from the request+ data = request.json or {}+ current_speaker_map = data.get('current_speaker_map', {})++ # Extract all speaker labels from transcription+ all_labels = re.findall(r'\[(SPEAKER_\d+)\]', recording.transcription)+ seen = set()+ speaker_labels = [x for x in all_labels if not (x in seen or seen.add(x))]++ # Filter out speakers that already have names assigned+ unidentified_speakers = []+ for speaker_label in speaker_labels:+ speaker_info = current_speaker_map.get(speaker_label, {})+ speaker_name = speaker_info.get('name', '').strip() if isinstance(speaker_info, dict) else str(speaker_info).strip()++ # Only include speakers that don't have names or have empty names+ if not speaker_name:+ unidentified_speakers.append(speaker_label)++ if not unidentified_speakers:+ return jsonify({'success': True, 'speaker_map': {}, 'message': 'All speakers are already identified'})++ # Call the helper function with only unidentified speakers+ speaker_map = identify_unidentified_speakers_from_text(recording.transcription, unidentified_speakers)++ return jsonify({'success': True, 'speaker_map': speaker_map})++ except ValueError as ve:+ # Handle cases where API key is not set+ return jsonify({'error': str(ve)}), 503+ except Exception as e:+ 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: {e}'}), 500+# --- Chat with Transcription ---@app.route('/chat', methods=['POST'])@login_requireddiff --git a/static/js/app.js b/static/js/app.jsindex fe4e370c..00ea620b 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -44,6 +44,7 @@ document.addEventListener('DOMContentLoaded', () => {const recordingToDelete = ref(null);const reprocessType = ref(null); // 'transcription' or 'summary'const reprocessRecording = ref(null);+ const isAutoIdentifying = ref(false);const asrReprocessOptions = reactive({language: '',min_speakers: null,@@ -1570,6 +1571,7 @@ document.addEventListener('DOMContentLoaded', () => {highlightedSpeaker.value = null;speakerSuggestions.value = {};loadingSuggestions.value = {};+ isAutoIdentifying.value = false;showSpeakerModal.value = true;};@@ -1627,6 +1629,60 @@ document.addEventListener('DOMContentLoaded', () => {});};+ const autoIdentifySpeakers = async () => {+ if (!selectedRecording.value) {+ showToast('No recording selected.', 'fa-exclamation-circle');+ return;+ }++ isAutoIdentifying.value = true;+ showToast('Starting automatic speaker identification...', 'fa-magic');++ try {+ const response = await fetch(`/recording/${selectedRecording.value.id}/auto_identify_speakers`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ current_speaker_map: speakerMap.value+ })+ });++ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Unknown error occurred during auto-identification.');+ }++ // Check if there's a message (e.g., all speakers already identified)+ if (data.message) {+ showToast(data.message, 'fa-info-circle');+ return;+ }++ // Update speakerMap with the identified names (only for unidentified speakers)+ let identifiedCount = 0;+ for (const speakerId in data.speaker_map) {+ if (speakerMap.value[speakerId]) {+ speakerMap.value[speakerId].name = data.speaker_map[speakerId];+ if (data.speaker_map[speakerId]) { // Only count non-empty names+ identifiedCount++;+ }+ }+ }++ if (identifiedCount > 0) {+ showToast(`${identifiedCount} speaker(s) identified successfully!`, 'fa-check-circle');+ } else {+ showToast('No speakers could be identified from the context.', 'fa-info-circle');+ }++ } catch (error) {+ console.error('Auto Identify Speakers Error:', error);+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 5000);+ } finally {+ isAutoIdentifying.value = false;+ }+ };+const performReprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {if (!recordingId) {setGlobalError('No recording ID provided for reprocessing.');@@ -2094,6 +2150,8 @@ document.addEventListener('DOMContentLoaded', () => {loadingSuggestions,searchSpeakers,selectSpeakerSuggestion,+ autoIdentifySpeakers,+ isAutoIdentifying,// Main column resizer refs (not needed in template but good practice if they were)// leftMainColumn, rightMainColumn, mainColumnResizer, mainContentColumns}diff --git a/templates/index.html b/templates/index.htmlindex 2575ea82..7ffadc0a 100644--- a/templates/index.html+++ b/templates/index.html@@ -319,9 +319,21 @@<span class="ml-2">Regenerate summary after updating names</span></label></div>- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">- <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>- <button @click="saveSpeakerNames" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save Names</button>+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">+ <div>+ <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">+ <i class="fas fa-magic mr-2"></i>+ <span v-if="!isAutoIdentifying">Auto Identify</span>+ <span v-else>+ <i class="fas fa-spinner fa-spin mr-2"></i>+ Identifying...+ </span>+ </button>+ </div>+ <div class="flex space-x-3">+ <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button @click="saveSpeakerNames" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save Names</button>+ </div></div></div></div>