Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add transcription initial-prompt template library with CRUD API and admin default initial prompt (#309)
Murtaza Nasir1be430bb1380
diff --git a/src/api/initial_prompt_templates.py b/src/api/initial_prompt_templates.pynew file mode 100644index 00000000..1ac8b456--- /dev/null+++ b/src/api/initial_prompt_templates.py@@ -0,0 +1,150 @@+"""+Initial-prompt template management.++CRUD for user-defined, reusable transcription initial-prompt texts. Mirrors the+transcript/export/naming template blueprints: user-scoped, JSON in/out, a single+is_default per user, and a create-defaults seeding endpoint. Plain text only —+these are ASR hints, not summarization prompts, and carry no variables.+"""++from datetime import datetime+from flask import Blueprint, request, jsonify+from flask_login import login_required, current_user++from src.database import db+from src.models import InitialPromptTemplate++# Create blueprint+initial_prompt_templates_bp = Blueprint('initial_prompt_templates', __name__)+++@initial_prompt_templates_bp.route('/api/initial-prompt-templates', methods=['GET'])+@login_required+def get_initial_prompt_templates():+ """Get all initial-prompt templates for the current user."""+ templates = InitialPromptTemplate.query.filter_by(user_id=current_user.id).all()+ return jsonify([template.to_dict() for template in templates])+++@initial_prompt_templates_bp.route('/api/initial-prompt-templates', methods=['POST'])+@login_required+def create_initial_prompt_template():+ """Create a new initial-prompt 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'):+ InitialPromptTemplate.query.filter_by(+ user_id=current_user.id,+ is_default=True+ ).update({'is_default': False})++ template = InitialPromptTemplate(+ 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+++@initial_prompt_templates_bp.route('/api/initial-prompt-templates/<int:template_id>', methods=['PUT'])+@login_required+def update_initial_prompt_template(template_id):+ """Update an existing initial-prompt template."""+ template = InitialPromptTemplate.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'):+ InitialPromptTemplate.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())+++@initial_prompt_templates_bp.route('/api/initial-prompt-templates/<int:template_id>', methods=['DELETE'])+@login_required+def delete_initial_prompt_template(template_id):+ """Delete an initial-prompt template."""+ template = InitialPromptTemplate.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})+++@initial_prompt_templates_bp.route('/api/initial-prompt-templates/create-defaults', methods=['POST'])+@login_required+def create_default_initial_prompt_templates():+ """Seed a few starter initial-prompt templates if the user has none."""+ existing = InitialPromptTemplate.query.filter_by(user_id=current_user.id).count()+ if existing > 0:+ return jsonify({'message': 'User already has templates'}), 200++ starters = [+ ('Business meeting',+ 'This is a business meeting.',+ 'Generic business meeting context'),+ ('Interview',+ 'This is an interview between an interviewer and an interviewee.',+ 'One-on-one interview context'),+ ('Podcast',+ 'This is a podcast episode with hosts and guests having a conversation.',+ 'Podcast / multi-speaker conversation context'),+ ('Lecture',+ 'This is an academic lecture given by a single speaker.',+ 'Single-speaker lecture or presentation context'),+ ]++ templates = []+ for idx, (name, text, description) in enumerate(starters):+ templates.append(InitialPromptTemplate(+ user_id=current_user.id,+ name=name,+ template=text,+ description=description,+ is_default=(idx == 0),+ ))++ for template in templates:+ db.session.add(template)+ db.session.commit()++ return jsonify({+ 'success': True,+ 'templates': [template.to_dict() for template in templates]+ }), 201diff --git a/src/app.py b/src/app.pyindex f2c1b69e..1e96ff6c 100644--- a/src/app.py+++ b/src/app.py@@ -605,6 +605,7 @@ from src.api.inquire import inquire_bp, init_inquire_helpersfrom src.api.templates import templates_bp, init_templates_helpersfrom src.api.naming_templates import naming_templates_bpfrom src.api.export_templates import export_templates_bp+from src.api.initial_prompt_templates import initial_prompt_templates_bpfrom src.api.events import events_bp, init_events_helpersfrom src.api.system import system_bp, init_system_helpersfrom src.api.push_notifications import push_bp@@ -651,6 +652,7 @@ app.register_blueprint(inquire_bp)app.register_blueprint(templates_bp)app.register_blueprint(naming_templates_bp)app.register_blueprint(export_templates_bp)+app.register_blueprint(initial_prompt_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.pyindex 37b72f5d..a0737437 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -728,6 +728,15 @@ def initialize_database(app):)app.logger.info("Initialized admin_default_hotwords setting")+ if not SystemSetting.query.filter_by(key='admin_default_initial_prompt').first():+ SystemSetting.set_setting(+ key='admin_default_initial_prompt',+ value='',+ description='Global initial prompt injected into all transcription requests. Applied when users have not set their own initial prompt.',+ setting_type='string'+ )+ app.logger.info("Initialized admin_default_initial_prompt setting")+if not SystemSetting.query.filter_by(key='enable_folders').first():SystemSetting.set_setting(key='enable_folders',diff --git a/src/models/__init__.py b/src/models/__init__.pyindex 3ed3e257..d1666f2c 100644--- a/src/models/__init__.py+++ b/src/models/__init__.py@@ -24,6 +24,7 @@ from .events import Eventfrom .templates import TranscriptTemplatefrom .naming_template import NamingTemplatefrom .export_template import ExportTemplate+from .initial_prompt_template import InitialPromptTemplatefrom .inquire import InquireSessionfrom .system import SystemSettingfrom .audit import ShareAuditLog@@ -68,6 +69,7 @@ __all__ = ['TranscriptTemplate','NamingTemplate','ExportTemplate',+ 'InitialPromptTemplate','InquireSession','SystemSetting','PushSubscription',diff --git a/src/models/initial_prompt_template.py b/src/models/initial_prompt_template.pynew file mode 100644index 00000000..d5035a22--- /dev/null+++ b/src/models/initial_prompt_template.py@@ -0,0 +1,39 @@+"""+InitialPromptTemplate model for user-defined transcription initial prompts.++These are reusable, plain-text ASR "initial prompt" hints (the context line+sent to the transcription engine to steer recognition). They are distinct from+summarization prompts and carry no {{variable}} substitution — they are plain+text, picked at upload time or used to fill tag/folder/account defaults.+"""++from datetime import datetime+from src.database import db+++class InitialPromptTemplate(db.Model):+ """Stores user-defined, reusable transcription initial-prompt texts."""++ 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('initial_prompt_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,+ '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+ }diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 63663230..7bcf47bb 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -1641,6 +1641,16 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_filehotwords = resolved_hotwordscurrent_app.logger.debug(f"Using admin default hotwords: {hotwords}")+ # Fall back to admin default initial prompt if none provided (mirrors+ # the hotwords fallback above; resolve_hotwords is a generic+ # "explicit value wins, else admin default" helper).+ resolved_initial_prompt = resolve_hotwords(+ initial_prompt, SystemSetting.get_setting('admin_default_initial_prompt', '')+ )+ if resolved_initial_prompt != initial_prompt:+ initial_prompt = resolved_initial_prompt+ current_app.logger.debug("Using admin default initial prompt")+# Persist the effective hints actually used for this transcription so# the UI can surface them and pre-fill them on reprocess (issue #309).# At this point hotwords and initial_prompt hold their final values,diff --git a/tests/test_cov_initial_prompt_templates.py b/tests/test_cov_initial_prompt_templates.pynew file mode 100644index 00000000..944f83c4--- /dev/null+++ b/tests/test_cov_initial_prompt_templates.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""+Coverage tests for src/api/initial_prompt_templates.py (issue #309).++User-scoped CRUD for reusable transcription initial-prompt texts. Mirrors the+transcript/export/naming template blueprints. Pattern follows tests/test_cov_admin.py:+isolated DB via repo-root conftest, login by session injection, hermetic/offline.++Run:+ docker run --rm -v $PWD:/app:ro -e UPLOAD_FOLDER=/tmp/up \+ -e ASR_BASE_URL=http://x:9999 speakr-test:cov \+ sh -c "cd /app && python -m pytest tests/test_cov_initial_prompt_templates.py -q"+"""++import uuid++import pytest++from src.app import app, db+from src.models import User, InitialPromptTemplate++app.config['WTF_CSRF_ENABLED'] = False+app.config['TESTING'] = True+++def _mk_user():+ suffix = uuid.uuid4().hex[:8]+ u = User(username=f"u_{suffix}", email=f"{suffix}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ return u+++def _login(client, user):+ with client.session_transaction() as s:+ s['_user_id'] = str(user.id)+ s['_fresh'] = True+++def ctx():+ with app.app_context():+ yield+++def user(ctx):+ u = _mk_user()+ yield u+ InitialPromptTemplate.query.filter_by(user_id=u.id).delete()+ db.session.delete(u)+ db.session.commit()+++def client(user):+ c = app.test_client()+ _login(c, user)+ return c+++def test_requires_auth():+ c = app.test_client()+ assert c.get('/api/initial-prompt-templates').status_code in (401, 302)+++def test_create_and_list(client, user):+ resp = client.post('/api/initial-prompt-templates',+ json={'name': 'Meeting', 'template': 'This is a meeting.'})+ assert resp.status_code == 201+ created = resp.get_json()+ assert created['name'] == 'Meeting'+ assert created['template'] == 'This is a meeting.'++ listing = client.get('/api/initial-prompt-templates').get_json()+ assert any(t['id'] == created['id'] for t in listing)+++def test_create_requires_name_and_template(client):+ assert client.post('/api/initial-prompt-templates', json={'name': 'x'}).status_code == 400+ assert client.post('/api/initial-prompt-templates', json={'template': 'x'}).status_code == 400+++def test_single_default_enforced(client, user):+ a = client.post('/api/initial-prompt-templates',+ json={'name': 'A', 'template': 'a', 'is_default': True}).get_json()+ b = client.post('/api/initial-prompt-templates',+ json={'name': 'B', 'template': 'b', 'is_default': True}).get_json()+ # Creating B as default must demote A.+ defaults = [t for t in client.get('/api/initial-prompt-templates').get_json() if t['is_default']]+ assert len(defaults) == 1+ assert defaults[0]['id'] == b['id']+++def test_update(client):+ t = client.post('/api/initial-prompt-templates',+ json={'name': 'A', 'template': 'a'}).get_json()+ resp = client.put(f"/api/initial-prompt-templates/{t['id']}",+ json={'name': 'A2', 'template': 'a2'})+ assert resp.status_code == 200+ assert resp.get_json()['name'] == 'A2'+ assert resp.get_json()['template'] == 'a2'+++def test_delete(client):+ t = client.post('/api/initial-prompt-templates',+ json={'name': 'A', 'template': 'a'}).get_json()+ assert client.delete(f"/api/initial-prompt-templates/{t['id']}").status_code == 200+ assert client.delete(f"/api/initial-prompt-templates/{t['id']}").status_code == 404+++def test_cannot_touch_other_users_template(client, ctx):+ other = _mk_user()+ try:+ foreign = InitialPromptTemplate(user_id=other.id, name='X', template='x')+ db.session.add(foreign)+ db.session.commit()+ fid = foreign.id+ # The logged-in user (client) must not see, edit, or delete it.+ assert all(t['id'] != fid for t in client.get('/api/initial-prompt-templates').get_json())+ assert client.put(f'/api/initial-prompt-templates/{fid}', json={'name': 'hack'}).status_code == 404+ assert client.delete(f'/api/initial-prompt-templates/{fid}').status_code == 404+ finally:+ InitialPromptTemplate.query.filter_by(user_id=other.id).delete()+ db.session.delete(other)+ db.session.commit()+++def test_create_defaults_seeds_then_noops(client):+ resp = client.post('/api/initial-prompt-templates/create-defaults')+ assert resp.status_code == 201+ seeded = resp.get_json()['templates']+ assert len(seeded) >= 1+ assert sum(1 for t in seeded if t['is_default']) == 1+ # Second call is a no-op because the user now has templates.+ again = client.post('/api/initial-prompt-templates/create-defaults')+ assert again.status_code == 200diff --git a/tests/test_cov_processing.py b/tests/test_cov_processing.pyindex f5696082..b14a3218 100644--- a/tests/test_cov_processing.py+++ b/tests/test_cov_processing.py@@ -628,6 +628,49 @@ def test_transcribe_with_connector_resolved_hints_default_none():assert out.resolved_initial_prompt is None+def test_transcribe_with_connector_applies_admin_default_initial_prompt():+ """With no initial prompt supplied, the admin default is applied + persisted (#309)."""+ import time as _time+ with app.app_context():+ user = _make_user("trans_admin_ip")+ rec = _make_recording(user.id, transcription=None, status="PENDING")+ rid = rec.id+ connector = _make_connector(text="Body.")++ tmp_path = os.path.join(app.config["UPLOAD_FOLDER"], f"admin_ip_{rid}.mp3")+ with open(tmp_path, "wb") as f:+ f.write(b"\x00" * 1024)+ conv_result = MagicMock()+ conv_result.was_converted = False++ def _fake_setting(key, default=None):+ if key == "admin_default_initial_prompt":+ return "This is a board meeting."+ if key == "admin_default_hotwords":+ return ""+ return default++ with patch("src.services.transcription.get_connector", return_value=connector), \+ patch.object(proc, "is_video_file", return_value=False), \+ patch.object(proc, "convert_if_needed", return_value=conv_result), \+ patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "ENABLE_INQUIRE_MODE", False), \+ patch.object(proc, "generate_title_task"), \+ patch.object(proc, "generate_summary_only_task"), \+ patch.object(proc, "chunking_service") as mock_chunk_svc, \+ patch.object(proc.SystemSetting, "get_setting", side_effect=_fake_setting):+ mock_chunk_svc.needs_chunking.return_value = False+ mock_chunk_svc.get_audio_duration.return_value = 120.0+ proc.transcribe_with_connector(+ app.app_context(), rid, tmp_path, "cov.mp3", _time.time(),+ mime_type="audio/mpeg",+ )++ db.session.expire_all()+ out = db.session.get(Recording, rid)+ assert out.resolved_initial_prompt == "This is a board meeting."++def test_transcribe_with_connector_budget_exceeded_sets_failed():import time as _timewith app.app_context():