Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add naming templates feature for custom recording title formatting

Murtaza Nasira4adf21cd1bd
diff --git a/src/api/naming_templates.py b/src/api/naming_templates.py
new file mode 100644
index 00000000..beab49de
--- /dev/null
+++ b/src/api/naming_templates.py
@@ -0,0 +1,331 @@
+"""
+Naming template management.
+
+This blueprint handles CRUD operations for naming templates,
+which define how recording titles are generated from filenames,
+metadata, and AI-generated content.
+"""
+
+import json
+from datetime import datetime
+from flask import Blueprint, request, jsonify, current_app
+from flask_login import login_required, current_user
+
+from src.database import db
+from src.models import NamingTemplate
+
+# Create blueprint
+naming_templates_bp = Blueprint('naming_templates', __name__)
+
+
+# --- Routes ---
+
+@naming_templates_bp.route('/api/naming-templates', methods=['GET'])
+@login_required
+def get_naming_templates():
+ """Get all naming templates for the current user."""
+ templates = NamingTemplate.query.filter_by(user_id=current_user.id).all()
+ return jsonify([template.to_dict() for template in templates])
+
+
+@naming_templates_bp.route('/api/naming-templates', methods=['POST'])
+@login_required
+def create_naming_template():
+ """Create a new naming 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
+
+ # Validate regex patterns if provided
+ regex_patterns = data.get('regex_patterns', {})
+ if regex_patterns:
+ if not isinstance(regex_patterns, dict):
+ return jsonify({'error': 'regex_patterns must be a dictionary'}), 400
+ # Validate each regex pattern
+ import re
+ for var_name, pattern in regex_patterns.items():
+ try:
+ re.compile(pattern)
+ except re.error as e:
+ return jsonify({'error': f'Invalid regex pattern for "{var_name}": {str(e)}'}), 400
+
+ # If this is set as default, unset other defaults
+ if data.get('is_default'):
+ NamingTemplate.query.filter_by(
+ user_id=current_user.id,
+ is_default=True
+ ).update({'is_default': False})
+
+ template = NamingTemplate(
+ user_id=current_user.id,
+ name=data['name'],
+ template=data['template'],
+ description=data.get('description'),
+ regex_patterns=json.dumps(regex_patterns) if regex_patterns else None,
+ is_default=data.get('is_default', False)
+ )
+
+ db.session.add(template)
+ db.session.commit()
+
+ return jsonify(template.to_dict()), 201
+
+
+@naming_templates_bp.route('/api/naming-templates/<int:template_id>', methods=['GET'])
+@login_required
+def get_naming_template(template_id):
+ """Get a specific naming template."""
+ template = NamingTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+
+ if not template:
+ return jsonify({'error': 'Template not found'}), 404
+
+ return jsonify(template.to_dict())
+
+
+@naming_templates_bp.route('/api/naming-templates/<int:template_id>', methods=['PUT'])
+@login_required
+def update_naming_template(template_id):
+ """Update an existing naming template."""
+ template = NamingTemplate.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
+
+ # Validate regex patterns if provided
+ if 'regex_patterns' in data:
+ regex_patterns = data['regex_patterns']
+ if regex_patterns:
+ if not isinstance(regex_patterns, dict):
+ return jsonify({'error': 'regex_patterns must be a dictionary'}), 400
+ import re
+ for var_name, pattern in regex_patterns.items():
+ try:
+ re.compile(pattern)
+ except re.error as e:
+ return jsonify({'error': f'Invalid regex pattern for "{var_name}": {str(e)}'}), 400
+
+ # If this is set as default, unset other defaults
+ if data.get('is_default'):
+ NamingTemplate.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)
+
+ if 'regex_patterns' in data:
+ regex_patterns = data['regex_patterns']
+ template.regex_patterns = json.dumps(regex_patterns) if regex_patterns else None
+
+ template.updated_at = datetime.utcnow()
+
+ db.session.commit()
+
+ return jsonify(template.to_dict())
+
+
+@naming_templates_bp.route('/api/naming-templates/<int:template_id>', methods=['DELETE'])
+@login_required
+def delete_naming_template(template_id):
+ """Delete a naming template."""
+ template = NamingTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+
+ if not template:
+ return jsonify({'error': 'Template not found'}), 404
+
+ # Check if any tags are using this template
+ from src.models import Tag
+ tags_using = Tag.query.filter_by(naming_template_id=template_id).count()
+ if tags_using > 0:
+ return jsonify({
+ 'error': f'Cannot delete template: {tags_using} tag(s) are using this template'
+ }), 400
+
+ db.session.delete(template)
+ db.session.commit()
+
+ return jsonify({'success': True})
+
+
+@naming_templates_bp.route('/api/naming-templates/create-defaults', methods=['POST'])
+@login_required
+def create_default_naming_templates():
+ """Create default naming templates for the user if they don't have any."""
+ existing_templates = NamingTemplate.query.filter_by(user_id=current_user.id).count()
+
+ if existing_templates > 0:
+ return jsonify({'message': 'User already has naming templates'}), 200
+
+ templates = []
+
+ # Default template 1: AI Title Only (default)
+ template1 = NamingTemplate(
+ user_id=current_user.id,
+ name="AI Title Only",
+ template="{{ai_title}}",
+ description="Uses AI-generated title from transcription content",
+ is_default=True
+ )
+ templates.append(template1)
+
+ # Default template 2: Date Prefix
+ template2 = NamingTemplate(
+ user_id=current_user.id,
+ name="Date Prefix",
+ template="{{date}} - {{ai_title}}",
+ description="Prepends recording date to AI-generated title",
+ is_default=False
+ )
+ templates.append(template2)
+
+ # Default template 3: Date and Time
+ template3 = NamingTemplate(
+ user_id=current_user.id,
+ name="Date and Time",
+ template="{{datetime}} {{ai_title}}",
+ description="Includes date and time before the AI title",
+ is_default=False
+ )
+ templates.append(template3)
+
+ # Default template 4: Filename Only (no AI)
+ template4 = NamingTemplate(
+ user_id=current_user.id,
+ name="Filename Only",
+ template="{{filename}}",
+ description="Uses original filename without extension (no AI generation)",
+ is_default=False
+ )
+ templates.append(template4)
+
+ # Default template 5: Phone Call Format
+ # For filenames like: 8005551234-5559876543-20260115.wav
+ phone_call_patterns = {
+ "caller_area": "^(\\d{3})",
+ "caller_ex": "^\\d{3}(\\d{3})",
+ "caller_sub": "^\\d{6}(\\d{4})",
+ "callee_area": "^\\d{10}-(\\d{3})",
+ "callee_ex": "^\\d{10}-\\d{3}(\\d{3})",
+ "callee_sub": "^\\d{10}-\\d{6}(\\d{4})",
+ "year": "^\\d{10}-\\d{10}-(\\d{4})",
+ "month": "^\\d{10}-\\d{10}-\\d{4}(\\d{2})",
+ "day": "^\\d{10}-\\d{10}-\\d{6}(\\d{2})"
+ }
+ template5 = NamingTemplate(
+ user_id=current_user.id,
+ name="Phone Call Format",
+ template="{{caller_area}}-{{caller_ex}}-{{caller_sub}} → {{callee_area}}-{{callee_ex}}-{{callee_sub}} ({{year}}-{{month}}-{{day}})",
+ description="For phone recordings: caller-callee-YYYYMMDD filenames",
+ regex_patterns=json.dumps(phone_call_patterns),
+ is_default=False
+ )
+ templates.append(template5)
+
+ # Add all templates to database
+ for template in templates:
+ db.session.add(template)
+
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'templates': [template.to_dict() for template in templates]
+ }), 201
+
+
+@naming_templates_bp.route('/api/naming-templates/<int:template_id>/test', methods=['POST'])
+@login_required
+def test_naming_template(template_id):
+ """Test a naming template with sample data."""
+ template = NamingTemplate.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 or {}
+ sample_filename = data.get('filename', 'sample-recording-2026-01-15.mp3')
+ sample_date = data.get('date')
+ sample_ai_title = data.get('ai_title', 'Meeting with Team')
+
+ # Parse sample date
+ meeting_date = None
+ if sample_date:
+ try:
+ meeting_date = datetime.fromisoformat(sample_date)
+ except ValueError:
+ pass
+
+ if not meeting_date:
+ meeting_date = datetime.now()
+
+ # Apply template
+ result = template.apply(
+ original_filename=sample_filename,
+ meeting_date=meeting_date,
+ ai_title=sample_ai_title
+ )
+
+ return jsonify({
+ 'result': result or '(empty - would fall back to AI title or filename)',
+ 'needs_ai_title': template.needs_ai_title(),
+ 'input': {
+ 'filename': sample_filename,
+ 'date': meeting_date.isoformat() if meeting_date else None,
+ 'ai_title': sample_ai_title
+ }
+ })
+
+
+@naming_templates_bp.route('/api/naming-templates/default', methods=['GET'])
+@login_required
+def get_default_naming_template():
+ """Get the user's default naming template."""
+ return jsonify({
+ 'default_naming_template_id': current_user.default_naming_template_id
+ })
+
+
+@naming_templates_bp.route('/api/naming-templates/default', methods=['PUT'])
+@login_required
+def set_default_naming_template():
+ """Set the user's default naming template."""
+ data = request.json
+ template_id = data.get('template_id') if data else None
+
+ if template_id:
+ # Verify template belongs to user
+ template = NamingTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+
+ if not template:
+ return jsonify({'error': 'Template not found'}), 404
+
+ current_user.default_naming_template_id = template_id if template_id else None
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'default_naming_template_id': current_user.default_naming_template_id
+ })
diff --git a/src/api/tags.py b/src/api/tags.py
index e03a4c5f..36afa6a4 100644
--- a/src/api/tags.py
+++ b/src/api/tags.py
@@ -123,6 +123,14 @@ def create_tag():
# -1 indicates infinite retention (protected from auto-deletion)
protect_from_deletion = True if ENABLE_AUTO_DELETION else False
+ # 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
+
tag = Tag(
name=data['name'],
user_id=current_user.id,
@@ -135,7 +143,8 @@ def create_tag():
protect_from_deletion=protect_from_deletion,
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
+ share_with_group_lead=data.get('share_with_group_lead', True) if group_id else True,
+ naming_template_id=naming_template_id
)
db.session.add(tag)
@@ -235,6 +244,14 @@ def update_tag(tag_id):
# Only applicable to group tags
if tag.group_id:
tag.share_with_group_lead = bool(data['share_with_group_lead'])
+ if 'naming_template_id' in data:
+ naming_template_id = data['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
+ tag.naming_template_id = naming_template_id if naming_template_id else None
tag.updated_at = datetime.utcnow()
diff --git a/src/app.py b/src/app.py
index 9bdc9c36..2ecc2147 100644
--- a/src/app.py
+++ b/src/app.py
@@ -544,6 +544,7 @@ from src.api.admin import admin_bp, init_admin_helpers
from src.api.speakers import speakers_bp, init_speakers_helpers
from src.api.inquire import inquire_bp, init_inquire_helpers
from src.api.templates import templates_bp, init_templates_helpers
+from src.api.naming_templates import naming_templates_bp
from src.api.events import events_bp, init_events_helpers
from src.api.system import system_bp, init_system_helpers
from src.api.push_notifications import push_bp
@@ -584,6 +585,7 @@ app.register_blueprint(admin_bp)
app.register_blueprint(speakers_bp)
app.register_blueprint(inquire_bp)
app.register_blueprint(templates_bp)
+app.register_blueprint(naming_templates_bp)
app.register_blueprint(events_bp)
app.register_blueprint(system_bp)
app.register_blueprint(push_bp)
diff --git a/src/init_db.py b/src/init_db.py
index 58b7660a..ebfb164d 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -238,6 +238,12 @@ def initialize_database(app):
if add_column_if_not_exists(engine, 'user', 'monthly_transcription_budget', 'INTEGER'):
app.logger.info("Added monthly_transcription_budget column to user table")
+ # Naming templates feature
+ if add_column_if_not_exists(engine, 'user', 'default_naming_template_id', 'INTEGER'):
+ app.logger.info("Added default_naming_template_id column to user table")
+ if add_column_if_not_exists(engine, 'tag', 'naming_template_id', 'INTEGER'):
+ app.logger.info("Added naming_template_id column to tag table")
+
# Add source tracking columns to internal_share table
if 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/__init__.py b/src/models/__init__.py
index a88121dd..f100e6fb 100644
--- a/src/models/__init__.py
+++ b/src/models/__init__.py
@@ -22,6 +22,7 @@ from .sharing import Share, InternalShare, SharedRecordingState
from .organization import Group, GroupMembership, Tag, RecordingTag
from .events import Event
from .templates import TranscriptTemplate
+from .naming_template import NamingTemplate
from .inquire import InquireSession
from .system import SystemSetting
from .audit import ShareAuditLog
@@ -55,6 +56,7 @@ __all__ = [
# Other models
'Event',
'TranscriptTemplate',
+ 'NamingTemplate',
'InquireSession',
'SystemSetting',
'PushSubscription',
diff --git a/src/models/naming_template.py b/src/models/naming_template.py
new file mode 100644
index 00000000..f09dc890
--- /dev/null
+++ b/src/models/naming_template.py
@@ -0,0 +1,114 @@
+"""
+NamingTemplate model for user-defined recording title formatting.
+
+This module defines the NamingTemplate model for storing
+custom templates for generating recording titles from filenames,
+metadata, and AI-generated content.
+"""
+
+import json
+import re
+import os
+from datetime import datetime
+from src.database import db
+
+
+class NamingTemplate(db.Model):
+ """Stores user-defined templates for recording title generation."""
+
+ 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) # e.g., "{{phone}} - {{date}} {{ai_title}}"
+ description = db.Column(db.String(500), nullable=True)
+ regex_patterns = db.Column(db.Text, nullable=True) # JSON: {"phone": "\\d{10}", "caller": "^([^-]+)"}
+ 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', foreign_keys=[user_id], backref=db.backref('naming_templates', lazy=True, cascade='all, delete-orphan'))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'template': self.template,
+ 'description': self.description,
+ 'regex_patterns': json.loads(self.regex_patterns) if self.regex_patterns else {},
+ '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
+ }
+
+ def get_regex_patterns(self):
+ """Parse and return regex patterns as dictionary."""
+ if not self.regex_patterns:
+ return {}
+ try:
+ return json.loads(self.regex_patterns)
+ except json.JSONDecodeError:
+ return {}
+
+ def needs_ai_title(self):
+ """Check if template requires AI-generated title."""
+ return '{{ai_title}}' in self.template
+
+ def apply(self, original_filename, meeting_date=None, ai_title=None):
+ """
+ Apply this template to generate a recording title.
+
+ Args:
+ original_filename: The original filename of the recording
+ meeting_date: Optional datetime of the recording
+ ai_title: Optional AI-generated title
+
+ Returns:
+ Generated title string, or None if template produces empty result
+ """
+ # Start with template
+ result = self.template
+
+ # Get filename without extension for {{filename}}
+ filename_no_ext = os.path.splitext(original_filename)[0] if original_filename else ''
+
+ # Build built-in variables
+ variables = {
+ 'ai_title': ai_title or '',
+ 'filename': filename_no_ext,
+ 'filename_full': original_filename or '',
+ 'date': meeting_date.strftime('%Y-%m-%d') if meeting_date else '',
+ 'datetime': meeting_date.strftime('%Y-%m-%d %H:%M') if meeting_date else '',
+ 'time': meeting_date.strftime('%H:%M') if meeting_date else '',
+ 'year': meeting_date.strftime('%Y') if meeting_date else '',
+ 'month': meeting_date.strftime('%m') if meeting_date else '',
+ 'day': meeting_date.strftime('%d') if meeting_date else '',
+ }
+
+ # Extract custom variables from filename using regex patterns
+ regex_patterns = self.get_regex_patterns()
+ for var_name, pattern in regex_patterns.items():
+ try:
+ match = re.search(pattern, filename_no_ext)
+ if match:
+ # Use first capture group if exists, else full match
+ variables[var_name] = match.group(1) if match.groups() else match.group(0)
+ else:
+ variables[var_name] = ''
+ except re.error as e:
+ # Invalid regex - log and treat as empty
+ variables[var_name] = ''
+
+ # Replace all variables in template
+ for var_name, value in variables.items():
+ result = result.replace('{{' + var_name + '}}', value)
+
+ # Clean up result
+ result = result.strip()
+
+ # If result is empty or only whitespace, return None
+ if not result:
+ return None
+
+ return result
diff --git a/src/models/organization.py b/src/models/organization.py
index 38dbe10e..644f9c31 100644
--- a/src/models/organization.py
+++ b/src/models/organization.py
@@ -103,12 +103,16 @@ class Tag(db.Model):
auto_share_on_apply = db.Column(db.Boolean, default=True) # Auto-share recording with group when this tag is applied
share_with_group_lead = db.Column(db.Boolean, default=True) # Share with group admins when this tag is applied
+ # Naming template for recordings with this tag
+ naming_template_id = db.Column(db.Integer, db.ForeignKey('naming_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)
# Relationships
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])
# Use association object for many-to-many with order tracking
recording_associations = db.relationship('RecordingTag', back_populates='tag', cascade='all, delete-orphan')
@@ -137,6 +141,8 @@ class Tag(db.Model):
'retention_days': self.retention_days,
'auto_share_on_apply': self.auto_share_on_apply,
'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,
'created_at': self.created_at.isoformat() if self.created_at else None,
'recording_count': len(self.recording_associations)
}
diff --git a/src/models/user.py b/src/models/user.py
index 24420e37..3157810f 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -32,6 +32,10 @@ class User(db.Model, UserMixin):
company = db.Column(db.String(100), nullable=True)
diarize = db.Column(db.Boolean, default=False)
+ # Default naming template for title generation
+ default_naming_template_id = db.Column(db.Integer, db.ForeignKey('naming_template.id', ondelete='SET NULL'), nullable=True)
+ default_naming_template = db.relationship('NamingTemplate', foreign_keys=[default_naming_template_id])
+
# Token budget (None = unlimited)
monthly_token_budget = db.Column(db.Integer, nullable=True)
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 7e33fbb5..1241341a 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -21,7 +21,7 @@ from flask import current_app
from openai import OpenAI
from src.database import db
-from src.models import Recording, Tag, Event, TranscriptChunk, SystemSetting, GroupMembership, RecordingTag, InternalShare, SharedRecordingState, User
+from src.models import Recording, Tag, Event, TranscriptChunk, SystemSetting, GroupMembership, RecordingTag, InternalShare, SharedRecordingState, User, NamingTemplate
from src.services.embeddings import process_recording_chunks
from src.services.llm import is_using_openai_api, call_llm_completion, format_api_error_message, TEXT_MODEL_NAME, client, http_client_no_proxy
from src.utils import extract_json_object, safe_json_loads
@@ -208,43 +208,111 @@ def generate_title_task(app_context, recording_id, will_auto_summarize=False):
current_app.logger.error(f"Error: Recording {recording_id} not found for title generation.")
return
- if client is None:
- current_app.logger.warning(f"Skipping title generation for {recording_id}: OpenRouter client not configured.")
- # Only mark as completed if auto-summarization won't happen next
- if not will_auto_summarize:
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- return
+ # Resolve naming template: first tag with template → user default → None
+ naming_template = None
+ for tag in recording.tags:
+ if tag.naming_template_id:
+ naming_template = tag.naming_template
+ current_app.logger.info(f"Using naming template '{naming_template.name}' from tag '{tag.name}' for recording {recording_id}")
+ break
+
+ if not naming_template and recording.owner and recording.owner.default_naming_template_id:
+ naming_template = recording.owner.default_naming_template
+ if naming_template:
+ current_app.logger.info(f"Using user's default naming template '{naming_template.name}' for recording {recording_id}")
+
+ # Check if we need to generate AI title
+ needs_ai_title = naming_template is None or naming_template.needs_ai_title()
+
+ # Early exit conditions
+ if not needs_ai_title:
+ # Template doesn't need AI - we can skip LLM call entirely
+ current_app.logger.info(f"Naming template doesn't require AI title for recording {recording_id}, skipping LLM call")
+ ai_title = None
+ elif client is None:
+ current_app.logger.warning(f"Skipping AI title generation for {recording_id}: OpenRouter client not configured.")
+ ai_title = None
+ elif not recording.transcription or len(recording.transcription.strip()) < 10:
+ current_app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping AI title generation.")
+ ai_title = None
+ else:
+ # Generate AI title via LLM
+ ai_title = _generate_ai_title(recording)
+
+ # Apply naming template if we have one
+ final_title = None
+ if naming_template:
+ final_title = naming_template.apply(
+ original_filename=recording.original_filename,
+ meeting_date=recording.meeting_date,
+ ai_title=ai_title
+ )
+ if final_title:
+ current_app.logger.info(f"Applied naming template for recording {recording_id}: '{final_title}'")
+
+ # Fallback chain: template result → AI title → filename
+ if not final_title:
+ if ai_title:
+ final_title = ai_title
+ elif recording.original_filename:
+ # Use filename without extension as last resort
+ import os
+ final_title = os.path.splitext(recording.original_filename)[0]
+ current_app.logger.info(f"Using filename as title for recording {recording_id}: '{final_title}'")
+
+ if final_title:
+ recording.title = final_title
+ current_app.logger.info(f"Title set for recording {recording_id}: {final_title}")
+ else:
+ current_app.logger.warning(f"Could not generate title for recording {recording_id}")
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- current_app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping title generation.")
- # Only mark as completed if auto-summarization won't happen next
- if not will_auto_summarize:
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- return
+ # Only set status to COMPLETED if auto-summarization won't happen next
+ # If auto-summarization is enabled, the summary task will set COMPLETED
+ if not will_auto_summarize:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+ current_app.logger.info(f"Title generation complete, status set to COMPLETED for recording {recording_id}")
- # Get configurable transcript length limit and format transcription for LLM
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- raw_transcription = recording.transcription
+ # Process chunks for semantic search after completion (if inquire mode is enabled)
+ if ENABLE_INQUIRE_MODE:
+ try:
+ process_recording_chunks(recording_id)
+ except Exception as e:
+ current_app.logger.error(f"Error processing chunks for completed recording {recording_id}: {e}")
else:
- raw_transcription = recording.transcription[:transcript_limit]
+ # Just commit the title without changing status
+ db.session.commit()
+ current_app.logger.info(f"Title generation complete, leaving status unchanged (auto-summarization will follow) for recording {recording_id}")
- # Convert ASR JSON to clean text format
- transcript_text = format_transcription_for_llm(raw_transcription)
+def _generate_ai_title(recording):
+ """Generate an AI title for a recording using LLM.
- # Get user language preference
- user_output_language = None
- if recording.owner:
- user_output_language = recording.owner.output_language
+ Args:
+ recording: Recording model instance
+
+ Returns:
+ Generated title string, or None if generation fails
+ """
+ # Get configurable transcript length limit and format transcription for LLM
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ raw_transcription = recording.transcription
+ else:
+ raw_transcription = recording.transcription[:transcript_limit]
+
+ # Convert ASR JSON to clean text format
+ transcript_text = format_transcription_for_llm(raw_transcription)
+
+ # Get user language preference
+ user_output_language = None
+ if recording.owner:
+ user_output_language = recording.owner.output_language
- language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""
+ language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""
- prompt_text = f"""Create a short title for this conversation:
+ prompt_text = f"""Create a short title for this conversation:
{transcript_text}
@@ -257,67 +325,50 @@ Requirements:
Title:"""
- system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."
- if user_output_language:
- system_message_content += f" Ensure your response is in {user_output_language}."
-
- try:
- completion = call_llm_completion(
- messages=[
- {"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
- ],
- temperature=0.7,
- max_tokens=5000,
- user_id=recording.user_id,
- operation_type='title_generation'
- )
+ system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."
+ if user_output_language:
+ system_message_content += f" Ensure your response is in {user_output_language}."
- raw_response = completion.choices[0].message.content
- reasoning = getattr(completion.choices[0].message, 'reasoning', None)
-
- # Use reasoning content if main content is empty (fallback for reasoning models)
- if not raw_response and reasoning:
- current_app.logger.info(f"Title generation for recording {recording_id}: Using reasoning field as fallback")
- # Try to extract a title from the reasoning field
- lines = reasoning.strip().split('\n')
- # Look for the last line that might be the title
- for line in reversed(lines):
- line = line.strip()
- if line and not line.startswith('I') and len(line.split()) <= 8:
- raw_response = line
- break
-
- title = clean_llm_response(raw_response) if raw_response else ""
-
- if title:
- recording.title = title
- current_app.logger.info(f"Title generated for recording {recording_id}: {title}")
- else:
- current_app.logger.warning(f"Empty title generated for recording {recording_id}")
+ try:
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": system_message_content},
+ {"role": "user", "content": prompt_text}
+ ],
+ temperature=0.7,
+ max_tokens=5000,
+ user_id=recording.user_id,
+ operation_type='title_generation'
+ )
- except Exception as e:
- current_app.logger.error(f"Error generating title for recording {recording_id}: {str(e)}")
- current_app.logger.error(f"Exception details:", exc_info=True)
+ raw_response = completion.choices[0].message.content
+ reasoning = getattr(completion.choices[0].message, 'reasoning', None)
+
+ # Use reasoning content if main content is empty (fallback for reasoning models)
+ if not raw_response and reasoning:
+ current_app.logger.info(f"Title generation for recording {recording.id}: Using reasoning field as fallback")
+ # Try to extract a title from the reasoning field
+ lines = reasoning.strip().split('\n')
+ # Look for the last line that might be the title
+ for line in reversed(lines):
+ line = line.strip()
+ if line and not line.startswith('I') and len(line.split()) <= 8:
+ raw_response = line
+ break
- # Only set status to COMPLETED if auto-summarization won't happen next
- # If auto-summarization is enabled, the summary task will set COMPLETED
- if not will_auto_summarize:
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- current_app.logger.info(f"Title generation complete, status set to COMPLETED for recording {recording_id}")
+ title = clean_llm_response(raw_response) if raw_response else None
- # Process chunks for semantic search after completion (if inquire mode is enabled)
- if ENABLE_INQUIRE_MODE:
- try:
- process_recording_chunks(recording_id)
- except Exception as e:
- current_app.logger.error(f"Error processing chunks for completed recording {recording_id}: {e}")
+ if title:
+ current_app.logger.info(f"AI title generated for recording {recording.id}: {title}")
else:
- # Just commit the title without changing status
- db.session.commit()
- current_app.logger.info(f"Title generation complete, leaving status unchanged (auto-summarization will follow) for recording {recording_id}")
+ current_app.logger.warning(f"Empty AI title generated for recording {recording.id}")
+
+ return title
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating AI title for recording {recording.id}: {str(e)}")
+ current_app.logger.error(f"Exception details:", exc_info=True)
+ return None
def generate_summary_only_task(app_context, recording_id, custom_prompt_override=None, user_id=None):
diff --git a/static/locales/en.json b/static/locales/en.json
index a8df5db3..a3fbd6bc 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -91,6 +91,7 @@
"about": "About",
"apiTokens": "API Tokens",
"customPrompts": "Custom Prompts",
+ "namingTemplates": "Naming",
"promptOptions": "Prompt Options",
"sharedTranscripts": "Shared Transcripts",
"speakersManagement": "Speakers Management",
@@ -141,6 +142,31 @@
"downloadDefault": "Download default",
"chooseTemplate": "Choose template..."
},
+ "namingTemplates": {
+ "title": "Naming Templates",
+ "description": "Define how recording titles are generated from filenames and transcription content.",
+ "createNew": "Create Template",
+ "availableTemplates": "Available Templates",
+ "createDefaults": "Create Default Templates",
+ "templateName": "Template Name",
+ "descriptionLabel": "Description",
+ "template": "Template",
+ "availableVars": "Built-in Variables",
+ "customVarsHint": "Define regex patterns below to extract custom variables from filenames.",
+ "regexPatterns": "Regex Patterns (Optional)",
+ "addPattern": "Add Pattern",
+ "regexHint": "Extract data from filenames. Use capture groups () to specify the match. Example: (\\d{10}) for phone numbers.",
+ "testTemplate": "Test Template",
+ "test": "Test",
+ "result": "Result:",
+ "save": "Save",
+ "cancel": "Cancel",
+ "delete": "Delete",
+ "selectOrCreate": "Select a template to edit or create a new one",
+ "userDefault": "Default Template",
+ "noDefault": "No default (AI title only)",
+ "userDefaultHint": "Applied when no tag has a naming template set."
+ },
"admin": {
"title": "Admin",
"userMenu": "User Menu"
@@ -488,6 +514,9 @@
"leaveBlankPrompt": "Leave blank to use your default summary prompt",
"maxSpeakers": "Max Speakers",
"minSpeakers": "Min Speakers",
+ "namingTemplate": "Naming Template",
+ "namingTemplateHint": "Select a naming template to automatically format titles for recordings with this tag",
+ "noNamingTemplate": "No template (use user default or AI title)",
"tagName": "Tag Name *",
"tagNamePlaceholder": "e.g., Meetings, Interviews",
"title": "Edit Tag"
diff --git a/templates/account.html b/templates/account.html
index 0220dd3e..35274058 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -461,6 +461,9 @@
<a href="#" id="tab-templates" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-file-alt mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.transcriptTemplates">Templates</span>
</a>
+ <a href="#" id="tab-naming-templates" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
+ <i class="fas fa-heading mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.namingTemplates">Naming</span>
+ </a>
<a href="#" id="tab-tokens" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-key mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.apiTokens">API Tokens</span>
</a>
@@ -980,6 +983,133 @@
</div>
</div>
+ <!-- Naming Templates Tab Content -->
+ <div id="content-naming-templates" class="hidden tab-content pt-6">
+ <div class="space-y-6">
+ <!-- Naming 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="namingTemplates.title">Naming Templates</h2>
+ <p class="text-[var(--text-secondary)]" data-i18n="namingTemplates.description">Define how recording titles are generated from filenames and transcription content.</p>
+ </div>
+ <button id="createNamingTemplateBtn" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-plus mr-2"></i>
+ <span data-i18n="namingTemplates.createNew">Create Template</span>
+ </button>
+ </div>
+
+ <!-- Naming Templates Grid -->
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ <!-- Naming 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="namingTemplates.availableTemplates">Available Templates</h3>
+ <div id="namingTemplatesList" class="space-y-2">
+ <!-- Templates will be populated here -->
+ </div>
+ <button id="createDefaultNamingTemplatesBtn" 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="namingTemplates.createDefaults">Create Default Templates</span>
+ </button>
+ </div>
+
+ <!-- User Default Selection -->
+ <div class="mt-4 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="namingTemplates.userDefault">Default Template</h3>
+ <select id="userDefaultNamingTemplate" 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)]">
+ <option value="" data-i18n="namingTemplates.noDefault">No default (AI title only)</option>
+ </select>
+ <p class="mt-2 text-xs text-[var(--text-muted)]" data-i18n="namingTemplates.userDefaultHint">Applied when no tag has a naming template set.</p>
+ </div>
+ </div>
+
+ <!-- Naming Template Editor (Right) -->
+ <div class="lg:col-span-2">
+ <div id="namingTemplateEditor" class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-6 hidden">
+ <form id="namingTemplateForm" class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="namingTemplates.templateName">Template Name</label>
+ <input type="text" id="namingTemplateName" 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="namingTemplates.descriptionLabel">Description</label>
+ <input type="text" id="namingTemplateDescription" 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="namingTemplates.template">Template</label>
+ <input type="text" id="namingTemplateContent" 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 placeholder="{{date}} - {{ai_title}}">
+
+ <!-- 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="namingTemplates.availableVars">Built-in Variables:</p>
+ <div class="flex flex-wrap gap-2 mb-2">
+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded cursor-help" title="AI-generated title from transcription">{{ai_title}}</code>
+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded cursor-help" title="Original filename without extension">{{filename}}</code>
+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded cursor-help" title="Recording date (YYYY-MM-DD)">{{date}}</code>
+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded cursor-help" title="Recording date and time">{{datetime}}</code>
+ <code class="text-xs bg-[var(--bg-primary)] px-2 py-1 rounded cursor-help" title="Time only (HH:MM)">{{time}}</code>
+ </div>
+ <p class="text-xs text-[var(--text-muted)]" data-i18n="namingTemplates.customVarsHint">Define regex patterns below to extract custom variables from filenames.</p>
+ </div>
+ </div>
+
+ <!-- Regex Patterns -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="namingTemplates.regexPatterns">Regex Patterns (Optional)</label>
+ <div id="regexPatternsContainer" class="space-y-2">
+ <!-- Regex patterns will be added here dynamically -->
+ </div>
+ <button type="button" id="addRegexPatternBtn" class="mt-2 text-sm text-[var(--text-accent)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-plus mr-1"></i>
+ <span data-i18n="namingTemplates.addPattern">Add Pattern</span>
+ </button>
+ <p class="mt-1 text-xs text-[var(--text-muted)]" data-i18n="namingTemplates.regexHint">Extract data from filenames. Use capture groups () to specify the match. Example: (\d{10}) for phone numbers.</p>
+ </div>
+
+ <!-- Test Section -->
+ <div class="border-t border-[var(--border-primary)] pt-4 mt-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="namingTemplates.testTemplate">Test Template</label>
+ <div class="flex gap-2">
+ <input type="text" id="testFilename" class="flex-1 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)] text-sm" placeholder="sample-file-name.mp3">
+ <button type="button" id="testNamingTemplateBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-accent-light)]">
+ <i class="fas fa-play mr-1"></i>
+ <span data-i18n="namingTemplates.test">Test</span>
+ </button>
+ </div>
+ <div id="testResult" class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded-md hidden">
+ <p class="text-xs text-[var(--text-muted)]" data-i18n="namingTemplates.result">Result:</p>
+ <p id="testResultText" class="text-sm text-[var(--text-primary)] font-medium"></p>
+ </div>
+ </div>
+
+ <div class="flex gap-3">
+ <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-save mr-2"></i>
+ <span data-i18n="namingTemplates.save">Save</span>
+ </button>
+ <button type="button" id="cancelNamingTemplateBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-secondary)]">
+ <span data-i18n="namingTemplates.cancel">Cancel</span>
+ </button>
+ <button type="button" id="deleteNamingTemplateBtn" class="px-4 py-2 bg-[var(--bg-danger)] text-white rounded-md hover:bg-[var(--bg-danger-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors duration-200 hidden">
+ <i class="fas fa-trash mr-2"></i>
+ <span data-i18n="namingTemplates.delete">Delete</span>
+ </button>
+ </div>
+ </form>
+ </div>
+
+ <!-- Empty State -->
+ <div id="namingTemplateEmptyState" class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-12 text-center">
+ <i class="fas fa-heading text-4xl text-[var(--text-muted)] mb-4"></i>
+ <p class="text-[var(--text-muted)]" data-i18n="namingTemplates.selectOrCreate">Select a template to edit or create a new one</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- API Tokens Tab Content -->
<div id="content-tokens" class="hidden tab-content pt-6">
<div class="space-y-6">
@@ -1664,6 +1794,16 @@ 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.leaveBlankPrompt">Leave blank to use your default summary prompt</p>
</div>
+ <!-- Naming Template Selection -->
+ <div>
+ <label for="tagNamingTemplate" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="editTagModal.namingTemplate">Naming Template</label>
+ <select id="tagNamingTemplate" name="naming_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.noNamingTemplate">No template (use user default or AI title)</option>
+ <!-- Naming template options will be populated dynamically -->
+ </select>
+ <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>
+
<!-- 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>
@@ -2089,6 +2229,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
const tabShares = document.getElementById('tab-shares');
const tabTags = document.getElementById('tab-tags');
const tabTemplates = document.getElementById('tab-templates');
+ const tabNamingTemplates = document.getElementById('tab-naming-templates');
const tabTokens = document.getElementById('tab-tokens');
const tabAbout = document.getElementById('tab-about');
const contentAccount = document.getElementById('content-account');
@@ -2097,6 +2238,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
const contentSpeakers = document.getElementById('content-speakers');
const contentTags = document.getElementById('content-tags');
const contentTemplates = document.getElementById('content-templates');
+ const contentNamingTemplates = document.getElementById('content-naming-templates');
const contentTokens = document.getElementById('content-tokens');
const contentAbout = document.getElementById('content-about');
const sharesContainer = document.getElementById('shares-container');
@@ -2112,6 +2254,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
{ tab: tabSpeakers, content: contentSpeakers, name: 'speakers' },
{ tab: tabTags, content: contentTags, name: 'tags' },
{ tab: tabTemplates, content: contentTemplates, name: 'templates' },
+ { tab: tabNamingTemplates, content: contentNamingTemplates, name: 'naming-templates' },
{ tab: tabTokens, content: contentTokens, name: 'tokens' },
{ tab: tabAbout, content: contentAbout, name: 'about' }
];
@@ -2140,6 +2283,8 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
loadTags();
} else if (targetName === 'templates') {
loadTemplates();
+ } else if (targetName === 'naming-templates') {
+ loadNamingTemplates();
} else if (targetName === 'tokens') {
loadTokensTab();
} else if (targetName === 'about') {
@@ -2171,6 +2316,10 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
switchToTab('templates');
}
+ function showNamingTemplatesTab() {
+ switchToTab('naming-templates');
+ }
+
function showTokensTab() {
switchToTab('tokens');
}
@@ -2209,6 +2358,11 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
showTemplatesTab();
});
+ tabNamingTemplates.addEventListener('click', (e) => {
+ e.preventDefault();
+ showNamingTemplatesTab();
+ });
+
tabTokens.addEventListener('click', (e) => {
e.preventDefault();
showTokensTab();
@@ -3931,6 +4085,11 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (document.getElementById('tagMaxSpeakers')) {
document.getElementById('tagMaxSpeakers').value = tag.default_max_speakers || '';
}
+
+ // Populate naming template
+ if (document.getElementById('tagNamingTemplate')) {
+ document.getElementById('tagNamingTemplate').value = tag.naming_template_id || '';
+ }
} else {
// Create mode
isEditingTag = false;
@@ -3966,11 +4125,56 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (protectCheck) {
protectCheck.checked = false;
}
+
+ // Reset naming template
+ if (document.getElementById('tagNamingTemplate')) {
+ document.getElementById('tagNamingTemplate').value = '';
+ }
}
+ // Load naming templates for dropdown
+ loadNamingTemplatesForTagModal();
+
tagModal.classList.remove('hidden');
}
+ // Load naming templates for the tag modal dropdown
+ async function loadNamingTemplatesForTagModal() {
+ const select = document.getElementById('tagNamingTemplate');
+ if (!select) return;
+
+ try {
+ const response = await fetch('/api/naming-templates');
+ if (!response.ok) return;
+
+ const templates = await response.json();
+
+ // Preserve current selection
+ const currentValue = select.value;
+
+ // Clear all options except the first one
+ select.innerHTML = '<option value="">No template (use user default or AI title)</option>';
+
+ // Add template options
+ templates.forEach(template => {
+ const option = document.createElement('option');
+ option.value = template.id;
+ option.textContent = template.name;
+ if (template.description) {
+ option.title = template.description;
+ }
+ select.appendChild(option);
+ });
+
+ // Restore selection
+ if (currentValue) {
+ select.value = currentValue;
+ }
+ } catch (error) {
+ console.error('Error loading naming templates for tag modal:', error);
+ }
+ }
+
// Edit tag
function editTag(tag) {
openTagModal(tag);
@@ -4027,10 +4231,12 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
retentionDays = retentionInput ? parseInt(retentionInput) : null;
}
+ const namingTemplateId = formData.get('naming_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,
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,
@@ -4768,6 +4974,383 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
}
});
+ // ============================================
+ // Naming Templates Management
+ // ============================================
+ let namingTemplates = [];
+ let currentNamingTemplate = null;
+ let isEditingNamingTemplate = false;
+ let userDefaultNamingTemplateId = null;
+
+ async function loadNamingTemplates() {
+ try {
+ const [templatesRes, defaultRes] = await Promise.all([
+ fetch('/api/naming-templates'),
+ fetch('/api/naming-templates/default')
+ ]);
+
+ if (!templatesRes.ok) {
+ throw new Error('Failed to load naming templates');
+ }
+
+ namingTemplates = await templatesRes.json();
+
+ if (defaultRes.ok) {
+ const defaultData = await defaultRes.json();
+ userDefaultNamingTemplateId = defaultData.default_naming_template_id;
+ }
+
+ // Show/hide create defaults button
+ if (namingTemplates.length === 0) {
+ document.getElementById('createDefaultNamingTemplatesBtn').style.display = 'block';
+ } else {
+ document.getElementById('createDefaultNamingTemplatesBtn').style.display = 'none';
+ }
+
+ renderNamingTemplatesList();
+ updateUserDefaultSelect();
+ } catch (error) {
+ console.error('Error loading naming templates:', error);
+ showToast('Failed to load naming templates', 'error');
+ }
+ }
+
+ function renderNamingTemplatesList() {
+ const list = document.getElementById('namingTemplatesList');
+ list.innerHTML = '';
+
+ if (namingTemplates.length === 0) {
+ list.innerHTML = '<p class="text-sm text-[var(--text-muted)] text-center py-4">No templates yet</p>';
+ return;
+ }
+
+ namingTemplates.forEach(template => {
+ const item = document.createElement('div');
+ item.className = 'p-3 bg-[var(--bg-primary)] rounded-md hover:bg-[var(--bg-tertiary)] cursor-pointer transition-colors border border-[var(--border-primary)]';
+ if (userDefaultNamingTemplateId === template.id) {
+ item.className += ' ring-2 ring-[var(--ring-focus)]';
+ }
+
+ const nameEl = document.createElement('h4');
+ nameEl.className = 'text-sm font-medium text-[var(--text-primary)]';
+ nameEl.textContent = template.name;
+
+ const templateEl = document.createElement('p');
+ templateEl.className = 'text-xs text-[var(--text-muted)] mt-1 font-mono';
+ templateEl.textContent = template.template;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'flex items-start justify-between';
+ const inner = document.createElement('div');
+ inner.className = 'flex-1';
+ inner.appendChild(nameEl);
+ inner.appendChild(templateEl);
+
+ if (template.description) {
+ const descEl = document.createElement('p');
+ descEl.className = 'text-xs text-[var(--text-muted)] mt-1';
+ descEl.textContent = template.description;
+ inner.appendChild(descEl);
+ }
+
+ if (userDefaultNamingTemplateId === template.id) {
+ const defaultEl = document.createElement('span');
+ defaultEl.className = 'text-xs text-[var(--text-accent)] mt-1';
+ defaultEl.innerHTML = '<i class="fas fa-star mr-1"></i>Default';
+ inner.appendChild(defaultEl);
+ }
+
+ wrapper.appendChild(inner);
+ item.appendChild(wrapper);
+
+ item.addEventListener('click', () => selectNamingTemplate(template));
+ list.appendChild(item);
+ });
+ }
+
+ function updateUserDefaultSelect() {
+ const select = document.getElementById('userDefaultNamingTemplate');
+ select.innerHTML = '<option value="">No default (AI title only)</option>';
+
+ namingTemplates.forEach(template => {
+ const option = document.createElement('option');
+ option.value = template.id;
+ option.textContent = template.name;
+ if (userDefaultNamingTemplateId === template.id) {
+ option.selected = true;
+ }
+ select.appendChild(option);
+ });
+ }
+
+ document.getElementById('userDefaultNamingTemplate')?.addEventListener('change', async (e) => {
+ const templateId = e.target.value ? parseInt(e.target.value) : null;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch('/api/naming-templates/default', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ template_id: templateId })
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to update default template');
+ }
+
+ userDefaultNamingTemplateId = templateId;
+ renderNamingTemplatesList();
+ showToast('Default naming template updated', 'success');
+ } catch (error) {
+ console.error('Error updating default template:', error);
+ showToast('Failed to update default template', 'error');
+ }
+ });
+
+ function selectNamingTemplate(template) {
+ currentNamingTemplate = template;
+ isEditingNamingTemplate = true;
+
+ document.getElementById('namingTemplateEditor').classList.remove('hidden');
+ document.getElementById('namingTemplateEmptyState').classList.add('hidden');
+
+ document.getElementById('namingTemplateName').value = template.name;
+ document.getElementById('namingTemplateDescription').value = template.description || '';
+ document.getElementById('namingTemplateContent').value = template.template;
+
+ // Populate regex patterns
+ renderRegexPatterns(template.regex_patterns || {});
+
+ document.getElementById('deleteNamingTemplateBtn').classList.remove('hidden');
+ }
+
+ function createNewNamingTemplate() {
+ currentNamingTemplate = null;
+ isEditingNamingTemplate = false;
+
+ document.getElementById('namingTemplateEditor').classList.remove('hidden');
+ document.getElementById('namingTemplateEmptyState').classList.add('hidden');
+
+ document.getElementById('namingTemplateForm').reset();
+ renderRegexPatterns({});
+
+ document.getElementById('deleteNamingTemplateBtn').classList.add('hidden');
+ }
+
+ function renderRegexPatterns(patterns) {
+ const container = document.getElementById('regexPatternsContainer');
+ container.innerHTML = '';
+
+ Object.entries(patterns).forEach(([varName, pattern]) => {
+ addRegexPatternRow(varName, pattern);
+ });
+ }
+
+ function addRegexPatternRow(varName = '', pattern = '') {
+ const container = document.getElementById('regexPatternsContainer');
+ const row = document.createElement('div');
+ row.className = 'flex gap-2 items-center';
+
+ const varInput = document.createElement('input');
+ varInput.type = 'text';
+ varInput.placeholder = 'Variable name';
+ varInput.value = varName;
+ varInput.className = 'flex-1 px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md regex-var-name';
+
+ const patternInput = document.createElement('input');
+ patternInput.type = 'text';
+ patternInput.placeholder = 'Regex pattern';
+ patternInput.value = pattern;
+ patternInput.className = 'flex-2 px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md regex-pattern font-mono';
+
+ const removeBtn = document.createElement('button');
+ removeBtn.type = 'button';
+ removeBtn.className = 'text-[var(--text-danger)] hover:text-[var(--text-danger-hover)] remove-regex-btn';
+ removeBtn.innerHTML = '<i class="fas fa-times"></i>';
+ removeBtn.addEventListener('click', () => row.remove());
+
+ row.appendChild(varInput);
+ row.appendChild(patternInput);
+ row.appendChild(removeBtn);
+ container.appendChild(row);
+ }
+
+ document.getElementById('addRegexPatternBtn')?.addEventListener('click', () => addRegexPatternRow());
+
+ document.getElementById('createNamingTemplateBtn')?.addEventListener('click', createNewNamingTemplate);
+
+ document.getElementById('cancelNamingTemplateBtn')?.addEventListener('click', () => {
+ document.getElementById('namingTemplateEditor').classList.add('hidden');
+ document.getElementById('namingTemplateEmptyState').classList.remove('hidden');
+ currentNamingTemplate = null;
+ isEditingNamingTemplate = false;
+ });
+
+ document.getElementById('namingTemplateForm')?.addEventListener('submit', async (e) => {
+ e.preventDefault();
+
+ // Collect regex patterns
+ const regexPatterns = {};
+ document.querySelectorAll('#regexPatternsContainer > div').forEach(row => {
+ const varName = row.querySelector('.regex-var-name').value.trim();
+ const pattern = row.querySelector('.regex-pattern').value.trim();
+ if (varName && pattern) {
+ regexPatterns[varName] = pattern;
+ }
+ });
+
+ const templateData = {
+ name: document.getElementById('namingTemplateName').value,
+ description: document.getElementById('namingTemplateDescription').value,
+ template: document.getElementById('namingTemplateContent').value,
+ regex_patterns: regexPatterns
+ };
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const url = isEditingNamingTemplate ? `/api/naming-templates/${currentNamingTemplate.id}` : '/api/naming-templates';
+ const method = isEditingNamingTemplate ? '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 naming template');
+ }
+
+ const savedTemplate = await response.json();
+
+ if (isEditingNamingTemplate) {
+ const index = namingTemplates.findIndex(t => t.id === savedTemplate.id);
+ if (index !== -1) {
+ namingTemplates[index] = savedTemplate;
+ }
+ } else {
+ namingTemplates.push(savedTemplate);
+ }
+
+ renderNamingTemplatesList();
+ updateUserDefaultSelect();
+ showToast(isEditingNamingTemplate ? 'Naming template updated' : 'Naming template created', 'success');
+
+ document.getElementById('namingTemplateEditor').classList.add('hidden');
+ document.getElementById('namingTemplateEmptyState').classList.remove('hidden');
+ currentNamingTemplate = null;
+ isEditingNamingTemplate = false;
+ } catch (error) {
+ console.error('Error saving naming template:', error);
+ showToast(error.message || 'Failed to save naming template', 'error');
+ }
+ });
+
+ document.getElementById('deleteNamingTemplateBtn')?.addEventListener('click', async () => {
+ if (!currentNamingTemplate || !confirm('Are you sure you want to delete this naming template?')) {
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/naming-templates/${currentNamingTemplate.id}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to delete naming template');
+ }
+
+ namingTemplates = namingTemplates.filter(t => t.id !== currentNamingTemplate.id);
+
+ if (userDefaultNamingTemplateId === currentNamingTemplate.id) {
+ userDefaultNamingTemplateId = null;
+ }
+
+ renderNamingTemplatesList();
+ updateUserDefaultSelect();
+
+ document.getElementById('namingTemplateEditor').classList.add('hidden');
+ document.getElementById('namingTemplateEmptyState').classList.remove('hidden');
+ currentNamingTemplate = null;
+ isEditingNamingTemplate = false;
+
+ showToast('Naming template deleted', 'success');
+ } catch (error) {
+ console.error('Error deleting naming template:', error);
+ showToast(error.message || 'Failed to delete naming template', 'error');
+ }
+ });
+
+ document.getElementById('createDefaultNamingTemplatesBtn')?.addEventListener('click', async () => {
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch('/api/naming-templates/create-defaults', {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to create default naming templates');
+ }
+
+ const result = await response.json();
+ namingTemplates = result.templates;
+ renderNamingTemplatesList();
+ updateUserDefaultSelect();
+ showToast('Default naming templates created', 'success');
+ } catch (error) {
+ console.error('Error creating default naming templates:', error);
+ showToast('Failed to create default naming templates', 'error');
+ }
+ });
+
+ document.getElementById('testNamingTemplateBtn')?.addEventListener('click', async () => {
+ const templateId = currentNamingTemplate?.id;
+ const testFilename = document.getElementById('testFilename').value || 'sample-file.mp3';
+
+ if (!templateId) {
+ showToast('Save the template first to test it', 'info');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/naming-templates/${templateId}/test`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ filename: testFilename, ai_title: 'Sample AI Title' })
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to test template');
+ }
+
+ const result = await response.json();
+ document.getElementById('testResult').classList.remove('hidden');
+ document.getElementById('testResultText').textContent = result.result;
+ } catch (error) {
+ console.error('Error testing template:', error);
+ showToast('Failed to test template', 'error');
+ }
+ });
+
function showToast(message, type = 'info') {
// Simple toast notification
const toast = document.createElement('div');