Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add inline transcript editing in speaker identification modal
Murtaza Nasir967dce468b37
diff --git a/src/app.py b/src/app.pyindex e8239b17..18ccc0e4 100644--- a/src/app.py+++ b/src/app.py@@ -4586,6 +4586,81 @@ 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[email protected]('/recording/<int:recording_id>/update_transcript', methods=['POST'])+@login_required+def update_transcript(recording_id):+ """Updates the complete transcript data including text edits and speaker changes."""+ 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 edit this recording'}), 403++ data = request.json+ transcript_data = data.get('transcript_data')+ speaker_map = data.get('speaker_map', {})+ regenerate_summary = data.get('regenerate_summary', False)++ if not transcript_data or not isinstance(transcript_data, list):+ return jsonify({'error': 'Invalid transcript data provided'}), 400++ # Update speaker names in the transcript data+ speaker_names_used = []+ for segment in transcript_data:+ original_speaker_label = segment.get('speaker')++ # Apply speaker name mapping if provided+ 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'):+ 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)++ # Save the updated transcript+ recording.transcription = json.dumps(transcript_data)++ # Update participants+ final_speakers = set()+ for seg in transcript_data:+ speaker = seg.get('speaker')+ if speaker and str(speaker).strip():+ # Only include speakers with real names (not default labels)+ if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):+ final_speakers.add(speaker)+ recording.participants = ', '.join(sorted(list(final_speakers)))++ # Update speaker usage statistics+ if speaker_names_used:+ update_speaker_usage(speaker_names_used)++ db.session.commit()++ if regenerate_summary:+ app.logger.info(f"Regenerating summary for recording {recording_id} after transcript update.")+ thread = threading.Thread(+ target=generate_summary_only_task,+ args=(app.app_context(), recording.id)+ )+ thread.start()++ return jsonify({+ 'success': True,+ 'message': 'Transcript updated successfully.',+ 'recording': recording.to_dict()+ })++ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error updating transcript 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.diff --git a/static/js/app.js b/static/js/app.jsindex b8f00c19..65ab140f 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -218,6 +218,16 @@ document.addEventListener('DOMContentLoaded', async () => {const loadingSuggestions = ref({});const activeSpeakerInput = ref(null);+ // --- Transcript Editing State ---+ const editingSegmentIndex = ref(null);+ const editingSpeakerIndex = ref(null);+ const showEditTextModal = ref(false);+ const editedText = ref('');+ const showAddSpeakerModal = ref(false);+ const newSpeakerName = ref('');+ const newSpeakerIsMe = ref(false);+ const editedTranscriptData = ref(null);+// --- Inline Editing State ---const editingParticipants = ref(false);const editingMeetingDate = ref(false);@@ -1645,7 +1655,12 @@ document.addEventListener('DOMContentLoaded', async () => {const saveSpeakerNames = async () => {if (!selectedRecording.value) return;-++ // If there are transcript edits, save those instead+ if (editedTranscriptData.value) {+ return saveTranscriptEdits();+ }+// Create a filtered speaker map that excludes entries with blank namesconst filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {if (speakerData.name && speakerData.name.trim() !== '') {@@ -1653,7 +1668,7 @@ document.addEventListener('DOMContentLoaded', async () => {}return acc;}, {});-+try {const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {method: 'POST',@@ -1887,6 +1902,171 @@ document.addEventListener('DOMContentLoaded', async () => {}};+ // --- Transcript Editing Functions ---++ const openAddSpeakerModal = () => {+ newSpeakerName.value = '';+ newSpeakerIsMe.value = false;+ showAddSpeakerModal.value = true;+ };++ const closeAddSpeakerModal = () => {+ showAddSpeakerModal.value = false;+ newSpeakerName.value = '';+ newSpeakerIsMe.value = false;+ };++ const addNewSpeaker = () => {+ const name = newSpeakerIsMe.value ? (currentUserName.value || 'Me') : newSpeakerName.value.trim();++ if (!newSpeakerIsMe.value && !name) {+ showToast('Please enter a speaker name', 'fa-exclamation-circle');+ return;+ }++ // Generate new speaker ID+ const existingSpeakerNumbers = modalSpeakers.value+ .map(s => {+ const match = s.match(/^SPEAKER_(\d+)$/);+ return match ? parseInt(match[1]) : -1;+ })+ .filter(n => n >= 0);++ const nextNumber = existingSpeakerNumbers.length > 0+ ? Math.max(...existingSpeakerNumbers) + 1+ : modalSpeakers.value.length;++ const newSpeakerId = `SPEAKER_${String(nextNumber).padStart(2, '0')}`;++ // Add to modalSpeakers+ modalSpeakers.value.push(newSpeakerId);++ // Add to speakerMap with next available color+ const colorIndex = modalSpeakers.value.length - 1;+ speakerMap.value[newSpeakerId] = {+ name: name,+ isMe: newSpeakerIsMe.value,+ color: `speaker-color-${(colorIndex % 8) + 1}`+ };++ // Add to speakerDisplayMap+ speakerDisplayMap.value[newSpeakerId] = newSpeakerId;++ closeAddSpeakerModal();+ showToast('Speaker added successfully', 'fa-check-circle');+ };++ const openSpeakerChangeDropdown = (segmentIndex) => {+ editingSpeakerIndex.value = editingSpeakerIndex.value === segmentIndex ? null : segmentIndex;+ };++ const changeSpeaker = (segmentIndex, newSpeakerId) => {+ if (!selectedRecording.value?.transcription) return;++ try {+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {+ transcriptionData[segmentIndex].speaker = newSpeakerId;+ editedTranscriptData.value = transcriptionData;++ // Update the recording's transcription temporarily for UI update+ selectedRecording.value.transcription = JSON.stringify(transcriptionData);++ editingSpeakerIndex.value = null;+ showToast('Speaker changed. Click "Save Names" to persist changes.', 'fa-info-circle');+ }+ } catch (e) {+ console.error('Error changing speaker:', e);+ showToast('Error changing speaker', 'fa-exclamation-circle');+ }+ };++ const openEditTextModal = (segmentIndex) => {+ if (!selectedRecording.value?.transcription) return;++ try {+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {+ editingSegmentIndex.value = segmentIndex;+ editedText.value = transcriptionData[segmentIndex].sentence || '';+ showEditTextModal.value = true;+ }+ } catch (e) {+ console.error('Error opening text editor:', e);+ showToast('Error opening text editor', 'fa-exclamation-circle');+ }+ };++ const closeEditTextModal = () => {+ showEditTextModal.value = false;+ editingSegmentIndex.value = null;+ editedText.value = '';+ };++ const saveEditedText = () => {+ if (editingSegmentIndex.value === null || !selectedRecording.value?.transcription) return;++ try {+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[editingSegmentIndex.value]) {+ transcriptionData[editingSegmentIndex.value].sentence = editedText.value;+ editedTranscriptData.value = transcriptionData;++ // Update the recording's transcription temporarily for UI update+ selectedRecording.value.transcription = JSON.stringify(transcriptionData);++ closeEditTextModal();+ showToast('Text updated. Click "Save Names" to persist changes.', 'fa-info-circle');+ }+ } catch (e) {+ console.error('Error saving text:', e);+ showToast('Error saving text', 'fa-exclamation-circle');+ }+ };++ const saveTranscriptEdits = async () => {+ if (!selectedRecording.value || !editedTranscriptData.value) {+ return saveSpeakerNames(); // Fall back to regular speaker name save+ }++ try {+ // Save both speaker names and transcript edits+ const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {+ if (speakerData.name && speakerData.name.trim() !== '') {+ acc[speakerId] = speakerData;+ }+ return acc;+ }, {});++ const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcript`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ transcript_data: editedTranscriptData.value,+ speaker_map: filteredSpeakerMap,+ regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value+ })+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.error || 'Failed to update transcript');++ closeSpeakerModal();++ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);+ if (index !== -1) {+ recordings.value[index] = data.recording;+ }+ selectedRecording.value = data.recording;+ editedTranscriptData.value = null;++ showToast('Transcript updated successfully!', 'fa-check-circle');+ } catch (error) {+ console.error('Save Transcript Error:', error);+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle');+ }+ };+const toggleInbox = async (recording) => {if (!recording || !recording.id) return;@@ -5903,6 +6083,26 @@ document.addEventListener('DOMContentLoaded', async () => {closeSpeakerSuggestionsOnClick,autoIdentifySpeakers,isAutoIdentifying,++ // Transcript Editing+ editingSegmentIndex,+ editingSpeakerIndex,+ showEditTextModal,+ editedText,+ showAddSpeakerModal,+ newSpeakerName,+ newSpeakerIsMe,+ editedTranscriptData,+ openAddSpeakerModal,+ closeAddSpeakerModal,+ addNewSpeaker,+ openSpeakerChangeDropdown,+ changeSpeaker,+ openEditTextModal,+ closeEditTextModal,+ saveEditedText,+ saveTranscriptEdits,+formatDuration,openShareModal,closeShareModal,diff --git a/templates/index.html b/templates/index.htmlindex c9a3a337..45b52248 100644--- a/templates/index.html+++ b/templates/index.html@@ -2531,6 +2531,14 @@</div></div></div>++ <!-- Add Speaker Button -->+ <div class="pt-4 border-t border-[var(--border-primary)]">+ <button @click="openAddSpeakerModal" class="w-full px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-center">+ <i class="fas fa-plus mr-2"></i>+ Add Speaker+ </button>+ </div></div><div class="w-2/3 p-6 flex flex-col overflow-hidden"><!-- Audio Player Section -->@@ -2546,11 +2554,34 @@<!-- Transcript Section --><div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent"><div v-if="processedTranscription.isJson">- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2" :data-start-time="segment.startTime">- <p>+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2 group relative" :data-start-time="segment.startTime">+ <p class="flex items-start"><span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId">[${ segment.speaker }]</span>:- <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5">${ segment.sentence }</span>+ <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5 flex-1">${ segment.sentence }</span>++ <!-- Edit buttons (shown on hover) -->+ <span class="ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex items-center space-x-1 flex-shrink-0">+ <!-- Change Speaker Button -->+ <button @click.stop="openSpeakerChangeDropdown(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Change speaker">+ <i class="fas fa-user-edit text-xs"></i>+ </button>+ <!-- Edit Text Button -->+ <button @click.stop="openEditTextModal(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Edit text">+ <i class="fas fa-edit text-xs"></i>+ </button>+ </span></p>++ <!-- Speaker Change Dropdown -->+ <div v-if="editingSpeakerIndex === index" @click.stop class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] shadow-lg">+ <p class="text-xs text-[var(--text-muted)] mb-2">Select new speaker:</p>+ <div class="space-y-1 max-h-48 overflow-y-auto custom-scrollbar">+ <button v-for="speaker in modalSpeakers" :key="speaker" @click="changeSpeaker(index, speaker)" class="w-full text-left px-3 py-2 rounded hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] transition-colors flex items-center space-x-2">+ <div :class="speakerMap[speaker].color" class="w-3 h-3 rounded-full flex-shrink-0"></div>+ <span class="text-sm">${ speakerMap[speaker].name || speaker }</span>+ </button>+ </div>+ </div></div></div><div v-else v-html="highlightedTranscript"></div>@@ -2618,6 +2649,76 @@</div></div>+ <!-- Add Speaker Modal -->+ <div v-if="showAddSpeakerModal" @click="closeAddSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md p-6">+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Add New Speaker</h3>++ <!-- "This is Me" checkbox -->+ <div class="mb-4">+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">+ <input type="checkbox" v-model="newSpeakerIsMe" class="speaker-checkbox">+ <span class="ml-2 select-none">This is Me</span>+ </label>+ </div>++ <!-- Speaker name input (disabled if "This is Me" is checked) -->+ <div class="mb-6">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">+ Speaker Name+ </label>+ <input+ type="text"+ v-model="newSpeakerName"+ :disabled="newSpeakerIsMe"+ :placeholder="newSpeakerIsMe ? 'Me' : 'Enter speaker name...'"+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"+ @keyup.enter="addNewSpeaker"+ >+ </div>++ <!-- Action buttons -->+ <div class="flex justify-end space-x-3">+ <button @click="closeAddSpeakerModal" 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)] transition-colors">+ Cancel+ </button>+ <button @click="addNewSpeaker" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">+ Add Speaker+ </button>+ </div>+ </div>+ </div>++ <!-- Edit Text Modal -->+ <div v-if="showEditTextModal" @click="closeEditTextModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl p-6">+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Edit Transcript Text</h3>++ <!-- Text editor -->+ <div class="mb-6">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">+ Text Content+ </label>+ <textarea+ v-model="editedText"+ rows="6"+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"+ placeholder="Enter transcript text..."+ ></textarea>+ </div>++ <!-- Action buttons -->+ <div class="flex justify-end space-x-3">+ <button @click="closeEditTextModal" 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)] transition-colors">+ Cancel+ </button>+ <button @click="saveEditedText" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">+ Save Changes+ </button>+ </div>+ </div>+ </div>+<!-- Global Error Display --><div v-if="globalError"class="fixed top-4 right-4 bg-[var(--bg-danger)] text-white p-4 rounded-lg shadow-lg z-50 max-w-md">