Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: configurable AI title instructions at tag, folder, user and admin level with the same precedence as the summary prompt, used for regular and incognito titles and exposed through the tag, folder, account and API v1 endpoints (#400)
Murtaza Nasir05126f19d6e2
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 6cf0f7fe..cca1dbd3 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -155,6 +155,7 @@ OPENAPI_SPEC = {"name": {"type": "string"},"color": {"type": "string"},"custom_prompt": {"type": "string"},+ "title_prompt": {"type": "string"},"default_language": {"type": "string"},"default_min_speakers": {"type": "integer"},"default_max_speakers": {"type": "integer"},@@ -172,6 +173,7 @@ OPENAPI_SPEC = {"group_id": {"type": "integer", "nullable": True},"is_group_folder": {"type": "boolean"},"custom_prompt": {"type": "string"},+ "title_prompt": {"type": "string"},"default_language": {"type": "string"},"default_min_speakers": {"type": "integer"},"default_max_speakers": {"type": "integer"},@@ -412,19 +414,19 @@ OPENAPI_SPEC = {},"/tags": {"get": {"tags": ["Tags"], "summary": "List tags", "responses": {"200": {"description": "List of tags"}}},- "post": {"tags": ["Tags"], "summary": "Create tag", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}}}}}}, "responses": {"201": {"description": "Tag created"}}}+ "post": {"tags": ["Tags"], "summary": "Create tag", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "title_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}}}}}}, "responses": {"201": {"description": "Tag created"}}}},"/tags/{id}": {- "put": {"tags": ["Tags"], "summary": "Update tag", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}}}}}}, "responses": {"200": {"description": "Tag updated"}}},+ "put": {"tags": ["Tags"], "summary": "Update tag", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "title_prompt": {"type": "string"}}}}}}, "responses": {"200": {"description": "Tag updated"}}},"delete": {"tags": ["Tags"], "summary": "Delete tag", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Tag deleted"}}}},"/folders": {"get": {"tags": ["Folders"], "summary": "List folders", "responses": {"200": {"description": "Array of folders the user can access", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/Folder"}}}}}}},- "post": {"tags": ["Folders"], "summary": "Create folder", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "group_id": {"type": "integer", "nullable": True}, "custom_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}, "default_hotwords": {"type": "string"}, "default_initial_prompt": {"type": "string"}, "default_transcription_model": {"type": "string"}, "retention_days": {"type": "integer"}}}}}}, "responses": {"201": {"description": "Folder created"}}}+ "post": {"tags": ["Folders"], "summary": "Create folder", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "group_id": {"type": "integer", "nullable": True}, "custom_prompt": {"type": "string"}, "title_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}, "default_hotwords": {"type": "string"}, "default_initial_prompt": {"type": "string"}, "default_transcription_model": {"type": "string"}, "retention_days": {"type": "integer"}}}}}}, "responses": {"201": {"description": "Folder created"}}}},"/folders/{id}": {"get": {"tags": ["Folders"], "summary": "Get folder", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Folder", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Folder"}}}}}},- "patch": {"tags": ["Folders"], "summary": "Update folder", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}, "default_hotwords": {"type": "string"}, "default_initial_prompt": {"type": "string"}, "default_transcription_model": {"type": "string"}, "retention_days": {"type": "integer"}}}}}}, "responses": {"200": {"description": "Folder updated"}}},+ "patch": {"tags": ["Folders"], "summary": "Update folder", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "title_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}, "default_hotwords": {"type": "string"}, "default_initial_prompt": {"type": "string"}, "default_transcription_model": {"type": "string"}, "retention_days": {"type": "integer"}}}}}}, "responses": {"200": {"description": "Folder updated"}}},"delete": {"tags": ["Folders"], "summary": "Delete folder", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Folder deleted"}}}},"/transcription": {@@ -1468,6 +1470,7 @@ def list_tags():'is_group_tag': False,'group_id': None,'custom_prompt': tag.custom_prompt,+ 'title_prompt': tag.title_prompt,'default_language': tag.default_language,'default_min_speakers': tag.default_min_speakers,'default_max_speakers': tag.default_max_speakers,@@ -1485,6 +1488,7 @@ def list_tags():'is_group_tag': True,'group_id': tag.group_id,'custom_prompt': tag.custom_prompt,+ 'title_prompt': tag.title_prompt,'default_language': tag.default_language,'default_min_speakers': tag.default_min_speakers,'default_max_speakers': tag.default_max_speakers,@@ -1532,6 +1536,7 @@ def create_tag():group_id=group_id,color=data.get('color', '#3B82F6'),custom_prompt=data.get('custom_prompt'),+ title_prompt=data.get('title_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),default_max_speakers=data.get('default_max_speakers'),@@ -1548,6 +1553,7 @@ def create_tag():'is_group_tag': tag.group_id is not None,'group_id': tag.group_id,'custom_prompt': tag.custom_prompt,+ 'title_prompt': tag.title_prompt,'default_language': tag.default_language,'default_min_speakers': tag.default_min_speakers,'default_max_speakers': tag.default_max_speakers,@@ -1587,6 +1593,8 @@ def update_tag(tag_id):tag.color = data['color']if 'custom_prompt' in data:tag.custom_prompt = data['custom_prompt']+ if 'title_prompt' in data:+ tag.title_prompt = data['title_prompt'] or Noneif 'default_language' in data:tag.default_language = data['default_language']if 'default_min_speakers' in data:@@ -1603,6 +1611,7 @@ def update_tag(tag_id):'name': tag.name,'color': tag.color,'custom_prompt': tag.custom_prompt,+ 'title_prompt': tag.title_prompt,'default_language': tag.default_language,'default_min_speakers': tag.default_min_speakers,'default_max_speakers': tag.default_max_speakers,diff --git a/src/api/auth.py b/src/api/auth.pyindex 5b37f624..6fb52e6f 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -672,6 +672,10 @@ def account():# Handle custom prompt updatessummary_prompt_text = request.form.get('summary_prompt')current_user.summary_prompt = summary_prompt_text if summary_prompt_text else None+ # Gated on its own field so a form without it cannot clear it (#400).+ if 'title_prompt' in request.form:+ title_prompt_text = (request.form.get('title_prompt') or '').strip()+ current_user.title_prompt = title_prompt_text or None# Handle event extraction settingcurrent_user.extract_events = 'extract_events' in request.form# Inquire content availability (agentic inquire). Gated on the@@ -744,6 +748,10 @@ def account():from src.config.prompts import DEFAULT_SUMMARY_PROMPTdefault_summary_prompt_text = DEFAULT_SUMMARY_PROMPT+ # The title instructions a user gets when they leave their own blank.+ from src.tasks.processing import _user_title_instructions+ default_title_prompt_text = _user_title_instructions(None)[0]+asr_diarize_locked = 'ASR_DIARIZE' in os.environASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'false').lower() == 'true'USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'@@ -825,6 +833,7 @@ def account():return render_template('account.html',title='Account',default_summary_prompt_text=default_summary_prompt_text,+ default_title_prompt_text=default_title_prompt_text,use_asr_endpoint=USE_ASR_ENDPOINT,connector_supports_diarization=connector_supports_diarization,connector_supports_hotwords=connector_supports_hotwords,diff --git a/src/api/folders.py b/src/api/folders.pyindex 1298cbb5..78e75189 100644--- a/src/api/folders.py+++ b/src/api/folders.py@@ -147,6 +147,7 @@ def create_folder():group_id=group_id,color=data.get('color', '#10B981'),custom_prompt=data.get('custom_prompt'),+ title_prompt=data.get('title_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),default_max_speakers=data.get('default_max_speakers'),@@ -234,6 +235,8 @@ def update_folder(folder_id):folder.color = data['color']if 'custom_prompt' in data:folder.custom_prompt = data['custom_prompt']+ if 'title_prompt' in data:+ folder.title_prompt = data['title_prompt'] or Noneif 'default_language' in data:folder.default_language = data['default_language']if 'default_min_speakers' in data:@@ -391,6 +394,7 @@ def create_group_folder(group_id):group_id=group_id,color=data.get('color', '#10B981'),custom_prompt=data.get('custom_prompt'),+ title_prompt=data.get('title_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),default_max_speakers=data.get('default_max_speakers'),diff --git a/src/api/tags.py b/src/api/tags.pyindex ae1a5eff..56d56264 100644--- a/src/api/tags.py+++ b/src/api/tags.py@@ -247,6 +247,7 @@ def create_tag():group_id=group_id,color=color_val or _DEFAULT_TAG_COLOR,custom_prompt=data.get('custom_prompt'),+ title_prompt=data.get('title_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),default_max_speakers=data.get('default_max_speakers'),@@ -347,6 +348,8 @@ def update_tag(tag_id):tag.color = color_val or _DEFAULT_TAG_COLORif 'custom_prompt' in data:tag.custom_prompt = data['custom_prompt']+ if 'title_prompt' in data:+ tag.title_prompt = data['title_prompt'] or Noneif 'default_language' in data:tag.default_language = data['default_language']if 'default_min_speakers' in data:@@ -538,6 +541,7 @@ def create_group_tag(group_id):group_id=group_id,color=color_val or _DEFAULT_TAG_COLOR,custom_prompt=data.get('custom_prompt'),+ title_prompt=data.get('title_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),default_max_speakers=data.get('default_max_speakers'),diff --git a/src/config/prompts.py b/src/config/prompts.pyindex 1bba31ff..cd4d3ef2 100644--- a/src/config/prompts.py+++ b/src/config/prompts.py@@ -42,3 +42,13 @@ Example Format:# (see PREFIX_CACHE_OPTIMIZED_PROMPTS): the transcript is the stable prefix, this# guidance is the editable suffix.DEFAULT_CONTEXTUAL_SPEAKER_PROMPT = """Work out which of the known speaker profiles each speaker label most likely corresponds to, using clues in the conversation such as the names people are addressed by, self-introductions, and references to roles or relationships. Only assign a known profile when the conversation clearly supports it; if you are not confident about a speaker, leave that speaker unassigned with an empty string. Never invent a name that is not in the known profiles list."""+++# Instructions for AI-generated recording titles (#400), and the fallback when+# no tag / folder / user / admin title prompt is set. Only the instructions are+# editable: the transcript, the output-language directive and the rule to reply+# with the title text alone are added in code, after the transcript, so an edit+# here never disturbs prefix caching.+DEFAULT_TITLE_PROMPT = """- Maximum 8 words+- No phrases like "Discussion about" or "Meeting on"+- Just the main topic"""diff --git a/src/init_db.py b/src/init_db.pyindex d9221b72..f5e796ff 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -440,6 +440,11 @@ def _run_migrations(app, engine):if add_column_if_not_exists(engine, 'folder', 'default_initial_prompt', 'TEXT'):app.logger.info("Added default_initial_prompt column to folder table")+ # Configurable AI title instructions at every level (#400)+ for table in ('user', 'tag', 'folder'):+ if add_column_if_not_exists(engine, table, 'title_prompt', 'TEXT'):+ app.logger.info(f"Added title_prompt column to {table} table")+with _migration_section(app, failures, "token indexes, export templates and sharing columns"):# Create indexes for token lookups (for faster token verification)try:@@ -819,6 +824,16 @@ def _run_migrations(app, engine):)app.logger.info("Initialized admin_default_summary_prompt setting")+ if not SystemSetting.query.filter_by(key='admin_default_title_prompt').first():+ from src.config.prompts import DEFAULT_TITLE_PROMPT+ SystemSetting.set_setting(+ key='admin_default_title_prompt',+ value=DEFAULT_TITLE_PROMPT,+ description='Default instructions for AI-generated recording titles, used when no tag, folder or user title prompt is set.',+ setting_type='string'+ )+ app.logger.info("Initialized admin_default_title_prompt setting")+if not SystemSetting.query.filter_by(key='admin_default_contextual_speaker_prompt').first():from src.config.prompts import DEFAULT_CONTEXTUAL_SPEAKER_PROMPTSystemSetting.set_setting(diff --git a/src/models/organization.py b/src/models/organization.pyindex 25d6a6a9..0fd00bca 100644--- a/src/models/organization.py+++ b/src/models/organization.py@@ -91,6 +91,7 @@ class Folder(db.Model):# Custom settings for this foldercustom_prompt = db.Column(db.Text, nullable=True) # Custom summarization prompt+ title_prompt = db.Column(db.Text, nullable=True) # Instructions for AI titles (#400)default_language = db.Column(db.String(10), nullable=True) # Default transcription languagedefault_min_speakers = db.Column(db.Integer, nullable=True) # Default min speakers for ASRdefault_max_speakers = db.Column(db.Integer, nullable=True) # Default max speakers for ASR@@ -143,6 +144,7 @@ class Folder(db.Model):'is_group_folder': self.is_group_folder,'group_name': self.group.name if self.group else None,'custom_prompt': self.custom_prompt,+ 'title_prompt': self.title_prompt,'default_language': self.default_language,'default_min_speakers': self.default_min_speakers,'default_max_speakers': self.default_max_speakers,@@ -173,6 +175,7 @@ class Tag(db.Model):# Custom settings for this tagcustom_prompt = db.Column(db.Text, nullable=True) # Custom summarization prompt+ title_prompt = db.Column(db.Text, nullable=True) # Instructions for AI titles (#400)default_language = db.Column(db.String(10), nullable=True) # Default transcription languagedefault_min_speakers = db.Column(db.Integer, nullable=True) # Default min speakers for ASRdefault_max_speakers = db.Column(db.Integer, nullable=True) # Default max speakers for ASR@@ -229,6 +232,7 @@ class Tag(db.Model):'is_group_tag': self.is_group_tag,'group_name': self.group.name if self.group else None,'custom_prompt': self.custom_prompt,+ 'title_prompt': self.title_prompt,'default_language': self.default_language,'default_min_speakers': self.default_min_speakers,'default_max_speakers': self.default_max_speakers,diff --git a/src/models/user.py b/src/models/user.pyindex 639041c7..3c2a5d1e 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -27,6 +27,7 @@ class User(db.Model, UserMixin):output_language = db.Column(db.String(50), nullable=True) # For full language names like "Spanish"ui_language = db.Column(db.String(10), nullable=True, default='en') # For UI language preference (en, es, fr, zh)summary_prompt = db.Column(db.Text, nullable=True)+ title_prompt = db.Column(db.Text, nullable=True) # Instructions for AI titles (#400)extract_events = db.Column(db.Boolean, default=False) # Enable event extraction from transcripts# Inquire content availability (agentic inquire). Transcripts are always# available; summaries/notes are optional. NULL = use the admin envdiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 31b3656d..48b0b3f2 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -410,6 +410,47 @@ def generate_title_task(app_context, recording_id, will_auto_summarize=False):current_app.logger.info(f"Title generation complete, leaving status unchanged (auto-summarization will follow) for recording {recording_id}")+def _user_title_instructions(user):+ """The user, admin and shipped levels of the title precedence."""+ from src.config.prompts import DEFAULT_TITLE_PROMPT++ if user and user.title_prompt and user.title_prompt.strip():+ return user.title_prompt.strip(), 'user'+ admin_prompt = SystemSetting.get_setting('admin_default_title_prompt', None)+ if admin_prompt and str(admin_prompt).strip():+ return str(admin_prompt).strip(), 'admin'+ return DEFAULT_TITLE_PROMPT, 'default'+++def resolve_title_instructions(recording, viewer=None):+ """Instructions for a recording's AI title, and which level supplied them.++ Same precedence as the summary prompt (#400): tag > folder > user > admin+ default > shipped default. Every tag visible to the viewer that carries a+ title prompt contributes, in the order the tags were added, joined the way+ tag summary prompts are. The viewer defaults to the owner, who is the user+ titles are generated for.++ Returns (instructions, source); source is 'tag', 'folder', 'user',+ 'admin' or 'default'.+ """+ viewer = viewer or recording.owner+ if viewer:+ tag_prompts = [+ tag.title_prompt.strip()+ for tag in (recording.get_visible_tags(viewer) or [])+ if tag.title_prompt and tag.title_prompt.strip()+ ]+ if tag_prompts:+ return "\n\n".join(tag_prompts), 'tag'++ folder = recording.folder+ if folder and folder.title_prompt and folder.title_prompt.strip():+ return folder.title_prompt.strip(), 'folder'++ return _user_title_instructions(recording.owner)++def _generate_ai_title(recording):"""Generate an AI title for a recording using LLM.@@ -451,6 +492,9 @@ def _generate_ai_title(recording):language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""+ title_instructions, title_source = resolve_title_instructions(recording)+ current_app.logger.info(f"Using {title_source} title instructions for recording {recording.id}")+if PREFIX_CACHE_OPTIMIZED_PROMPTS:# Shared-prefix layout: identical system message + identical user prefix# (including the transcript) between this call and the summary call, so@@ -460,11 +504,9 @@ def _generate_ai_title(recording):system_message_content = _SHARED_LLM_SYSTEM_MSGprompt_text = (_shared_user_prefix(transcript_text)- + "Task: produce ONE short title for the conversation above.\n"+ + "Task: produce ONE title for the conversation above.\n"+ "Requirements:\n"- + "- Maximum 8 words\n"- + "- No phrases like \"Discussion about\" or \"Meeting on\"\n"- + "- Just the main topic\n"+ + title_instructions + "\n"+ "- Output ONLY the title text, nothing else (no quotes, no prefix)\n"+ (f"- Respond in {user_output_language}\n" if user_output_language else "")+ "\nTitle:"@@ -475,9 +517,8 @@ def _generate_ai_title(recording):{transcript_text}Requirements:-- Maximum 8 words-- No phrases like "Discussion about" or "Meeting on"-- Just the main topic+{title_instructions}+- Output ONLY the title text, nothing else{language_directive}@@ -513,7 +554,7 @@ Title:"""# Look for the last line that might be the titlefor line in reversed(lines):line = line.strip()- if line and not line.startswith('I') and len(line.split()) <= 8:+ if line and not line.startswith('I') and len(line.split()) <= 20:raw_response = linebreak@@ -2669,15 +2710,17 @@ def _generate_incognito_title(transcription_text, user=None):# Get user language preferenceuser_output_language = user.output_language if user else Nonelanguage_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""+ # Incognito recordings have no tags or folder, so only the user,+ # admin and shipped levels apply.+ title_instructions, _ = _user_title_instructions(user)prompt_text = f"""Create a short title for this conversation:{limited_text}Requirements:-- Maximum 8 words-- No phrases like "Discussion about" or "Meeting on"-- Just the main topic+{title_instructions}+- Output ONLY the title text, nothing else{language_directive}diff --git a/tests/test_title_prompt.py b/tests/test_title_prompt.pynew file mode 100644index 00000000..c5b89413--- /dev/null+++ b/tests/test_title_prompt.py@@ -0,0 +1,248 @@+"""Configurable AI title instructions (#400).++The title prompt follows the summary prompt's precedence: tag > folder >+user > admin default > shipped default. It can be set on tags and folders+(personal and group), in the user's Prompt Options, and by the admin, and the+resolved text is what reaches the model in both prompt layouts.++SHARED-DB: every assertion is scoped to the rows the test created. The admin+setting is global, so tests that change it restore it.+"""++import json+import os+import sys+import uuid+from contextlib import contextmanager+from unittest.mock import patch, MagicMock++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import src.tasks.processing as processing+from src.app import app, db+from src.config.prompts import DEFAULT_TITLE_PROMPT+from src.models import User, Recording, Tag, Folder, RecordingTag, SystemSetting++app.config["WTF_CSRF_ENABLED"] = False++TRANSCRIPT = json.dumps([+ {"speaker": "SPEAKER_00", "sentence": "Christine Lagarde opened the press conference on the deposit rate.", "start_time": 0, "end_time": 5},+ {"speaker": "SPEAKER_01", "sentence": "Questions followed on the inflation outlook.", "start_time": 5, "end_time": 9},+])+++def ctx():+ with app.app_context():+ yield+++@contextmanager+def admin_title_prompt(value):+ previous = SystemSetting.get_setting('admin_default_title_prompt', None)+ SystemSetting.set_setting('admin_default_title_prompt', value, setting_type='string')+ try:+ yield+ finally:+ SystemSetting.set_setting('admin_default_title_prompt', previous if previous is not None else DEFAULT_TITLE_PROMPT,+ setting_type='string')+++def _user(**kwargs):+ suffix = uuid.uuid4().hex[:8]+ user = User(username=f"tp_{suffix}", email=f"tp_{suffix}@local.test", password="x", **kwargs)+ db.session.add(user)+ db.session.commit()+ return user+++def _recording(user, folder=None):+ rec = Recording(user_id=user.id, title="r", status="COMPLETED", audio_path="local://recordings/x.mp3",+ original_filename="x.mp3", transcription=TRANSCRIPT, folder_id=folder.id if folder else None)+ db.session.add(rec)+ db.session.commit()+ return rec+++def _tag(user, title_prompt=None, order=0, rec=None):+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id, title_prompt=title_prompt)+ db.session.add(tag)+ db.session.commit()+ if rec is not None:+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=tag.id, order=order))+ db.session.commit()+ return tag+++def _folder(user, title_prompt=None):+ folder = Folder(name=f"f_{uuid.uuid4().hex[:6]}", user_id=user.id, title_prompt=title_prompt)+ db.session.add(folder)+ db.session.commit()+ return folder+++def _client(user):+ c = app.test_client()+ with c.session_transaction() as sess:+ sess["_user_id"] = str(user.id)+ sess["_fresh"] = True+ return c+++# ----------------------------------------------------------------- precedence++def test_shipped_default_when_nothing_is_set(ctx):+ rec = _recording(_user())+ with admin_title_prompt(''):+ assert processing.resolve_title_instructions(rec) == (DEFAULT_TITLE_PROMPT, 'default')+++def test_each_level_overrides_the_ones_below(ctx):+ user = _user()+ folder = _folder(user)+ rec = _recording(user, folder)+ with admin_title_prompt('ADMIN'):+ assert processing.resolve_title_instructions(rec) == ('ADMIN', 'admin')++ user.title_prompt = 'USER'+ db.session.commit()+ assert processing.resolve_title_instructions(rec) == ('USER', 'user')++ folder.title_prompt = 'FOLDER'+ db.session.commit()+ assert processing.resolve_title_instructions(rec) == ('FOLDER', 'folder')++ _tag(user, 'TAG', rec=rec)+ assert processing.resolve_title_instructions(rec) == ('TAG', 'tag')+++def test_blank_levels_fall_through(ctx):+ user = _user(title_prompt=' ')+ folder = _folder(user, title_prompt='')+ rec = _recording(user, folder)+ _tag(user, ' ', rec=rec)+ with admin_title_prompt('ADMIN'):+ assert processing.resolve_title_instructions(rec) == ('ADMIN', 'admin')+++def test_several_tag_prompts_are_joined_in_tag_order(ctx):+ user = _user()+ rec = _recording(user)+ _tag(user, 'SECOND', order=1, rec=rec)+ _tag(user, 'FIRST', order=0, rec=rec)+ _tag(user, None, order=2, rec=rec)+ text, source = processing.resolve_title_instructions(rec)+ assert source == 'tag'+ assert text == 'FIRST\n\nSECOND'+++def test_another_users_personal_tag_is_ignored(ctx):+ owner, other = _user(), _user()+ rec = _recording(owner)+ _tag(other, 'NOT YOURS', rec=rec)+ with admin_title_prompt('ADMIN'):+ assert processing.resolve_title_instructions(rec)[1] == 'admin'+++# ------------------------------------------------------------ prompt content++def _title_messages(rec, prefix_mode):+ calls = []++ def fake(messages=None, **kwargs):+ calls.append(messages)+ stub = MagicMock()+ stub.choices = [MagicMock()]+ stub.choices[0].message.content = "Lagarde ECB press conference on deposit rate"+ stub.choices[0].message.reasoning = None+ return stub++ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", prefix_mode), \+ patch("src.tasks.processing.call_llm_completion", side_effect=fake):+ title = processing._generate_ai_title(rec)+ return title, {m["role"]: m["content"] for m in calls[-1]}++[email protected]("prefix_mode", [False, True])+def test_resolved_instructions_reach_the_model(ctx, prefix_mode):+ user = _user()+ rec = _recording(user)+ _tag(user, '- Name the institution and the main speaker', rec=rec)+ title, messages = _title_messages(rec, prefix_mode)+ assert title == "Lagarde ECB press conference on deposit rate"+ user_msg = messages["user"]+ assert '- Name the institution and the main speaker' in user_msg+ assert 'Maximum 8 words' not in user_msg+ assert 'Output ONLY the title text' in user_msg+ # The instructions come after the transcript, so the prefix-cache layout+ # keeps the transcript as the shared prefix.+ assert user_msg.index('Christine Lagarde') < user_msg.index('Name the institution')+++def test_default_instructions_keep_the_previous_prompt(ctx):+ rec = _recording(_user())+ with admin_title_prompt(''):+ _, messages = _title_messages(rec, False)+ assert '- Maximum 8 words' in messages["user"]+++def test_incognito_titles_use_the_user_level(ctx):+ user = _user(title_prompt='- Start with the date')+ calls = []++ def fake_create(**kwargs):+ calls.append(kwargs["messages"])+ stub = MagicMock()+ stub.choices = [MagicMock()]+ stub.choices[0].message.content = "A title"+ return stub++ fake_client = MagicMock()+ fake_client.chat.completions.create.side_effect = fake_create+ with patch("src.tasks.processing.client", new=fake_client):+ processing._generate_incognito_title(TRANSCRIPT, user=user)+ assert '- Start with the date' in calls[-1][1]["content"]+++# ------------------------------------------------------------- where it is set++def test_tag_and_folder_routes_store_the_title_prompt(ctx):+ user = _user()+ c = _client(user)+ r = c.post('/api/tags', json={'name': f'tag_{uuid.uuid4().hex[:6]}', 'title_prompt': 'TAG TITLE'})+ assert r.status_code in (200, 201), r.get_data(as_text=True)+ tag_id = (r.get_json().get('tag') or r.get_json())['id']+ assert db.session.get(Tag, tag_id).title_prompt == 'TAG TITLE'+ c.put(f'/api/tags/{tag_id}', json={'title_prompt': ''})+ db.session.expire_all()+ assert db.session.get(Tag, tag_id).title_prompt is None++ previous = SystemSetting.get_setting('enable_folders', False)+ SystemSetting.set_setting('enable_folders', 'true', setting_type='boolean')+ try:+ r = c.post('/api/folders', json={'name': f'folder_{uuid.uuid4().hex[:6]}', 'title_prompt': 'FOLDER TITLE'})+ finally:+ SystemSetting.set_setting('enable_folders', 'true' if previous else 'false', setting_type='boolean')+ assert r.status_code in (200, 201), r.get_data(as_text=True)+ body = r.get_json()+ folder_id = (body.get('folder') or body)['id']+ assert db.session.get(Folder, folder_id).title_prompt == 'FOLDER TITLE'+ assert db.session.get(Folder, folder_id).to_dict()['title_prompt'] == 'FOLDER TITLE'+++def test_account_prompt_form_saves_and_keeps_the_title_prompt(ctx):+ user = _user()+ c = _client(user)+ c.post('/account', data={'summary_prompt': '', 'title_prompt': ' - Speaker and topic '})+ db.session.expire_all()+ assert db.session.get(User, user.id).title_prompt == '- Speaker and topic'+ # A submission of the same form without the field leaves it alone.+ c.post('/account', data={'summary_prompt': ''})+ db.session.expire_all()+ assert db.session.get(User, user.id).title_prompt == '- Speaker and topic'+++def test_admin_default_is_seeded(ctx):+ assert SystemSetting.query.filter_by(key='admin_default_title_prompt').first() is not None