Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add export template selection for tags and folders
Murtaza Nasir6ea0e74e0ede
diff --git a/src/api/auth.py b/src/api/auth.pyindex 1d8bde22..d6bfd90b 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -625,6 +625,7 @@ def account():ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'ASR_RETURN_SPEAKER_EMBEDDINGS = os.environ.get('ASR_RETURN_SPEAKER_EMBEDDINGS', 'false').lower() == 'true'+ ENABLE_AUTO_EXPORT = os.environ.get('ENABLE_AUTO_EXPORT', 'false').lower() == 'true'# Get connector diarization support (new architecture)connector_supports_diarization = USE_ASR_ENDPOINT # Default to USE_ASR_ENDPOINT for backwards compat@@ -692,7 +693,8 @@ def account():auto_speaker_labelling_threshold=current_user.auto_speaker_labelling_threshold or 'medium',admin_disabled_auto_summarization=admin_disabled_auto_summarization,auto_summarization=current_user.auto_summarization if current_user.auto_summarization is not None else True,- user_language=user_language)+ user_language=user_language,+ enable_auto_export=ENABLE_AUTO_EXPORT)@auth_bp.route('/api/user/auto-speaker-labelling', methods=['POST'])diff --git a/src/api/folders.py b/src/api/folders.pyindex 06345840..30390a9b 100644--- a/src/api/folders.py+++ b/src/api/folders.py@@ -134,6 +134,13 @@ def create_folder():if not template:return jsonify({'error': 'Naming template not found'}), 404+ # Validate export_template_id if provided+ export_template_id = data.get('export_template_id')+ if export_template_id:+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+folder = Folder(name=data['name'],user_id=current_user.id,@@ -147,7 +154,8 @@ def create_folder():retention_days=retention_days,auto_share_on_apply=data.get('auto_share_on_apply', True) if group_id else True,share_with_group_lead=data.get('share_with_group_lead', True) if group_id else True,- naming_template_id=naming_template_id+ naming_template_id=naming_template_id,+ export_template_id=export_template_id)db.session.add(folder)@@ -258,6 +266,13 @@ def update_folder(folder_id):if not template:return jsonify({'error': 'Naming template not found'}), 404folder.naming_template_id = naming_template_id if naming_template_id else None+ if 'export_template_id' in data:+ export_template_id = data['export_template_id']+ if export_template_id:+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+ folder.export_template_id = export_template_id if export_template_id else Nonefolder.updated_at = datetime.utcnow()@@ -346,6 +361,20 @@ def create_group_folder(group_id):if existing_folder:return jsonify({'error': 'A group folder with this name already exists'}), 400+ # Validate naming_template_id if provided+ naming_template_id = data.get('naming_template_id')+ if naming_template_id:+ template = NamingTemplate.query.filter_by(id=naming_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Naming template not found'}), 404++ # Validate export_template_id if provided+ export_template_id = data.get('export_template_id')+ if export_template_id:+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+# Create the group folder with all supported parametersfolder = Folder(name=name,@@ -359,7 +388,9 @@ def create_group_folder(group_id):protect_from_deletion=data.get('protect_from_deletion', False),retention_days=data.get('retention_days'),auto_share_on_apply=data.get('auto_share_on_apply', True), # Default to True for group folders- share_with_group_lead=data.get('share_with_group_lead', True) # Default to True for group folders+ share_with_group_lead=data.get('share_with_group_lead', True), # Default to True for group folders+ naming_template_id=naming_template_id,+ export_template_id=export_template_id)db.session.add(folder)diff --git a/src/api/tags.py b/src/api/tags.pyindex 36afa6a4..288a5a7b 100644--- a/src/api/tags.py+++ b/src/api/tags.py@@ -131,6 +131,14 @@ def create_tag():if not template:return jsonify({'error': 'Naming template not found'}), 404+ # Validate export_template_id if provided+ export_template_id = data.get('export_template_id')+ if export_template_id:+ from src.models import ExportTemplate+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+tag = Tag(name=data['name'],user_id=current_user.id,@@ -144,7 +152,8 @@ def create_tag():retention_days=retention_days,auto_share_on_apply=data.get('auto_share_on_apply', True) if group_id else True,share_with_group_lead=data.get('share_with_group_lead', True) if group_id else True,- naming_template_id=naming_template_id+ naming_template_id=naming_template_id,+ export_template_id=export_template_id)db.session.add(tag)@@ -252,6 +261,14 @@ def update_tag(tag_id):if not template:return jsonify({'error': 'Naming template not found'}), 404tag.naming_template_id = naming_template_id if naming_template_id else None+ if 'export_template_id' in data:+ export_template_id = data['export_template_id']+ if export_template_id:+ from src.models import ExportTemplate+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+ tag.export_template_id = export_template_id if export_template_id else Nonetag.updated_at = datetime.utcnow()@@ -331,6 +348,22 @@ def create_group_tag(group_id):if existing_tag:return jsonify({'error': 'A group tag with this name already exists'}), 400+ # Validate naming_template_id if provided+ naming_template_id = data.get('naming_template_id')+ if naming_template_id:+ from src.models import NamingTemplate+ template = NamingTemplate.query.filter_by(id=naming_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Naming template not found'}), 404++ # Validate export_template_id if provided+ export_template_id = data.get('export_template_id')+ if export_template_id:+ from src.models import ExportTemplate+ template = ExportTemplate.query.filter_by(id=export_template_id, user_id=current_user.id).first()+ if not template:+ return jsonify({'error': 'Export template not found'}), 404+# Create the group tag with all supported parameterstag = Tag(name=name,@@ -344,7 +377,9 @@ def create_group_tag(group_id):protect_from_deletion=data.get('protect_from_deletion', False),retention_days=data.get('retention_days'),auto_share_on_apply=data.get('auto_share_on_apply', True), # Default to True for group tags- share_with_group_lead=data.get('share_with_group_lead', True) # Default to True for group tags+ share_with_group_lead=data.get('share_with_group_lead', True), # Default to True for group tags+ naming_template_id=naming_template_id,+ export_template_id=export_template_id)db.session.add(tag)diff --git a/src/file_exporter.py b/src/file_exporter.pyindex 745e5a76..deff627a 100644--- a/src/file_exporter.py+++ b/src/file_exporter.py@@ -207,17 +207,39 @@ def format_file_size(bytes_size):return f"{bytes_size:.1f} TB"-def get_user_export_template(user):+def get_user_export_template(user, recording=None):"""- Get the user's default export template.+ Get the export template to use for a recording.++ Resolution order:+ 1. Folder's export_template_id (if recording is in a folder)+ 2. Tag's export_template_id (first matching tag with an export template)+ 3. User's default export template (is_default=True)Args:user: User object+ recording: Optional Recording object (for folder/tag lookup)Returns:ExportTemplate object or None"""from src.models import ExportTemplate++ # 1. Check folder's export template+ if recording and recording.folder and recording.folder.export_template_id:+ template = ExportTemplate.query.get(recording.folder.export_template_id)+ if template:+ return template++ # 2. Check tags' export templates+ if recording and recording.tags:+ for tag in recording.tags:+ if tag.export_template_id:+ template = ExportTemplate.query.get(tag.export_template_id)+ if template:+ return template++ # 3. Fall back to user's defaultreturn ExportTemplate.query.filter_by(user_id=user.id,is_default=True@@ -284,8 +306,8 @@ def generate_markdown_content(recording, user, include_transcription=True, inclu# Get localized labelslabels = get_export_labels(user_language)- # Get user's export template- export_template = get_user_export_template(user)+ # Get export template (checks folder, tags, then user default)+ export_template = get_user_export_template(user, recording)if export_template:# Use custom templatediff --git a/src/init_db.py b/src/init_db.pyindex d6e86434..b81d2d6c 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -285,6 +285,12 @@ def initialize_database(app):if add_column_if_not_exists(engine, 'tag', 'naming_template_id', 'INTEGER'):app.logger.info("Added naming_template_id column to tag table")+ # Export template assignments for tags and folders+ if add_column_if_not_exists(engine, 'tag', 'export_template_id', 'INTEGER'):+ app.logger.info("Added export_template_id column to tag table")+ if add_column_if_not_exists(engine, 'folder', 'export_template_id', 'INTEGER'):+ app.logger.info("Added export_template_id column to folder table")+# Add source tracking columns to internal_share tableif add_column_if_not_exists(engine, 'internal_share', 'source_type', 'VARCHAR(20) DEFAULT "manual"'):app.logger.info("Added source_type column to internal_share table")diff --git a/src/models/organization.py b/src/models/organization.pyindex 18886fc6..a934801b 100644--- a/src/models/organization.py+++ b/src/models/organization.py@@ -106,6 +106,9 @@ class Folder(db.Model):# Naming template for recordings in this foldernaming_template_id = db.Column(db.Integer, db.ForeignKey('naming_template.id', ondelete='SET NULL'), nullable=True)+ # Export template for recordings in this folder+ export_template_id = db.Column(db.Integer, db.ForeignKey('export_template.id', ondelete='SET NULL'), nullable=True)+created_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)@@ -113,6 +116,7 @@ class Folder(db.Model):user = db.relationship('User', backref=db.backref('folders', lazy=True, cascade='all, delete-orphan'))group = db.relationship('Group', backref=db.backref('folders', lazy=True))naming_template = db.relationship('NamingTemplate', foreign_keys=[naming_template_id])+ export_template = db.relationship('ExportTemplate', foreign_keys=[export_template_id])# One-to-many relationship with recordingsrecordings = db.relationship('Recording', back_populates='folder', lazy=True)@@ -143,6 +147,8 @@ class Folder(db.Model):'share_with_group_lead': self.share_with_group_lead,'naming_template_id': self.naming_template_id,'naming_template_name': self.naming_template.name if self.naming_template else None,+ 'export_template_id': self.export_template_id,+ 'export_template_name': self.export_template.name if self.export_template else None,'created_at': self.created_at.isoformat() if self.created_at else None,'recording_count': len(self.recordings) if self.recordings else 0}@@ -174,6 +180,9 @@ class Tag(db.Model):# Naming template for recordings with this tagnaming_template_id = db.Column(db.Integer, db.ForeignKey('naming_template.id', ondelete='SET NULL'), nullable=True)+ # Export template for recordings with this tag+ export_template_id = db.Column(db.Integer, db.ForeignKey('export_template.id', ondelete='SET NULL'), nullable=True)+created_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)@@ -181,6 +190,7 @@ class Tag(db.Model):user = db.relationship('User', backref=db.backref('tags', lazy=True, cascade='all, delete-orphan'))group = db.relationship('Group', backref=db.backref('tags', lazy=True))naming_template = db.relationship('NamingTemplate', foreign_keys=[naming_template_id])+ export_template = db.relationship('ExportTemplate', foreign_keys=[export_template_id])# Use association object for many-to-many with order trackingrecording_associations = db.relationship('RecordingTag', back_populates='tag', cascade='all, delete-orphan')@@ -211,6 +221,8 @@ class Tag(db.Model):'share_with_group_lead': self.share_with_group_lead,'naming_template_id': self.naming_template_id,'naming_template_name': self.naming_template.name if self.naming_template else None,+ 'export_template_id': self.export_template_id,+ 'export_template_name': self.export_template.name if self.export_template else None,'created_at': self.created_at.isoformat() if self.created_at else None,'recording_count': len(self.recording_associations)}diff --git a/templates/account.html b/templates/account.htmlindex 6cd85051..7c5f4fc7 100644--- a/templates/account.html+++ b/templates/account.html@@ -2022,6 +2022,18 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co<p class="text-xs text-[var(--text-light)] mt-1" data-i18n="editTagModal.namingTemplateHint">Select a naming template to automatically format titles for recordings with this tag</p></div>+ <!-- Export Template Selection -->+ {% if enable_auto_export %}+ <div>+ <label for="tagExportTemplate" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="editTagModal.exportTemplate">Export Template</label>+ <select id="tagExportTemplate" name="export_template_id" 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)]">+ <option value="" data-i18n="editTagModal.noExportTemplate">No template (use user default)</option>+ <!-- Export template options will be populated dynamically -->+ </select>+ <p class="text-xs text-[var(--text-light)] mt-1" data-i18n="editTagModal.exportTemplateHint">Select an export template to use when exporting recordings with this tag</p>+ </div>+ {% endif %}+<!-- Group Selection (only shown if internal sharing is enabled and user is admin of some groups) --><div id="tagGroupSelectionSection" class="hidden"><label for="tagGroupId" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Group Assignment (Optional)</label>@@ -2183,6 +2195,18 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co<p class="text-xs text-[var(--text-light)] mt-1">Select a naming template to automatically format titles for recordings in this folder</p></div>+ <!-- Export Template Selection -->+ {% if enable_auto_export %}+ <div>+ <label for="folderExportTemplate" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Export Template</label>+ <select id="folderExportTemplate" name="export_template_id" 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)]">+ <option value="">No template (use user default)</option>+ <!-- Export template options will be populated dynamically -->+ </select>+ <p class="text-xs text-[var(--text-light)] mt-1">Select an export template to use when exporting recordings in this folder</p>+ </div>+ {% endif %}+<!-- Group Selection (only shown if internal sharing is enabled and user is admin of some groups) --><div id="folderGroupSelectionSection" class="hidden"><label for="folderGroupId" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Group Assignment (Optional)</label>@@ -4538,6 +4562,11 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</coif (document.getElementById('tagNamingTemplate')) {document.getElementById('tagNamingTemplate').value = tag.naming_template_id || '';}++ // Populate export template+ if (document.getElementById('tagExportTemplate')) {+ document.getElementById('tagExportTemplate').value = tag.export_template_id || '';+ }} else {// Create modeisEditingTag = false;@@ -4578,11 +4607,19 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</coif (document.getElementById('tagNamingTemplate')) {document.getElementById('tagNamingTemplate').value = '';}++ // Reset export template+ if (document.getElementById('tagExportTemplate')) {+ document.getElementById('tagExportTemplate').value = '';+ }}// Load naming templates for dropdownloadNamingTemplatesForTagModal();+ // Load export templates for dropdown+ loadExportTemplatesForTagModal();+tagModal.classList.remove('hidden');}@@ -4623,6 +4660,44 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co}}+ // Load export templates for the tag modal dropdown+ async function loadExportTemplatesForTagModal() {+ const select = document.getElementById('tagExportTemplate');+ if (!select) return;++ try {+ const response = await fetch('/api/export-templates');+ if (!response.ok) return;++ const templates = await response.json();++ // Preserve current selection+ const currentValue = select.value;++ // Clear all options and add default+ select.textContent = '';+ const defaultOpt = document.createElement('option');+ defaultOpt.value = '';+ defaultOpt.textContent = 'No template (use user default)';+ select.appendChild(defaultOpt);++ // Add template options+ templates.forEach(template => {+ const option = document.createElement('option');+ option.value = template.id;+ option.textContent = template.name + (template.is_default ? ' (Default)' : '');+ select.appendChild(option);+ });++ // Restore selection+ if (currentValue) {+ select.value = currentValue;+ }+ } catch (error) {+ console.error('Error loading export templates for tag modal:', error);+ }+ }+// Edit tagfunction editTag(tag) {openTagModal(tag);@@ -4680,11 +4755,13 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co}const namingTemplateId = formData.get('naming_template_id');+ const exportTemplateId = formData.get('export_template_id');const tagData = {name: formData.get('name'),color: formData.get('color'),custom_prompt: formData.get('custom_prompt') || null,naming_template_id: namingTemplateId ? parseInt(namingTemplateId) : null,+ export_template_id: exportTemplateId ? parseInt(exportTemplateId) : null,default_language: formData.get('default_language') || null,default_min_speakers: formData.get('default_min_speakers') ? parseInt(formData.get('default_min_speakers')) : null,default_max_speakers: formData.get('default_max_speakers') ? parseInt(formData.get('default_max_speakers')) : null,@@ -5117,14 +5194,17 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</codocument.getElementById('folderId').value = '';}- // Load naming templates for dropdown- loadNamingTemplatesForFolderModal();+ // Load naming templates for dropdown (pass folder to set initial value)+ loadNamingTemplatesForFolderModal(folder);++ // Load export templates for dropdown (pass folder to set initial value)+ loadExportTemplatesForFolderModal(folder);if (folderModal) folderModal.classList.remove('hidden');}// Load naming templates for folder modal- async function loadNamingTemplatesForFolderModal() {+ async function loadNamingTemplatesForFolderModal(folder) {const select = document.getElementById('folderNamingTemplate');if (!select) return;@@ -5143,12 +5223,48 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</cooption.textContent = t.name;select.appendChild(option);});++ // Set value if editing+ if (folder && folder.naming_template_id) {+ select.value = folder.naming_template_id;+ }}} catch (error) {console.error('Error loading naming templates:', error);}}+ // Load export templates for folder modal+ async function loadExportTemplatesForFolderModal(folder) {+ const select = document.getElementById('folderExportTemplate');+ if (!select) return;++ try {+ const response = await fetch('/api/export-templates');+ if (response.ok) {+ const templates = await response.json();+ select.textContent = '';+ const defaultOpt = document.createElement('option');+ defaultOpt.value = '';+ defaultOpt.textContent = 'No template (use user default)';+ select.appendChild(defaultOpt);+ templates.forEach(function(t) {+ const option = document.createElement('option');+ option.value = t.id;+ option.textContent = t.name + (t.is_default ? ' (Default)' : '');+ select.appendChild(option);+ });++ // Set value if editing+ if (folder && folder.export_template_id) {+ select.value = folder.export_template_id;+ }+ }+ } catch (error) {+ console.error('Error loading export templates:', error);+ }+ }+// Update folder group settings visibilityfunction updateFolderGroupSettingsVisibility() {const folderGroupId = document.getElementById('folderGroupId');@@ -5246,6 +5362,8 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</cofolderData.default_max_speakers = maxEl && maxEl.value ? parseInt(maxEl.value) : null;var templateEl = document.getElementById('folderNamingTemplate');folderData.naming_template_id = templateEl && templateEl.value ? parseInt(templateEl.value) : null;+ var exportTemplateEl = document.getElementById('folderExportTemplate');+ folderData.export_template_id = exportTemplateEl && exportTemplateEl.value ? parseInt(exportTemplateEl.value) : null;// Group settingsconst folderGroupIdEl = document.getElementById('folderGroupId');