Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add custom summarization prompt selection to reprocess summary modal
Murtaza Nasir413658a36ebf
diff --git a/src/app.py b/src/app.pyindex 4e980f93..c3788e7f 100644--- a/src/app.py+++ b/src/app.py@@ -2398,12 +2398,13 @@ Title:"""except Exception as e:app.logger.error(f"Error processing chunks for completed recording {recording_id}: {e}")-def generate_summary_only_task(app_context, recording_id):+def generate_summary_only_task(app_context, recording_id, custom_prompt_override=None):"""Generates only a summary for a recording (no title, no JSON response).-+Args:app_context: Flask app contextrecording_id: ID of the recording+ custom_prompt_override: Optional custom prompt that overrides all other prompts (for reprocessing)"""with app_context:recording = db.session.get(Recording, recording_id)@@ -2477,11 +2478,14 @@ def generate_summary_only_task(app_context, recording_id):transcript_text = formatted_transcription[:transcript_limit]language_directive = f"IMPORTANT: You MUST provide the summary in {user_output_language}. The entire response must be in {user_output_language}." if user_output_language else ""-+# Determine which summarization instructions to use- # Priority order: tag custom prompt > user summary prompt > admin default prompt > hardcoded fallback+ # Priority order: custom_prompt_override > tag custom prompt > user summary prompt > admin default prompt > hardcoded fallbacksummarization_instructions = ""- if tag_custom_prompt:+ if custom_prompt_override:+ app.logger.info(f"Using custom prompt override for recording {recording_id} (length: {len(custom_prompt_override)})")+ summarization_instructions = custom_prompt_override+ elif tag_custom_prompt:app.logger.info(f"Using tag custom prompt for recording {recording_id}")summarization_instructions = tag_custom_promptelif user_summary_prompt:@@ -4989,7 +4993,17 @@ def reprocess_summary(recording_id):# Check if OpenRouter client is availableif client is None:return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503-++ # Get custom prompt from request if provided+ data = request.get_json() or {}+ custom_prompt = data.get('custom_prompt', '').strip() if data.get('custom_prompt') else None++ # Debug logging+ if custom_prompt:+ app.logger.info(f"Received custom prompt override for recording {recording_id} (length: {len(custom_prompt)})")+ else:+ app.logger.info(f"No custom prompt override provided for recording {recording_id}, will use default priority")+# Set status to SUMMARIZING and clear existing summaryrecording.summary = Nonerecording.status = 'SUMMARIZING'@@ -5002,16 +5016,17 @@ def reprocess_summary(recording_id):# Refresh the recording object to ensure it has the latest committed datadb.session.refresh(recording)- app.logger.info(f"Starting summary reprocessing for recording {recording_id}")-+ app.logger.info(f"Starting summary reprocessing for recording {recording_id}" ++ (f" with custom prompt (length: {len(custom_prompt)})" if custom_prompt else ""))+# Start summary generation in background thread- def reprocess_summary_task(app_context, recording_id):+ def reprocess_summary_task(app_context, recording_id, custom_prompt_override=None):app.logger.info(f"Starting summary reprocessing for recording {recording_id} using generate_summary_only_task")- generate_summary_only_task(app_context, recording_id)-+ generate_summary_only_task(app_context, recording_id, custom_prompt_override=custom_prompt_override)+thread = threading.Thread(target=reprocess_summary_task,- args=(app.app_context(), recording.id)+ args=(app.app_context(), recording.id, custom_prompt))thread.start()diff --git a/static/js/app.js b/static/js/app.jsindex 6e6c19de..9e7c9901 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -204,6 +204,9 @@ document.addEventListener('DOMContentLoaded', async () => {min_speakers: null,max_speakers: null});+ const summaryReprocessPromptSource = ref('default'); // 'default', 'tag', or 'custom'+ const summaryReprocessSelectedTagId = ref('');+ const summaryReprocessCustomPrompt = ref('');const speakerMap = ref({});const regenerateSummaryAfterSpeakerUpdate = ref(true);const speakerSuggestions = ref({});@@ -1161,26 +1164,45 @@ document.addEventListener('DOMContentLoaded', async () => {showReprocessModal.value = false;reprocessType.value = null;reprocessRecording.value = null;+ // Reset summary reprocess options+ summaryReprocessPromptSource.value = 'default';+ summaryReprocessSelectedTagId.value = '';+ summaryReprocessCustomPrompt.value = '';};const executeReprocess = async () => {if (!reprocessRecording.value || !reprocessType.value) return;-+const recordingId = reprocessRecording.value.id;const type = reprocessType.value;-- // Close the modal first++ // Save values before closing the modal (cancelReprocess resets them)+ const savedAsrOptions = {+ language: asrReprocessOptions.language,+ min_speakers: asrReprocessOptions.min_speakers,+ max_speakers: asrReprocessOptions.max_speakers+ };+ const savedSummaryPromptSource = summaryReprocessPromptSource.value;+ const savedSummaryTagId = summaryReprocessSelectedTagId.value;+ const savedSummaryCustomPrompt = summaryReprocessCustomPrompt.value;++ // Close the modalcancelReprocess();-+if (type === 'transcription') {await performReprocessTranscription(- recordingId,- asrReprocessOptions.language,- asrReprocessOptions.min_speakers,- asrReprocessOptions.max_speakers+ recordingId,+ savedAsrOptions.language,+ savedAsrOptions.min_speakers,+ savedAsrOptions.max_speakers);} else if (type === 'summary') {- await performReprocessSummary(recordingId);+ await performReprocessSummary(+ recordingId,+ savedSummaryPromptSource,+ savedSummaryTagId,+ savedSummaryCustomPrompt+ );}};@@ -1240,16 +1262,38 @@ document.addEventListener('DOMContentLoaded', async () => {}};- const performReprocessSummary = async (recordingId) => {+ const performReprocessSummary = async (recordingId, promptSource, selectedTagId, customPrompt) => {if (!recordingId) {setGlobalError('No recording ID provided for reprocessing.');return;}-+try {+ // Prepare payload with custom prompt data+ const payload = {};++ console.log('[Reprocess Summary] Prompt source:', promptSource);+ console.log('[Reprocess Summary] Selected tag ID:', selectedTagId);+ console.log('[Reprocess Summary] Custom prompt:', customPrompt);++ if (promptSource === 'tag' && selectedTagId) {+ const selectedTag = availableTags.value.find(t => t.id == selectedTagId);+ if (selectedTag && selectedTag.custom_prompt) {+ payload.custom_prompt = selectedTag.custom_prompt;+ console.log('[Reprocess Summary] Using tag prompt:', selectedTag.name, 'Length:', selectedTag.custom_prompt.length);+ }+ } else if (promptSource === 'custom' && customPrompt && customPrompt.trim()) {+ payload.custom_prompt = customPrompt.trim();+ console.log('[Reprocess Summary] Using custom prompt, Length:', payload.custom_prompt.length);+ }+ // If 'default' is selected or no custom prompt, payload will be empty and backend will use default++ console.log('[Reprocess Summary] Final payload:', payload);+const response = await fetch(`/recording/${recordingId}/reprocess_summary`, {method: 'POST',- headers: { 'Content-Type': 'application/json' }+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)});const data = await response.json();@@ -2671,6 +2715,21 @@ document.addEventListener('DOMContentLoaded', async () => {filterTags.value = [tag.id];applyAdvancedFilters();};++ // Computed property for tags with custom prompts (for reprocess modal)+ const tagsWithCustomPrompts = computed(() => {+ return availableTags.value.filter(tag => tag.custom_prompt && tag.custom_prompt.trim());+ });++ // Helper function to get tag prompt preview+ const getTagPromptPreview = (tagId) => {+ const tag = availableTags.value.find(t => t.id == tagId);+ if (!tag || !tag.custom_prompt) return '';+ // Return first 100 characters+ return tag.custom_prompt.length > 100+ ? tag.custom_prompt.substring(0, 100) + '...'+ : tag.custom_prompt;+ };const clearTagFilter = () => {searchQuery.value = '';clearAllFilters();@@ -5472,6 +5531,11 @@ document.addEventListener('DOMContentLoaded', async () => {cancelReprocess,executeReprocess,asrReprocessOptions,+ summaryReprocessPromptSource,+ summaryReprocessSelectedTagId,+ summaryReprocessCustomPrompt,+ tagsWithCustomPrompts,+ getTagPromptPreview,showSpeakerModal,showShareModal,recordingToShare,diff --git a/templates/index.html b/templates/index.htmlindex 7700d22f..0b34ddc0 100644--- a/templates/index.html+++ b/templates/index.html@@ -2205,7 +2205,54 @@<input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block 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)]" :placeholder="t('form.optional')"></div></div>-++ <!-- Custom Prompt Options for Summary Reprocessing -->+ <div v-if="reprocessType === 'summary'" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">+ <h4 class="text-md font-semibold text-[var(--text-secondary)]">Custom Summarization Prompt</h4>++ <!-- Prompt Source Selection -->+ <div>+ <label class="block text-sm font-medium text-[var(--text-muted)] mb-2">Prompt Source</label>+ <div class="space-y-2">+ <label class="flex items-center space-x-2 cursor-pointer">+ <input type="radio" v-model="summaryReprocessPromptSource" value="default" class="text-[var(--text-accent)]" name="promptSource">+ <span class="text-sm text-[var(--text-secondary)]">Use default prompt</span>+ </label>+ <label class="flex items-center space-x-2 cursor-pointer" v-if="tagsWithCustomPrompts.length > 0">+ <input type="radio" v-model="summaryReprocessPromptSource" value="tag" class="text-[var(--text-accent)]" name="promptSource">+ <span class="text-sm text-[var(--text-secondary)]">Use prompt from tag</span>+ </label>+ <label class="flex items-center space-x-2 cursor-pointer">+ <input type="radio" v-model="summaryReprocessPromptSource" value="custom" class="text-[var(--text-accent)]" name="promptSource">+ <span class="text-sm text-[var(--text-secondary)]">Enter custom prompt</span>+ </label>+ </div>+ </div>++ <!-- Tag Selection (shown when 'tag' is selected) -->+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length > 0">+ <label for="reprocess-tag-select" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Select Tag</label>+ <select id="reprocess-tag-select" v-model="summaryReprocessSelectedTagId" 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)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">+ <option value="">Select a tag...</option>+ <option v-for="tag in tagsWithCustomPrompts" :key="tag.id" :value="tag.id">${ tag.name }</option>+ </select>+ <div v-if="summaryReprocessSelectedTagId" class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded text-xs text-[var(--text-muted)] max-h-20 overflow-y-auto">+ <strong>Preview:</strong> ${ getTagPromptPreview(summaryReprocessSelectedTagId) }+ </div>+ </div>++ <!-- Custom Prompt Textarea (shown when 'custom' is selected) -->+ <div v-if="summaryReprocessPromptSource === 'custom'">+ <label for="reprocess-custom-prompt" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Custom Prompt</label>+ <textarea id="reprocess-custom-prompt" v-model="summaryReprocessCustomPrompt" rows="4" 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)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Enter your custom summarization instructions..."></textarea>+ </div>++ <!-- Info message when no tags with custom prompts exist -->+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length === 0" class="text-xs text-[var(--text-muted)] italic">+ No tags with custom prompts available. Create tags with custom prompts in the Account Settings.+ </div>+ </div>+<div class="flex items-start space-x-3"><div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5"><i class="fas fa-clock text-blue-600 text-xs"></i>