Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
templates
Murtaza Nasira7890fed7b18
diff --git a/src/app.py b/src/app.pyindex 08ea0d0b..c0d3fccf 100644--- a/src/app.py+++ b/src/app.py@@ -1,7 +1,7 @@# Speakr - Audio Transcription and Summarization Appimport osimport sys-from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for, flash, Response+from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for, flash, Response, make_responsefrom urllib.parse import urlparse, urljoin, quotefrom email.utils import encode_rfc2231try:@@ -1195,6 +1195,31 @@ class TranscriptChunk(db.Model):'created_at': self.created_at.isoformat() if self.created_at else None}+class TranscriptTemplate(db.Model):+ """Stores user-defined templates for transcript formatting."""+ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)+ name = db.Column(db.String(100), nullable=False)+ template = db.Column(db.Text, nullable=False)+ description = db.Column(db.String(500), nullable=True)+ is_default = db.Column(db.Boolean, default=False)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Relationships+ user = db.relationship('User', backref=db.backref('transcript_templates', lazy=True, cascade='all, delete-orphan'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'name': self.name,+ 'template': self.template,+ 'description': self.description,+ 'is_default': self.is_default,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None+ }+class InquireSession(db.Model):"""Tracks inquire mode sessions and their filtering criteria."""id = db.Column(db.Integer, primary_key=True)@@ -3124,6 +3149,117 @@ def delete_all_speakers():app.logger.error(f"Error deleting all speakers: {e}")return jsonify({'error': str(e)}), 500[email protected]('/recording/<int:recording_id>/download/transcript')+@login_required+def download_transcript_with_template(recording_id):+ """Download transcript with custom template formatting."""+ try:+ import re+ from datetime import timedelta++ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to access this recording'}), 403++ if not recording.transcription:+ return jsonify({'error': 'No transcription available for this recording'}), 400++ # Get template ID from query params+ template_id = request.args.get('template_id', type=int)++ # Get the template+ if template_id:+ template = TranscriptTemplate.query.filter_by(+ id=template_id,+ user_id=current_user.id+ ).first()+ else:+ # Use default template+ template = TranscriptTemplate.query.filter_by(+ user_id=current_user.id,+ is_default=True+ ).first()++ # If no template found, use a basic format+ if not template:+ template_format = "[{{speaker}}]: {{text}}"+ else:+ template_format = template.template++ # Helper functions for formatting+ def format_time(seconds):+ """Format seconds to HH:MM:SS"""+ if seconds is None:+ return "00:00:00"+ td = timedelta(seconds=seconds)+ hours = int(td.total_seconds() // 3600)+ minutes = int((td.total_seconds() % 3600) // 60)+ secs = int(td.total_seconds() % 60)+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"++ def format_srt_time(seconds):+ """Format seconds to SRT format HH:MM:SS,mmm"""+ if seconds is None:+ return "00:00:00,000"+ td = timedelta(seconds=seconds)+ hours = int(td.total_seconds() // 3600)+ minutes = int((td.total_seconds() % 3600) // 60)+ secs = int(td.total_seconds() % 60)+ millis = int((td.total_seconds() % 1) * 1000)+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"++ # Parse transcription JSON+ try:+ transcription_data = json.loads(recording.transcription)+ except:+ return jsonify({'error': 'Invalid transcription format'}), 400++ # Generate formatted transcript+ output_lines = []+ for index, segment in enumerate(transcription_data, 1):+ line = template_format++ # Replace variables+ replacements = {+ '{{index}}': str(index),+ '{{speaker}}': segment.get('speaker', 'Unknown'),+ '{{text}}': segment.get('sentence', ''),+ '{{start_time}}': format_time(segment.get('start_time')),+ '{{end_time}}': format_time(segment.get('end_time')),+ }++ for key, value in replacements.items():+ line = line.replace(key, value)++ # Handle filters+ # Upper case filter+ line = re.sub(r'{{(.*?)\|upper}}', lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(), line)+ # SRT time filter+ line = re.sub(r'{{start_time\|srt}}', format_srt_time(segment.get('start_time')), line)+ line = re.sub(r'{{end_time\|srt}}', format_srt_time(segment.get('end_time')), line)++ output_lines.append(line)++ # Join lines+ formatted_transcript = '\n'.join(output_lines)++ # Create response+ response = make_response(formatted_transcript)+ filename = f"{recording.title or 'transcript'}_{template.name if template else 'formatted'}.txt"+ filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)+ response.headers['Content-Type'] = 'text/plain; charset=utf-8'+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'++ return response++ except Exception as e:+ app.logger.error(f"Error downloading transcript: {e}")+ return jsonify({'error': 'Failed to generate transcript download'}), 500+@app.route('/recording/<int:recording_id>/download/summary')@login_requireddef download_summary_word(recording_id):@@ -4673,6 +4809,138 @@ def admin_get_stats():'total_queries': total_queries})+# --- Transcript Template Routes ---[email protected]('/api/transcript-templates', methods=['GET'])+@login_required+def get_transcript_templates():+ """Get all transcript templates for the current user."""+ templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).all()+ return jsonify([template.to_dict() for template in templates])+[email protected]('/api/transcript-templates', methods=['POST'])+@login_required+def create_transcript_template():+ """Create a new transcript template."""+ data = request.json+ if not data or not data.get('name') or not data.get('template'):+ return jsonify({'error': 'Name and template are required'}), 400++ # If this is set as default, unset other defaults+ if data.get('is_default'):+ TranscriptTemplate.query.filter_by(+ user_id=current_user.id,+ is_default=True+ ).update({'is_default': False})++ template = TranscriptTemplate(+ user_id=current_user.id,+ name=data['name'],+ template=data['template'],+ description=data.get('description'),+ is_default=data.get('is_default', False)+ )++ db.session.add(template)+ db.session.commit()++ return jsonify(template.to_dict()), 201+[email protected]('/api/transcript-templates/<int:template_id>', methods=['PUT'])+@login_required+def update_transcript_template(template_id):+ """Update an existing transcript template."""+ template = TranscriptTemplate.query.filter_by(+ id=template_id,+ user_id=current_user.id+ ).first()++ if not template:+ return jsonify({'error': 'Template not found'}), 404++ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ # If this is set as default, unset other defaults+ if data.get('is_default'):+ TranscriptTemplate.query.filter_by(+ user_id=current_user.id,+ is_default=True+ ).update({'is_default': False})++ template.name = data.get('name', template.name)+ template.template = data.get('template', template.template)+ template.description = data.get('description', template.description)+ template.is_default = data.get('is_default', template.is_default)+ template.updated_at = datetime.utcnow()++ db.session.commit()++ return jsonify(template.to_dict())+[email protected]('/api/transcript-templates/<int:template_id>', methods=['DELETE'])+@login_required+def delete_transcript_template(template_id):+ """Delete a transcript template."""+ template = TranscriptTemplate.query.filter_by(+ id=template_id,+ user_id=current_user.id+ ).first()++ if not template:+ return jsonify({'error': 'Template not found'}), 404++ db.session.delete(template)+ db.session.commit()++ return jsonify({'success': True})+[email protected]('/api/transcript-templates/create-defaults', methods=['POST'])+@login_required+def create_default_templates():+ """Create default templates for the user if they don't have any."""+ existing_templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).count()++ if existing_templates > 0:+ return jsonify({'message': 'User already has templates'}), 200++ # Default template 1: Simple with timestamps+ template1 = TranscriptTemplate(+ user_id=current_user.id,+ name="Simple with Timestamps",+ template="[{{start_time}} - {{end_time}}] {{speaker}}: {{text}}",+ description="Basic format with timestamps and speaker names",+ is_default=True+ )++ # Default template 2: Screenplay format+ template2 = TranscriptTemplate(+ user_id=current_user.id,+ name="Screenplay",+ template="{{speaker|upper}}\n({{start_time}})\n{{text}}\n",+ description="Screenplay-style format with speaker in caps",+ is_default=False+ )++ # Default template 3: Subtitle format+ template3 = TranscriptTemplate(+ user_id=current_user.id,+ name="SRT Subtitle",+ template="{{index}}\n{{start_time|srt}} --> {{end_time|srt}}\n{{text}}\n",+ description="SRT subtitle format for video editing",+ is_default=False+ )++ db.session.add(template1)+ db.session.add(template2)+ db.session.add(template3)+ db.session.commit()++ return jsonify({+ 'success': True,+ 'templates': [template1.to_dict(), template2.to_dict(), template3.to_dict()]+ }), 201+@app.route('/admin/settings', methods=['GET'])@login_requireddef admin_get_settings():diff --git a/static/js/app.js b/static/js/app.jsindex d9ad84e0..f6b69310 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -4163,6 +4163,118 @@ document.addEventListener('DOMContentLoaded', async () => {}};+ const downloadTranscript = async () => {+ if (!selectedRecording.value || !selectedRecording.value.transcription) {+ showToast('No transcription available to download.', 'fa-exclamation-circle');+ return;+ }++ try {+ // First, fetch available templates+ const templatesResponse = await fetch('/api/transcript-templates');+ let templates = [];+ if (templatesResponse.ok) {+ templates = await templatesResponse.json();+ }++ // If there are templates, show a selection dialog+ let templateId = null;+ if (templates.length > 0) {+ // Create a simple modal for template selection+ const modal = document.createElement('div');+ modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';+ modal.innerHTML = `+ <div class="bg-[var(--bg-secondary)] rounded-lg p-6 max-w-md w-full mx-4">+ <h3 class="text-lg font-semibold mb-4">Select Template</h3>+ <div class="space-y-2 max-h-60 overflow-y-auto">+ ${templates.map(t => `+ <button class="template-option w-full text-left p-3 rounded border border-[var(--border-primary)] hover:bg-[var(--bg-tertiary)] ${t.is_default ? 'ring-2 ring-[var(--ring-focus)]' : ''}" data-template-id="${t.id}">+ <div class="font-medium">${t.name}</div>+ ${t.description ? `<div class="text-sm text-[var(--text-muted)]">${t.description}</div>` : ''}+ ${t.is_default ? '<div class="text-xs text-[var(--text-accent)] mt-1"><i class="fas fa-star mr-1"></i>Default</div>' : ''}+ </button>+ `).join('')}+ </div>+ <div class="mt-4 flex gap-2">+ <button class="cancel-btn px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded hover:bg-[var(--bg-accent-light)]">Cancel</button>+ <button class="download-without-template-btn px-4 py-2 bg-[var(--bg-accent)] text-white rounded hover:bg-[var(--bg-accent-hover)]">Download without template</button>+ </div>+ </div>+ `;+ document.body.appendChild(modal);++ // Wait for user selection+ await new Promise((resolve) => {+ modal.querySelectorAll('.template-option').forEach(btn => {+ btn.addEventListener('click', () => {+ templateId = btn.dataset.templateId;+ modal.remove();+ resolve();+ });+ });++ modal.querySelector('.cancel-btn').addEventListener('click', () => {+ modal.remove();+ resolve();+ });++ modal.querySelector('.download-without-template-btn').addEventListener('click', () => {+ templateId = null;+ modal.remove();+ resolve();+ });++ modal.addEventListener('click', (e) => {+ if (e.target === modal) {+ modal.remove();+ resolve();+ }+ });+ });++ if (templateId === undefined) {+ // User cancelled+ return;+ }+ }++ // Download the transcript with the selected template+ const url = templateId+ ? `/recording/${selectedRecording.value.id}/download/transcript?template_id=${templateId}`+ : `/recording/${selectedRecording.value.id}/download/transcript`;++ const response = await fetch(url);+ if (!response.ok) {+ throw new Error('Failed to download transcript');+ }++ const blob = await response.blob();+ const contentDisposition = response.headers.get('content-disposition');+ let filename = 'transcript.txt';+ if (contentDisposition) {+ const matches = contentDisposition.match(/filename="([^"]+)"/);+ if (matches && matches[1]) {+ filename = matches[1];+ }+ }++ // Create download link+ const downloadUrl = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = downloadUrl;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(downloadUrl);++ showToast('Transcript downloaded successfully!');+ } catch (error) {+ console.error('Error downloading transcript:', error);+ showToast('Failed to download transcript', 'fa-exclamation-circle');+ }+ };+const downloadNotes = async () => {if (!selectedRecording.value || !selectedRecording.value.notes) {showToast('No notes available to download.', 'fa-exclamation-circle');@@ -5098,7 +5210,7 @@ document.addEventListener('DOMContentLoaded', async () => {autoSaveNotes, autoSaveSummary,sendChatMessage, isChatScrolledToBottom, scrollChatToBottom, startColumnResize, handleChatKeydown, seekAudio, seekAudioFromEvent, onPlayerVolumeChange,showToast, copyMessage, copyTranscription, copySummary, copyNotes,- downloadSummary, downloadNotes, downloadChat,+ downloadSummary, downloadTranscript, downloadNotes, downloadChat,toggleInbox, toggleHighlight,toggleTranscriptionViewMode,reprocessTranscription,diff --git a/static/locales/de.json b/static/locales/de.jsonindex b05b672b..770c826a 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -91,7 +91,25 @@"about": "Über","customPrompts": "Benutzerdefinierte Prompts","sharedTranscripts": "Geteilte Transkripte",- "tagManagement": "Tag-Verwaltung"+ "speakersManagement": "Sprecher-Verwaltung",+ "tagManagement": "Tag-Verwaltung",+ "transcriptTemplates": "Transkript-Vorlagen"+ },+ "transcriptTemplates": {+ "title": "Transkript-Vorlagen",+ "description": "Anpassen, wie Transkripte für Download und Export formatiert werden.",+ "createNew": "Vorlage Erstellen",+ "availableTemplates": "Verfügbare Vorlagen",+ "createDefaults": "Standardvorlagen Erstellen",+ "templateName": "Vorlagenname",+ "template": "Vorlage",+ "availableVars": "Verfügbare Variablen",+ "filters": "Filter: |upper für Großbuchstaben, |srt für Untertitelformat",+ "setDefault": "Als Standardvorlage festlegen",+ "save": "Speichern",+ "cancel": "Abbrechen",+ "delete": "Löschen",+ "selectOrCreate": "Wählen Sie eine Vorlage zum Bearbeiten oder erstellen Sie eine neue"},"admin": {"title": "Administration",diff --git a/static/locales/en.json b/static/locales/en.jsonindex 90938294..579e8089 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -92,7 +92,24 @@"customPrompts": "Custom Prompts","sharedTranscripts": "Shared Transcripts","speakersManagement": "Speakers Management",- "tagManagement": "Tag Management"+ "tagManagement": "Tag Management",+ "transcriptTemplates": "Transcript Templates"+ },+ "transcriptTemplates": {+ "title": "Transcript Templates",+ "description": "Customize how transcripts are formatted for download and export.",+ "createNew": "Create Template",+ "availableTemplates": "Available Templates",+ "createDefaults": "Create Default Templates",+ "templateName": "Template Name",+ "template": "Template",+ "availableVars": "Available Variables",+ "filters": "Filters: |upper for uppercase, |srt for subtitle time format",+ "setDefault": "Set as default template",+ "save": "Save",+ "cancel": "Cancel",+ "delete": "Delete",+ "selectOrCreate": "Select a template to edit or create a new one"},"admin": {"title": "Admin",diff --git a/static/locales/es.json b/static/locales/es.jsonindex f89c81bf..a0214033 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -91,7 +91,25 @@"about": "Acerca de","customPrompts": "Prompts Personalizados","sharedTranscripts": "Transcripciones Compartidas",- "tagManagement": "Gestión de Etiquetas"+ "speakersManagement": "Gestión de Hablantes",+ "tagManagement": "Gestión de Etiquetas",+ "transcriptTemplates": "Plantillas de Transcripción"+ },+ "transcriptTemplates": {+ "title": "Plantillas de Transcripción",+ "description": "Personaliza cómo se formatean las transcripciones para descarga y exportación.",+ "createNew": "Crear Plantilla",+ "availableTemplates": "Plantillas Disponibles",+ "createDefaults": "Crear Plantillas Predeterminadas",+ "templateName": "Nombre de Plantilla",+ "template": "Plantilla",+ "availableVars": "Variables Disponibles",+ "filters": "Filtros: |upper para mayúsculas, |srt para formato de subtítulos",+ "setDefault": "Establecer como plantilla predeterminada",+ "save": "Guardar",+ "cancel": "Cancelar",+ "delete": "Eliminar",+ "selectOrCreate": "Selecciona una plantilla para editar o crea una nueva"},"admin": {"title": "Administración",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 3f515852..737d74b0 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -91,7 +91,25 @@"about": "À Propos","customPrompts": "Invites Personnalisées","sharedTranscripts": "Transcriptions Partagées",- "tagManagement": "Gestion des Étiquettes"+ "speakersManagement": "Gestion des Locuteurs",+ "tagManagement": "Gestion des Étiquettes",+ "transcriptTemplates": "Modèles de Transcription"+ },+ "transcriptTemplates": {+ "title": "Modèles de Transcription",+ "description": "Personnalisez le formatage des transcriptions pour le téléchargement et l'exportation.",+ "createNew": "Créer un Modèle",+ "availableTemplates": "Modèles Disponibles",+ "createDefaults": "Créer des Modèles par Défaut",+ "templateName": "Nom du Modèle",+ "template": "Modèle",+ "availableVars": "Variables Disponibles",+ "filters": "Filtres: |upper pour majuscules, |srt pour format sous-titres",+ "setDefault": "Définir comme modèle par défaut",+ "save": "Enregistrer",+ "cancel": "Annuler",+ "delete": "Supprimer",+ "selectOrCreate": "Sélectionnez un modèle à éditer ou créez-en un nouveau"},"admin": {"title": "Administration",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex cc1d27fb..1b14c7b8 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -109,7 +109,25 @@"about": "关于","customPrompts": "自定义提示","sharedTranscripts": "共享转录",- "tagManagement": "标签管理"+ "speakersManagement": "发言人管理",+ "tagManagement": "标签管理",+ "transcriptTemplates": "转录模板"+ },+ "transcriptTemplates": {+ "title": "转录模板",+ "description": "自定义转录的下载和导出格式。",+ "createNew": "创建模板",+ "availableTemplates": "可用模板",+ "createDefaults": "创建默认模板",+ "templateName": "模板名称",+ "template": "模板",+ "availableVars": "可用变量",+ "filters": "过滤器:|upper 转大写,|srt 字幕格式",+ "setDefault": "设为默认模板",+ "save": "保存",+ "cancel": "取消",+ "delete": "删除",+ "selectOrCreate": "选择要编辑的模板或创建新模板"},"admin": {"title": "管理员",diff --git a/templates/account.html b/templates/account.htmlindex 22178989..583ee9b1 100644--- a/templates/account.html+++ b/templates/account.html@@ -180,6 +180,39 @@applyTheme();</script><style>+ /* Horizontal scrollbar for tab navigation */+ .tab-nav {+ scrollbar-width: thin;+ scrollbar-color: var(--border-secondary) transparent;+ }++ .tab-nav::-webkit-scrollbar {+ height: 6px;+ }++ .tab-nav::-webkit-scrollbar-track {+ background: transparent;+ }++ .tab-nav::-webkit-scrollbar-thumb {+ background-color: var(--border-secondary);+ border-radius: 3px;+ }++ .tab-nav::-webkit-scrollbar-thumb:hover {+ background-color: var(--border-accent);+ }++ /* Ensure tabs don't shrink below their content */+ .tab-nav a {+ flex-shrink: 0;+ }++ /* Add some padding at the end of scrollable area */+ .tab-nav > div {+ padding-right: 1rem;+ }+/* Custom scrollbar styling for Speakers Management */#content-speakers .overflow-y-auto::-webkit-scrollbar {width: 8px;@@ -273,7 +306,9 @@<main class="flex-grow"><div class="bg-[var(--bg-secondary)] p-4 sm:p-6 lg:p-8 rounded-xl shadow-lg border border-[var(--border-primary)]"><div class="mb-6 border-b border-[var(--border-primary)] sm:border-b">- <nav class="tab-nav -mb-px flex flex-col sm:flex-row sm:space-x-8" aria-label="Tabs">+ <div class="relative">+ <nav class="tab-nav -mb-px flex overflow-x-auto scrollbar-thin scrollbar-thumb-[var(--border-secondary)] scrollbar-track-transparent" aria-label="Tabs" style="scrollbar-width: thin;">+ <div class="flex flex-col sm:flex-row sm:space-x-4 min-w-full sm:min-w-0"><a href="#" id="tab-account" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b-2 sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-[var(--border-accent)] text-[var(--text-accent)] bg-[var(--bg-tertiary)] sm:bg-transparent"><i class="fas fa-user-circle mr-2"></i><span data-i18n="account.title">Account Information</span></a>@@ -289,10 +324,15 @@<a href="#" id="tab-tags" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent"><i class="fas fa-tags mr-2"></i><span data-i18n="accountTabs.tagManagement">Tag Management</span></a>+ <a href="#" id="tab-templates" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">+ <i class="fas fa-file-alt mr-2"></i><span data-i18n="accountTabs.transcriptTemplates">Transcript Templates</span>+ </a><a href="#" id="tab-about" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent"><i class="fas fa-info-circle mr-2"></i><span data-i18n="accountTabs.about">About</span></a>- </nav>+ </div>+ </nav>+ </div></div><div id="content-account">@@ -578,6 +618,99 @@</div></div>+ <div id="content-templates" class="hidden">+ <div class="space-y-6">+ <!-- Templates Header -->+ <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">+ <div>+ <h2 class="text-2xl font-semibold text-[var(--text-primary)]" data-i18n="transcriptTemplates.title">Transcript Templates</h2>+ <p class="text-[var(--text-secondary)]" data-i18n="transcriptTemplates.description">Customize how transcripts are formatted for download and export.</p>+ </div>+ <button id="createTemplateBtn" class="px-4 py-2 bg-[var(--bg-accent)] text-white rounded-md hover:bg-[var(--bg-accent-hover)] flex items-center gap-2">+ <i class="fas fa-plus"></i>+ <span data-i18n="transcriptTemplates.createNew">Create Template</span>+ </button>+ </div>++ <!-- Templates Grid -->+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">+ <!-- Templates List (Left) -->+ <div class="lg:col-span-1">+ <div class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-4">+ <h3 class="text-sm font-medium text-[var(--text-secondary)] mb-3" data-i18n="transcriptTemplates.availableTemplates">Available Templates</h3>+ <div id="templatesList" class="space-y-2">+ <!-- Templates will be populated here -->+ </div>+ <button id="createDefaultTemplatesBtn" class="mt-4 w-full px-3 py-2 text-sm bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-accent-light)] transition-colors">+ <i class="fas fa-magic mr-2"></i>+ <span data-i18n="transcriptTemplates.createDefaults">Create Default Templates</span>+ </button>+ </div>+ </div>++ <!-- Template Editor (Right) -->+ <div class="lg:col-span-2">+ <div id="templateEditor" class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-6 hidden">+ <form id="templateForm" class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="transcriptTemplates.templateName">Template Name</label>+ <input type="text" id="templateName" class="w-full px-3 py-2 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]" required>+ </div>++ <div>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="transcriptTemplates.description">Description</label>+ <input type="text" id="templateDescription" class="w-full px-3 py-2 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ </div>++ <div>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="transcriptTemplates.template">Template</label>+ <textarea id="templateContent" rows="6" class="w-full px-3 py-2 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] font-mono text-sm" required></textarea>++ <!-- Available Variables -->+ <div class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md">+ <p class="text-xs font-medium text-[var(--text-secondary)] mb-2" data-i18n="transcriptTemplates.availableVars">Available Variables:</p>+ <div class="flex flex-wrap gap-2">+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded">{{index}}</code>+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded">{{speaker}}</code>+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded">{{text}}</code>+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded">{{start_time}}</code>+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded">{{end_time}}</code>+ </div>+ <p class="text-xs text-[var(--text-muted)] mt-2" data-i18n="transcriptTemplates.filters">Filters: |upper for uppercase, |srt for subtitle time format</p>+ </div>+ </div>++ <div class="flex items-center">+ <input type="checkbox" id="templateIsDefault" class="mr-2">+ <label for="templateIsDefault" class="text-sm text-[var(--text-secondary)]" data-i18n="transcriptTemplates.setDefault">Set as default template</label>+ </div>++ <div class="flex gap-3">+ <button type="submit" class="px-4 py-2 bg-[var(--bg-accent)] text-white rounded-md hover:bg-[var(--bg-accent-hover)]">+ <i class="fas fa-save mr-2"></i>+ <span data-i18n="transcriptTemplates.save">Save</span>+ </button>+ <button type="button" id="cancelTemplateBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-secondary)]">+ <span data-i18n="transcriptTemplates.cancel">Cancel</span>+ </button>+ <button type="button" id="deleteTemplateBtn" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 hidden">+ <i class="fas fa-trash mr-2"></i>+ <span data-i18n="transcriptTemplates.delete">Delete</span>+ </button>+ </div>+ </form>+ </div>++ <!-- Empty State -->+ <div id="templateEmptyState" class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-12 text-center">+ <i class="fas fa-file-alt text-4xl text-[var(--text-muted)] mb-4"></i>+ <p class="text-[var(--text-muted)]" data-i18n="transcriptTemplates.selectOrCreate">Select a template to edit or create a new one</p>+ </div>+ </div>+ </div>+ </div>+ </div>+<div id="content-about" class="hidden"><div class="space-y-8"><!-- Header Section -->@@ -987,25 +1120,28 @@const tabPrompts = document.getElementById('tab-prompts');const tabShares = document.getElementById('tab-shares');const tabTags = document.getElementById('tab-tags');+ const tabTemplates = document.getElementById('tab-templates');const tabAbout = document.getElementById('tab-about');const contentAccount = document.getElementById('content-account');const contentPrompts = document.getElementById('content-prompts');const contentShares = document.getElementById('content-shares');const contentSpeakers = document.getElementById('content-speakers');const contentTags = document.getElementById('content-tags');+ const contentTemplates = document.getElementById('content-templates');const contentAbout = document.getElementById('content-about');const sharesContainer = document.getElementById('shares-container');-+// Simplified tab switchingconst tabSpeakers = document.getElementById('tab-speakers');-+const tabs = [{ tab: tabAccount, content: contentAccount, name: 'account' },{ tab: tabPrompts, content: contentPrompts, name: 'prompts' },{ tab: tabShares, content: contentShares, name: 'shares' },{ tab: tabSpeakers, content: contentSpeakers, name: 'speakers' },{ tab: tabTags, content: contentTags, name: 'tags' },+ { tab: tabTemplates, content: contentTemplates, name: 'templates' },{ tab: tabAbout, content: contentAbout, name: 'about' }];@@ -1031,6 +1167,8 @@loadShares();} else if (targetName === 'tags') {loadTags();+ } else if (targetName === 'templates') {+ loadTemplates();} else if (targetName === 'about') {loadSystemInfo();}@@ -1056,6 +1194,10 @@switchToTab('tags');}+ function showTemplatesTab() {+ switchToTab('templates');+ }+function showAboutTab() {switchToTab('about');}@@ -1085,6 +1227,11 @@showTagsTab();});+ tabTemplates.addEventListener('click', (e) => {+ e.preventDefault();+ showTemplatesTab();+ });+tabAbout.addEventListener('click', (e) => {e.preventDefault();showAboutTab();@@ -2223,6 +2370,247 @@localStorage.setItem('preferredLanguage', newUILanguage);}});++ // Template Management Functions+ let templates = [];+ let currentTemplate = null;+ let isEditingTemplate = false;++ async function loadTemplates() {+ try {+ const response = await fetch('/api/transcript-templates');+ if (!response.ok) {+ throw new Error('Failed to load templates');+ }+ templates = await response.json();++ // Create default templates if none exist+ if (templates.length === 0) {+ document.getElementById('createDefaultTemplatesBtn').style.display = 'block';+ } else {+ document.getElementById('createDefaultTemplatesBtn').style.display = 'none';+ }++ renderTemplatesList();+ } catch (error) {+ console.error('Error loading templates:', error);+ showToast('Failed to load templates', 'error');+ }+ }++ function renderTemplatesList() {+ const templatesList = document.getElementById('templatesList');+ templatesList.innerHTML = '';++ if (templates.length === 0) {+ templatesList.innerHTML = '<p class="text-sm text-[var(--text-muted)] text-center py-4">No templates yet</p>';+ return;+ }++ templates.forEach(template => {+ const templateItem = document.createElement('div');+ templateItem.className = 'p-3 bg-[var(--bg-primary)] rounded-md hover:bg-[var(--bg-tertiary)] cursor-pointer transition-colors border border-[var(--border-primary)]';+ if (template.is_default) {+ templateItem.className += ' ring-2 ring-[var(--ring-focus)]';+ }++ templateItem.innerHTML = `+ <div class="flex items-start justify-between">+ <div class="flex-1">+ <h4 class="text-sm font-medium text-[var(--text-primary)]">${template.name}</h4>+ ${template.description ? `<p class="text-xs text-[var(--text-muted)] mt-1">${template.description}</p>` : ''}+ ${template.is_default ? '<span class="text-xs text-[var(--text-accent)] mt-1"><i class="fas fa-star mr-1"></i>Default</span>' : ''}+ </div>+ </div>+ `;++ templateItem.addEventListener('click', () => selectTemplate(template));+ templatesList.appendChild(templateItem);+ });+ }++ function selectTemplate(template) {+ currentTemplate = template;+ isEditingTemplate = true;++ // Show editor, hide empty state+ document.getElementById('templateEditor').classList.remove('hidden');+ document.getElementById('templateEmptyState').classList.add('hidden');++ // Populate form+ document.getElementById('templateName').value = template.name;+ document.getElementById('templateDescription').value = template.description || '';+ document.getElementById('templateContent').value = template.template;+ document.getElementById('templateIsDefault').checked = template.is_default;++ // Show delete button+ document.getElementById('deleteTemplateBtn').classList.remove('hidden');+ }++ function createNewTemplate() {+ currentTemplate = null;+ isEditingTemplate = false;++ // Show editor, hide empty state+ document.getElementById('templateEditor').classList.remove('hidden');+ document.getElementById('templateEmptyState').classList.add('hidden');++ // Clear form+ document.getElementById('templateForm').reset();++ // Hide delete button+ document.getElementById('deleteTemplateBtn').classList.add('hidden');+ }++ document.getElementById('createTemplateBtn')?.addEventListener('click', createNewTemplate);++ document.getElementById('cancelTemplateBtn')?.addEventListener('click', () => {+ // Hide editor, show empty state+ document.getElementById('templateEditor').classList.add('hidden');+ document.getElementById('templateEmptyState').classList.remove('hidden');+ currentTemplate = null;+ isEditingTemplate = false;+ });++ document.getElementById('templateForm')?.addEventListener('submit', async (e) => {+ e.preventDefault();++ const templateData = {+ name: document.getElementById('templateName').value,+ description: document.getElementById('templateDescription').value,+ template: document.getElementById('templateContent').value,+ is_default: document.getElementById('templateIsDefault').checked+ };++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');+ const url = isEditingTemplate ? `/api/transcript-templates/${currentTemplate.id}` : '/api/transcript-templates';+ const method = isEditingTemplate ? 'PUT' : 'POST';++ const response = await fetch(url, {+ method: method,+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify(templateData)+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to save template');+ }++ const savedTemplate = await response.json();++ if (isEditingTemplate) {+ // Update existing template+ const index = templates.findIndex(t => t.id === savedTemplate.id);+ if (index !== -1) {+ templates[index] = savedTemplate;+ }+ } else {+ // Add new template+ templates.push(savedTemplate);+ }++ // Update default status for other templates if needed+ if (savedTemplate.is_default) {+ templates.forEach(t => {+ if (t.id !== savedTemplate.id) {+ t.is_default = false;+ }+ });+ }++ renderTemplatesList();+ showToast(isEditingTemplate ? 'Template updated successfully' : 'Template created successfully', 'success');++ // Hide editor+ document.getElementById('templateEditor').classList.add('hidden');+ document.getElementById('templateEmptyState').classList.remove('hidden');+ currentTemplate = null;+ isEditingTemplate = false;+ } catch (error) {+ console.error('Error saving template:', error);+ showToast(error.message || 'Failed to save template', 'error');+ }+ });++ document.getElementById('deleteTemplateBtn')?.addEventListener('click', async () => {+ if (!currentTemplate || !confirm('Are you sure you want to delete this template?')) {+ return;+ }++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');+ const response = await fetch(`/api/transcript-templates/${currentTemplate.id}`, {+ method: 'DELETE',+ headers: {+ 'X-CSRFToken': csrfToken+ }+ });++ if (!response.ok) {+ throw new Error('Failed to delete template');+ }++ // Remove from local array+ templates = templates.filter(t => t.id !== currentTemplate.id);+ renderTemplatesList();++ // Hide editor+ document.getElementById('templateEditor').classList.add('hidden');+ document.getElementById('templateEmptyState').classList.remove('hidden');+ currentTemplate = null;+ isEditingTemplate = false;++ showToast('Template deleted successfully', 'success');+ } catch (error) {+ console.error('Error deleting template:', error);+ showToast('Failed to delete template', 'error');+ }+ });++ document.getElementById('createDefaultTemplatesBtn')?.addEventListener('click', async () => {+ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');+ const response = await fetch('/api/transcript-templates/create-defaults', {+ method: 'POST',+ headers: {+ 'X-CSRFToken': csrfToken+ }+ });++ if (!response.ok) {+ throw new Error('Failed to create default templates');+ }++ const result = await response.json();+ templates = result.templates;+ renderTemplatesList();+ showToast('Default templates created successfully', 'success');+ } catch (error) {+ console.error('Error creating default templates:', error);+ showToast('Failed to create default templates', 'error');+ }+ });++ function showToast(message, type = 'info') {+ // Simple toast notification+ const toast = document.createElement('div');+ toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded-md text-white z-50 ${+ type === 'success' ? 'bg-green-600' :+ type === 'error' ? 'bg-red-600' :+ 'bg-blue-600'+ }`;+ toast.textContent = message;+ document.body.appendChild(toast);++ setTimeout(() => {+ toast.remove();+ }, 3000);+ }});</script></body>diff --git a/templates/index.html b/templates/index.htmlindex db021ce3..5f54e726 100644--- a/templates/index.html+++ b/templates/index.html@@ -979,8 +979,9 @@<button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']"><i class="fas fa-list"></i></button><button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']"><i class="fas fa-comments"></i></button></div>- <button @click="copyTranscription" class="copy-btn"><i class="fas fa-copy"></i></button>- <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn"><i class="fas fa-edit"></i></button>+ <button @click="copyTranscription" class="copy-btn" title="Copy transcript"><i class="fas fa-copy"></i></button>+ <button @click="downloadTranscript" class="copy-btn" title="Download transcript with template"><i class="fas fa-download"></i></button>+ <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" title="Edit transcript"><i class="fas fa-edit"></i></button></div><div class="flex-grow overflow-y-auto mobile-content-box"><div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">