Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Make transcription templates bundle initial prompt + hotwords and consolidate the upload modal into a Transcription Options group (#309)
Murtaza Nasird8408c705fd0
diff --git a/src/api/initial_prompt_templates.py b/src/api/initial_prompt_templates.pyindex 1ac8b456..561698fc 100644--- a/src/api/initial_prompt_templates.py+++ b/src/api/initial_prompt_templates.py@@ -29,10 +29,13 @@ def get_initial_prompt_templates():@initial_prompt_templates_bp.route('/api/initial-prompt-templates', methods=['POST'])@login_requireddef create_initial_prompt_template():- """Create a new initial-prompt template."""+ """Create a new transcription template (initial prompt and/or hotwords)."""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+ prompt = (data.get('template') or '') if data else ''+ hotwords = (data.get('hotwords') or '') if data else ''+ # A template needs a name and at least one of prompt / hotwords.+ if not data or not data.get('name') or not (prompt.strip() or hotwords.strip()):+ return jsonify({'error': 'Name and a prompt or hotwords are required'}), 400# If this is set as default, unset other defaultsif data.get('is_default'):@@ -44,7 +47,8 @@ def create_initial_prompt_template():template = InitialPromptTemplate(user_id=current_user.id,name=data['name'],- template=data['template'],+ template=prompt,+ hotwords=hotwords or None,description=data.get('description'),is_default=data.get('is_default', False))@@ -80,6 +84,8 @@ def update_initial_prompt_template(template_id):template.name = data.get('name', template.name)template.template = data.get('template', template.template)+ if 'hotwords' in data:+ template.hotwords = data.get('hotwords') or Nonetemplate.description = data.get('description', template.description)template.is_default = data.get('is_default', template.is_default)template.updated_at = datetime.utcnow()@@ -118,24 +124,29 @@ def create_default_initial_prompt_templates():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):+ for idx, (name, text, hotwords, description) in enumerate(starters):templates.append(InitialPromptTemplate(user_id=current_user.id,name=name,template=text,+ hotwords=hotwords or None,description=description,is_default=(idx == 0),))diff --git a/src/init_db.py b/src/init_db.pyindex 931ffd06..ce4e5260 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -229,6 +229,10 @@ def initialize_database(app):if add_column_if_not_exists(engine, 'recording', 'resolved_initial_prompt', 'TEXT'):app.logger.info("Added resolved_initial_prompt column to recording table")+ # Transcription templates now bundle hotwords alongside the prompt (#309)+ if add_column_if_not_exists(engine, 'initial_prompt_template', 'hotwords', 'TEXT'):+ app.logger.info("Added hotwords column to initial_prompt_template table")+# Add speaker voice profile embedding fieldsif add_column_if_not_exists(engine, 'speaker', 'average_embedding', 'BLOB'):app.logger.info("Added average_embedding column to speaker table")diff --git a/src/models/initial_prompt_template.py b/src/models/initial_prompt_template.pyindex d5035a22..034442ef 100644--- a/src/models/initial_prompt_template.py+++ b/src/models/initial_prompt_template.py@@ -1,10 +1,10 @@"""-InitialPromptTemplate model for user-defined transcription initial prompts.+InitialPromptTemplate model — user-defined, reusable transcription templates.-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.+A template bundles a plain-text ASR "initial prompt" (the context line sent to+the transcription engine, stored in `template`) and optional comma-separated+`hotwords`. Picked at upload time or used to fill tag/folder/account defaults.+Plain text only — no {{variable}} substitution (distinct from summary prompts)."""from datetime import datetime@@ -12,12 +12,13 @@ from src.database import dbclass InitialPromptTemplate(db.Model):- """Stores user-defined, reusable transcription initial-prompt texts."""+ """Stores user-defined, reusable transcription templates (prompt + hotwords)."""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)+ template = db.Column(db.Text, nullable=False) # the initial prompt ('' if hotwords-only)+ hotwords = db.Column(db.Text, nullable=True) # comma-separated hotwords (optional)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)@@ -32,6 +33,7 @@ class InitialPromptTemplate(db.Model):'id': self.id,'name': self.name,'template': self.template,+ 'hotwords': self.hotwords or '','description': self.description,'is_default': self.is_default,'created_at': self.created_at.isoformat() if self.created_at else None,diff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 5601458d..4cc3799a 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -528,7 +528,10 @@ document.addEventListener('DOMContentLoaded', async () => {const initialPromptTemplates = ref([]);const applyInitialPromptTemplate = (id) => {const tpl = initialPromptTemplates.value.find(t => String(t.id) === String(id));- if (tpl) uploadInitialPrompt.value = tpl.template;+ if (!tpl) return;+ // A transcription template applies BOTH its prompt and hotwords.+ uploadInitialPrompt.value = tpl.template || '';+ uploadHotwords.value = tpl.hotwords || '';};// Detail-view popover showing which hotwords/initial-prompt a// recording actually used (#309).diff --git a/static/locales/de.json b/static/locales/de.jsonindex f1496c0a..7b820594 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1590,23 +1590,26 @@"viewGuide": "Vorlagen-Leitfaden Anzeigen"},"initialPromptTemplates": {- "tabTitle": "Transkriptions-Prompts",- "title": "Transkriptions-Prompts",- "description": "Speichern Sie wiederverwendbare Initial-Prompts, die die Transkription steuern. Wählen Sie einen beim Hochladen aus oder verwenden Sie ihn als Standard für Tags, Ordner oder Ihr Konto.",- "createNew": "Prompt erstellen",- "availableTemplates": "Gespeicherte Prompts",- "createDefaults": "Start-Prompts erstellen",+ "tabTitle": "Transkriptionsvorlagen",+ "title": "Transkriptionsvorlagen",+ "description": "Speichern Sie wiederverwendbare Vorlagen aus Initial-Prompt und Hotwords, die die Transkription steuern. Wählen Sie eine beim Hochladen aus oder verwenden Sie sie als Standard für Tags, Ordner oder Ihr Konto.",+ "createNew": "Vorlage erstellen",+ "availableTemplates": "Gespeicherte Vorlagen",+ "createDefaults": "Start-Vorlagen erstellen","templateName": "Name","descriptionLabel": "Beschreibung",- "template": "Prompt",+ "template": "Initial-Prompt","help": "Ein kurzer, einfacher Satz, der die Aufnahme beschreibt, z. B. „Dies ist eine Geschäftsbesprechung über die Quartalsumsätze.“ Er wird an die Transkriptions-Engine gesendet, um die Erkennung zu steuern.",- "setDefault": "Als Standard-Prompt festlegen",+ "setDefault": "Als Standardvorlage festlegen","save": "Speichern","cancel": "Abbrechen","delete": "Löschen",- "selectOrCreate": "Wählen Sie einen Prompt zum Bearbeiten oder erstellen Sie einen neuen",+ "selectOrCreate": "Wählen Sie eine Vorlage zum Bearbeiten oder erstellen Sie eine neue","default": "Standard",- "pickPlaceholder": "Gespeicherten Prompt einfügen…"+ "pickPlaceholder": "Gespeicherte Vorlage einfügen…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Optionale, durch Komma getrennte Wörter zur Verbesserung der Erkennung domänenspezifischer Begriffe.",+ "savedTemplate": "Gespeicherte Vorlage"},"detail": {"hints": "Hinweise",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "Video verworfen","keepAudioOnlyLargerAllowed": "Größere Uploads erlaubt","largeVideoNotice": "Großes Videodatei. Upload wird fortgesetzt; Transkription dauert ggf. länger und nutzt das Chunking auf dem Server.",- "options": "Optionen"+ "options": "Optionen",+ "transcriptionOptions": "Transkriptionsoptionen"},"uploadProgress": {"title": "Upload-Fortschritt"diff --git a/static/locales/en.json b/static/locales/en.jsonindex 056a9788..e8fa3260 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1599,23 +1599,26 @@"viewGuide": "View Template Guide"},"initialPromptTemplates": {- "tabTitle": "Transcription Prompts",- "title": "Transcription Prompts",- "description": "Save reusable initial prompts that steer the transcription engine. Pick one when uploading, or use it to fill a tag, folder, or account default.",- "createNew": "Create Prompt",- "availableTemplates": "Saved Prompts",- "createDefaults": "Create Starter Prompts",+ "tabTitle": "Transcription Templates",+ "title": "Transcription Templates",+ "description": "Save reusable templates that bundle an initial prompt and hotwords to steer the transcription engine. Pick one when uploading, or use it to fill a tag, folder, or account default.",+ "createNew": "Create Template",+ "availableTemplates": "Saved Templates",+ "createDefaults": "Create Starter Templates","templateName": "Name","descriptionLabel": "Description",- "template": "Prompt",+ "template": "Initial prompt","help": "A short, plain sentence that describes the recording, e.g. \"This is a business meeting about quarterly sales.\" It is sent to the transcription engine to steer recognition.",- "setDefault": "Set as default prompt",+ "setDefault": "Set as default template","save": "Save","cancel": "Cancel","delete": "Delete",- "selectOrCreate": "Select a prompt to edit or create a new one",+ "selectOrCreate": "Select a template to edit or create a new one","default": "Default",- "pickPlaceholder": "Insert a saved prompt…"+ "pickPlaceholder": "Insert a saved template…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Optional comma-separated words to bias recognition of domain-specific terms.",+ "savedTemplate": "Saved template"},"detail": {"hints": "Hints",@@ -1682,7 +1685,8 @@"keepAudioOnlySubtitleOn": "Video dropped","keepAudioOnlyLargerAllowed": "Larger uploads allowed","largeVideoNotice": "Large video file. Upload will proceed; transcription may take longer and uses chunking on the server.",- "options": "Options"+ "options": "Options",+ "transcriptionOptions": "Transcription Options"},"uploadProgress": {"title": "Upload Progress"diff --git a/static/locales/es.json b/static/locales/es.jsonindex 6f79852c..1dea533e 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1590,23 +1590,26 @@"viewGuide": "Ver Guía de Plantillas"},"initialPromptTemplates": {- "tabTitle": "Prompts de transcripción",- "title": "Prompts de transcripción",- "description": "Guarda prompts iniciales reutilizables que orientan el motor de transcripción. Elige uno al subir un archivo o úsalo para rellenar un valor predeterminado de etiqueta, carpeta o cuenta.",- "createNew": "Crear prompt",- "availableTemplates": "Prompts guardados",- "createDefaults": "Crear prompts iniciales",+ "tabTitle": "Plantillas de transcripción",+ "title": "Plantillas de transcripción",+ "description": "Guarda plantillas reutilizables que combinan un prompt inicial y hotwords para orientar el motor de transcripción. Elige una al subir un archivo o úsala como predeterminada de una etiqueta, carpeta o cuenta.",+ "createNew": "Crear plantilla",+ "availableTemplates": "Plantillas guardadas",+ "createDefaults": "Crear plantillas iniciales","templateName": "Nombre","descriptionLabel": "Descripción",- "template": "Prompt",+ "template": "Prompt inicial","help": "Una frase breve y sencilla que describa la grabación, p. ej. «Esta es una reunión de negocios sobre las ventas trimestrales.» Se envía al motor de transcripción para orientar el reconocimiento.",- "setDefault": "Establecer como prompt predeterminado",+ "setDefault": "Establecer como plantilla predeterminada","save": "Guardar","cancel": "Cancelar","delete": "Eliminar",- "selectOrCreate": "Selecciona un prompt para editar o crea uno nuevo",+ "selectOrCreate": "Selecciona una plantilla para editar o crea una nueva","default": "Predeterminado",- "pickPlaceholder": "Insertar un prompt guardado…"+ "pickPlaceholder": "Insertar una plantilla guardada…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Palabras opcionales separadas por comas para mejorar el reconocimiento de términos específicos.",+ "savedTemplate": "Plantilla guardada"},"detail": {"hints": "Indicaciones",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "Vídeo descartado","keepAudioOnlyLargerAllowed": "Se permiten subidas más grandes","largeVideoNotice": "Archivo de vídeo grande. La subida continuará; la transcripción puede tardar más y usa el troceado en el servidor.",- "options": "Opciones"+ "options": "Opciones",+ "transcriptionOptions": "Opciones de transcripción"},"uploadProgress": {"title": "Progreso de Carga"diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex f6cd3f7b..15388e51 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1590,23 +1590,26 @@"viewGuide": "Voir le Guide des Modèles"},"initialPromptTemplates": {- "tabTitle": "Prompts de transcription",- "title": "Prompts de transcription",- "description": "Enregistrez des prompts initiaux réutilisables qui orientent le moteur de transcription. Choisissez-en un lors de l'envoi, ou utilisez-le pour remplir une valeur par défaut d'étiquette, de dossier ou de compte.",- "createNew": "Créer un prompt",- "availableTemplates": "Prompts enregistrés",- "createDefaults": "Créer des prompts de départ",+ "tabTitle": "Modèles de transcription",+ "title": "Modèles de transcription",+ "description": "Enregistrez des modèles réutilisables combinant un prompt initial et des hotwords pour orienter le moteur de transcription. Choisissez-en un lors de l'envoi, ou utilisez-le comme valeur par défaut d'étiquette, de dossier ou de compte.",+ "createNew": "Créer un modèle",+ "availableTemplates": "Modèles enregistrés",+ "createDefaults": "Créer des modèles de départ","templateName": "Nom","descriptionLabel": "Description",- "template": "Prompt",+ "template": "Prompt initial","help": "Une phrase courte et simple décrivant l'enregistrement, par ex. « Ceci est une réunion d'affaires sur les ventes trimestrielles. » Elle est envoyée au moteur de transcription pour orienter la reconnaissance.",- "setDefault": "Définir comme prompt par défaut",+ "setDefault": "Définir comme modèle par défaut","save": "Enregistrer","cancel": "Annuler","delete": "Supprimer",- "selectOrCreate": "Sélectionnez un prompt à modifier ou créez-en un nouveau",+ "selectOrCreate": "Sélectionnez un modèle à modifier ou créez-en un nouveau","default": "Par défaut",- "pickPlaceholder": "Insérer un prompt enregistré…"+ "pickPlaceholder": "Insérer un modèle enregistré…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Mots optionnels séparés par des virgules pour améliorer la reconnaissance de termes spécifiques.",+ "savedTemplate": "Modèle enregistré"},"detail": {"hints": "Indices",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "Vidéo supprimée","keepAudioOnlyLargerAllowed": "Envois plus volumineux autorisés","largeVideoNotice": "Fichier vidéo volumineux. L’envoi va se poursuivre ; la transcription peut être plus longue et utilise le découpage côté serveur.",- "options": "Options"+ "options": "Options",+ "transcriptionOptions": "Options de transcription"},"uploadProgress": {"title": "Progression du Téléchargement"diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 5ac3ef38..269da649 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1590,23 +1590,26 @@"viewGuide": "Ver Guia de Modelo"},"initialPromptTemplates": {- "tabTitle": "Prompts de transcrição",- "title": "Prompts de transcrição",- "description": "Salve prompts iniciais reutilizáveis que orientam o mecanismo de transcrição. Escolha um ao enviar um arquivo ou use-o para preencher um padrão de tag, pasta ou conta.",- "createNew": "Criar prompt",- "availableTemplates": "Prompts salvos",- "createDefaults": "Criar prompts iniciais",+ "tabTitle": "Modelos de transcrição",+ "title": "Modelos de transcrição",+ "description": "Salve modelos reutilizáveis que combinam um prompt inicial e hotwords para orientar o mecanismo de transcrição. Escolha um ao enviar um arquivo ou use-o como padrão de tag, pasta ou conta.",+ "createNew": "Criar modelo",+ "availableTemplates": "Modelos salvos",+ "createDefaults": "Criar modelos iniciais","templateName": "Nome","descriptionLabel": "Descrição",- "template": "Prompt",+ "template": "Prompt inicial","help": "Uma frase curta e simples que descreve a gravação, por ex. \"Esta é uma reunião de negócios sobre as vendas trimestrais.\" Ela é enviada ao mecanismo de transcrição para orientar o reconhecimento.",- "setDefault": "Definir como prompt padrão",+ "setDefault": "Definir como modelo padrão","save": "Salvar","cancel": "Cancelar","delete": "Excluir",- "selectOrCreate": "Selecione um prompt para editar ou crie um novo",+ "selectOrCreate": "Selecione um modelo para editar ou crie um novo","default": "Padrão",- "pickPlaceholder": "Inserir um prompt salvo…"+ "pickPlaceholder": "Inserir um modelo salvo…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Palavras opcionais separadas por vírgula para melhorar o reconhecimento de termos específicos.",+ "savedTemplate": "Modelo salvo"},"detail": {"hints": "Dicas",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "Vídeo descartado","keepAudioOnlyLargerAllowed": "Envios maiores permitidos","largeVideoNotice": "Arquivo de vídeo grande. O envio será concluído; a transcrição pode demorar mais e usa o particionamento no servidor.",- "options": "Opções"+ "options": "Opções",+ "transcriptionOptions": "Opções de transcrição"},"uploadProgress": {"title": "Progresso do Envio"diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex d53451e2..48baba6d 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1590,23 +1590,26 @@"viewGuide": "Посмотреть руководство по шаблонам"},"initialPromptTemplates": {- "tabTitle": "Промпты транскрипции",- "title": "Промпты транскрипции",- "description": "Сохраняйте многократно используемые начальные промпты, которые направляют движок транскрипции. Выберите один при загрузке или используйте его как значение по умолчанию для тега, папки или аккаунта.",- "createNew": "Создать промпт",- "availableTemplates": "Сохранённые промпты",- "createDefaults": "Создать стартовые промпты",+ "tabTitle": "Шаблоны транскрипции",+ "title": "Шаблоны транскрипции",+ "description": "Сохраняйте многократно используемые шаблоны, объединяющие начальный промпт и hotwords для управления транскрипцией. Выбирайте при загрузке или используйте как значение по умолчанию для тега, папки или аккаунта.",+ "createNew": "Создать шаблон",+ "availableTemplates": "Сохранённые шаблоны",+ "createDefaults": "Создать стартовые шаблоны","templateName": "Название","descriptionLabel": "Описание",- "template": "Промпт",+ "template": "Начальный промпт","help": "Короткое простое предложение, описывающее запись, например «Это деловая встреча о квартальных продажах.» Оно отправляется в движок транскрипции для уточнения распознавания.",- "setDefault": "Сделать промптом по умолчанию",+ "setDefault": "Сделать шаблоном по умолчанию","save": "Сохранить","cancel": "Отмена","delete": "Удалить",- "selectOrCreate": "Выберите промпт для редактирования или создайте новый",+ "selectOrCreate": "Выберите шаблон для редактирования или создайте новый","default": "По умолчанию",- "pickPlaceholder": "Вставить сохранённый промпт…"+ "pickPlaceholder": "Вставить сохранённый шаблон…",+ "hotwords": "Hotwords",+ "hotwordsHelp": "Необязательные слова через запятую для улучшения распознавания специфичных терминов.",+ "savedTemplate": "Сохранённый шаблон"},"detail": {"hints": "Подсказки",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "Видео отброшено","keepAudioOnlyLargerAllowed": "Допустимы более крупные загрузки","largeVideoNotice": "Большой видеофайл. Загрузка продолжится; транскрибация может занять больше времени и использует разбивку на сервере.",- "options": "Параметры"+ "options": "Параметры",+ "transcriptionOptions": "Параметры транскрипции"},"uploadProgress": {"title": "Прогресс загрузки"diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 904b7172..33c88315 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1590,23 +1590,26 @@"viewGuide": "查看模板指南"},"initialPromptTemplates": {- "tabTitle": "转录提示词",- "title": "转录提示词",- "description": "保存可重复使用的初始提示词,用于引导转录引擎。上传时选择一个,或用它来填充标签、文件夹或账户的默认值。",- "createNew": "创建提示词",- "availableTemplates": "已保存的提示词",- "createDefaults": "创建入门提示词",+ "tabTitle": "转录模板",+ "title": "转录模板",+ "description": "保存可重复使用的模板,将初始提示词和热词组合起来引导转录引擎。上传时选择一个,或将其用作标签、文件夹或账户的默认值。",+ "createNew": "创建模板",+ "availableTemplates": "已保存的模板",+ "createDefaults": "创建入门模板","templateName": "名称","descriptionLabel": "描述",- "template": "提示词",+ "template": "初始提示词","help": "用一句简短、朴素的话描述录音,例如“这是一场关于季度销售的商务会议。”它会发送给转录引擎以引导识别。",- "setDefault": "设为默认提示词",+ "setDefault": "设为默认模板","save": "保存","cancel": "取消","delete": "删除",- "selectOrCreate": "选择一个提示词进行编辑,或创建一个新的",+ "selectOrCreate": "选择一个模板进行编辑,或创建一个新的","default": "默认",- "pickPlaceholder": "插入已保存的提示词…"+ "pickPlaceholder": "插入已保存的模板…",+ "hotwords": "热词",+ "hotwordsHelp": "可选的、以逗号分隔的词语,用于提高特定术语的识别。",+ "savedTemplate": "已保存的模板"},"detail": {"hints": "提示",@@ -1673,7 +1676,8 @@"keepAudioOnlySubtitleOn": "已丢弃视频","keepAudioOnlyLargerAllowed": "允许更大文件","largeVideoNotice": "视频文件较大。上传将继续;转录可能耗时更长,并依赖服务器端的分块处理。",- "options": "选项"+ "options": "选项",+ "transcriptionOptions": "转录选项"},"uploadProgress": {"title": "上传进度"diff --git a/templates/account.html b/templates/account.htmlindex 7e9d7aea..6b698b13 100644--- a/templates/account.html+++ b/templates/account.html@@ -853,7 +853,7 @@<label for="transcription_initial_prompt" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="account.defaultInitialPrompt">Default Initial Prompt</label>- <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="transcription_initial_prompt" style="display:none">+ <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="transcription_initial_prompt" data-target-hotwords="transcription_hotwords" style="display:none"><option value="">Insert a saved prompt…</option></select><textarea name="transcription_initial_prompt" id="transcription_initial_prompt" rows="2"@@ -1678,14 +1678,20 @@</div><div>- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="initialPromptTemplates.template">Prompt</label>- <textarea id="ipTemplateContent" rows="4" 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)] text-sm" required></textarea>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="initialPromptTemplates.template">Initial prompt</label>+ <textarea id="ipTemplateContent" rows="4" 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)] text-sm"></textarea><p class="text-xs text-[var(--text-muted)] mt-2" data-i18n="initialPromptTemplates.help">A short, plain sentence that describes the recording, e.g. "This is a business meeting about quarterly sales." It is sent to the transcription engine to steer recognition.</p></div>+ <div>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="initialPromptTemplates.hotwords">Hotwords</label>+ <input type="text" id="ipTemplateHotwords" 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)] text-sm" data-i18n-placeholder="form.hotwordsPlaceholder" placeholder="e.g., Speakr, CTranslate2, PyAnnote">+ <p class="text-xs text-[var(--text-muted)] mt-2" data-i18n="initialPromptTemplates.hotwordsHelp">Optional comma-separated words to bias recognition of domain-specific terms.</p>+ </div>+<div class="flex items-center"><input type="checkbox" id="ipTemplateIsDefault" class="mr-2">- <label for="ipTemplateIsDefault" class="text-sm text-[var(--text-secondary)]" data-i18n="initialPromptTemplates.setDefault">Set as default prompt</label>+ <label for="ipTemplateIsDefault" class="text-sm text-[var(--text-secondary)]" data-i18n="initialPromptTemplates.setDefault">Set as default template</label></div><div class="flex gap-3">@@ -2301,7 +2307,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co{% if connector_supports_initial_prompt %}<div><label for="tagInitialPrompt" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="form.initialPrompt">Initial Prompt</label>- <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="tagInitialPrompt" style="display:none">+ <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="tagInitialPrompt" data-target-hotwords="tagHotwords" style="display:none"><option value="">Insert a saved prompt…</option></select><textarea id="tagInitialPrompt" name="default_initial_prompt" rows="2" 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)]" data-i18n-placeholder="form.initialPromptPlaceholder" placeholder="e.g., This is a meeting about AI transcription tools."></textarea>@@ -2523,7 +2529,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co{% if connector_supports_initial_prompt %}<div><label for="folderInitialPrompt" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="form.initialPrompt">Initial Prompt</label>- <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="folderInitialPrompt" style="display:none">+ <select class="ip-template-picker w-full mb-2 px-3 py-2 border border-[var(--border-secondary)] rounded-md text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" data-target="folderInitialPrompt" data-target-hotwords="folderHotwords" style="display:none"><option value="">Insert a saved prompt…</option></select><textarea id="folderInitialPrompt" name="default_initial_prompt" rows="2" 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)]" data-i18n-placeholder="form.initialPromptPlaceholder" placeholder="e.g., This is a meeting about AI transcription tools."></textarea>@@ -7200,7 +7206,8 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</codocument.getElementById('ipTemplateEmptyState').classList.add('hidden');document.getElementById('ipTemplateName').value = template.name;document.getElementById('ipTemplateDescription').value = template.description || '';- document.getElementById('ipTemplateContent').value = template.template;+ document.getElementById('ipTemplateContent').value = template.template || '';+ document.getElementById('ipTemplateHotwords').value = template.hotwords || '';document.getElementById('ipTemplateIsDefault').checked = template.is_default;document.getElementById('ipDeleteTemplateBtn').classList.remove('hidden');}@@ -7229,8 +7236,13 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</coname: document.getElementById('ipTemplateName').value,description: document.getElementById('ipTemplateDescription').value,template: document.getElementById('ipTemplateContent').value,+ hotwords: document.getElementById('ipTemplateHotwords').value,is_default: document.getElementById('ipTemplateIsDefault').checked};+ if (!templateData.name.trim() || !(templateData.template.trim() || templateData.hotwords.trim())) {+ showToast('Enter a name and a prompt or hotwords', 'error');+ return;+ }try {const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');const url = ipIsEditing ? `/api/initial-prompt-templates/${ipCurrentTemplate.id}` : '/api/initial-prompt-templates';@@ -7319,7 +7331,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co// Only show the picker once the user actually has saved prompts,// so single-prompt users keep a clean editor.sel.style.display = ipTemplates.length ? '' : 'none';- sel.innerHTML = '<option value="">' + (t('initialPromptTemplates.pickPlaceholder') || 'Insert a saved prompt…') + '</option>';+ sel.innerHTML = '<option value="">' + (t('initialPromptTemplates.pickPlaceholder') || 'Insert a saved template…') + '</option>';ipTemplates.forEach(tpl => {const opt = document.createElement('option');opt.value = String(tpl.id);@@ -7329,15 +7341,26 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co});}- // Delegated handler: choosing a saved prompt fills the picker's target textarea.+ // Delegated handler: choosing a saved template fills BOTH the picker's+ // target prompt field (data-target) and its hotwords field+ // (data-target-hotwords), so a transcription template applies prompt ++ // hotwords together.document.addEventListener('change', (e) => {const sel = e.target;if (!sel.classList || !sel.classList.contains('ip-template-picker')) return;const tpl = ipTemplates.find(t => String(t.id) === sel.value);- const target = document.getElementById(sel.dataset.target);- if (tpl && target) {- target.value = tpl.template;- target.dispatchEvent(new Event('input', { bubbles: true }));+ if (tpl) {+ const promptTarget = document.getElementById(sel.dataset.target);+ if (promptTarget) {+ promptTarget.value = tpl.template || '';+ promptTarget.dispatchEvent(new Event('input', { bubbles: true }));+ }+ const hotwordsTarget = sel.dataset.targetHotwords+ ? document.getElementById(sel.dataset.targetHotwords) : null;+ if (hotwordsTarget) {+ hotwordsTarget.value = tpl.hotwords || '';+ hotwordsTarget.dispatchEvent(new Event('input', { bubbles: true }));+ }}sel.value = '';});diff --git a/templates/components/upload-view.html b/templates/components/upload-view.htmlindex 611ec7a0..41ba8b19 100644--- a/templates/components/upload-view.html+++ b/templates/components/upload-view.html@@ -682,16 +682,16 @@</div><!-- end .disclosure-anim --></div>- <!-- Advanced ASR Options (collapsible). Shown whenever the active- connector supports any advanced option — not just diarization —- so hotwords/initial-prompt remain reachable on hint-only- connectors (e.g. OpenAI/Mistral) that don't diarize. -->+ <!-- Transcription Options (collapsible): one group for the saved+ template picker, initial prompt, hotwords and model, then+ language + speakers. Shown whenever the active connector supports+ any of them — not just diarization. --><div v-if="connectorSupportsDiarization || connectorSupportsSpeakerCount || connectorSupportsHotwords || connectorSupportsInitialPrompt" class="mt-4"><button @click="showAdvancedOptions = !showAdvancedOptions":class="['disclosure-trigger w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium', { 'is-open': showAdvancedOptions }]"><span class="flex items-center gap-2 text-[var(--text-secondary)]"><i class="fas fa-cog text-[var(--text-muted)]"></i>- <span v-text="t('help.advancedAsrOptions')"></span>+ <span v-text="t('upload.transcriptionOptions')"></span></span><i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i></button>@@ -699,6 +699,61 @@<div class="disclosure-anim" :class="{ 'is-open': showAdvancedOptions }"><div class="disclosure-anim__inner"><div class="disclosure-panel p-3 bg-[var(--bg-tertiary)] space-y-3 border border-[var(--border-secondary)]">+ <!-- Saved transcription template (#309): fills BOTH the initial+ prompt and hotwords below. Hidden until the user has saved+ templates. -->+ <div v-if="initialPromptTemplates && initialPromptTemplates.length && (connectorSupportsInitialPrompt || connectorSupportsHotwords)">+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">+ ${ t('initialPromptTemplates.savedTemplate') }+ </label>+ <select @change="applyInitialPromptTemplate($event.target.value); $event.target.value=''"+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">+ <option value="">${ t('initialPromptTemplates.pickPlaceholder') }</option>+ <option v-for="tpl in initialPromptTemplates" :key="tpl.id" :value="tpl.id" v-text="tpl.name"></option>+ </select>+ </div>++ <!-- Initial Prompt -->+ <div v-if="connectorSupportsInitialPrompt">+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">+ ${ t('form.initialPrompt') }+ </label>+ <textarea v-model="uploadInitialPrompt"+ rows="2"+ :placeholder="t('form.initialPromptPlaceholder')"+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] resize-y"></textarea>+ <p class="text-[10px] text-[var(--text-muted)] mt-0.5">${ t('form.initialPromptHelp') }</p>+ </div>++ <!-- Hotwords -->+ <div v-if="connectorSupportsHotwords">+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">+ ${ t('form.hotwords') }+ </label>+ <input v-model="uploadHotwords"+ type="text"+ :placeholder="t('form.hotwordsPlaceholder')"+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">+ <p class="text-[10px] text-[var(--text-muted)] mt-0.5">${ t('form.hotwordsHelp') }</p>+ </div>++ <!-- Transcription Model (issue #266 — visible only when admin set TRANSCRIPTION_MODELS_AVAILABLE).+ Only when there are at least 2 visible models. -->+ <div v-if="transcriptionModelOptions && transcriptionModelOptions.length > 1">+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">+ ${ t('form.transcriptionModel') }+ </label>+ <select v-model="uploadTranscriptionModel"+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">+ <option value="">${ t('form.useResolvedDefault') }</option>+ <option v-for="opt in transcriptionModelOptions" :key="opt.value" :value="opt.value" v-text="opt.label || opt.value"></option>+ </select>+ </div>++ <!-- Divider before the language / speakers (ASR) controls -->+ <hr v-if="connectorSupportsInitialPrompt || connectorSupportsHotwords || (transcriptionModelOptions && transcriptionModelOptions.length > 1)"+ class="border-t border-[var(--border-secondary)] my-1">+<!-- Language Selection --><div><label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">@@ -710,7 +765,7 @@</select></div>- <!-- Speaker Settings - only show for connectors that support min/max speakers -->+ <!-- Speaker Settings - only for connectors that support min/max speakers --><div v-if="connectorSupportsSpeakerCount" class="grid grid-cols-2 gap-3"><div><label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">@@ -732,52 +787,6 @@</div></div>- <!-- Hotwords -->- <div v-if="connectorSupportsHotwords">- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">- ${ t('form.hotwords') }- </label>- <input v-model="uploadHotwords"- type="text"- :placeholder="t('form.hotwordsPlaceholder')"- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">- <p class="text-[10px] text-[var(--text-muted)] mt-0.5">${ t('form.hotwordsHelp') }</p>- </div>-- <!-- Initial Prompt -->- <div v-if="connectorSupportsInitialPrompt">- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">- ${ t('form.initialPrompt') }- </label>- <!-- Pick from saved transcription prompts (#309). Hidden- until the user has saved prompts. -->- <select v-if="initialPromptTemplates && initialPromptTemplates.length"- @change="applyInitialPromptTemplate($event.target.value); $event.target.value=''"- class="w-full mb-1 px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">- <option value="">${ t('initialPromptTemplates.pickPlaceholder') }</option>- <option v-for="tpl in initialPromptTemplates" :key="tpl.id" :value="tpl.id" v-text="tpl.name"></option>- </select>- <textarea v-model="uploadInitialPrompt"- rows="2"- :placeholder="t('form.initialPromptPlaceholder')"- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] resize-y"></textarea>- <p class="text-[10px] text-[var(--text-muted)] mt-0.5">${ t('form.initialPromptHelp') }</p>- </div>-- <!-- Transcription Model (issue #266 — visible only when admin set TRANSCRIPTION_MODELS_AVAILABLE) -->- <!-- Only show the dropdown when there are at least 2 visible models;- a single visible model means there is no real choice to offer. -->- <div v-if="transcriptionModelOptions && transcriptionModelOptions.length > 1">- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">- ${ t('form.transcriptionModel') }- </label>- <select v-model="uploadTranscriptionModel"- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">- <option value="">${ t('form.useResolvedDefault') }</option>- <option v-for="opt in transcriptionModelOptions" :key="opt.value" :value="opt.value" v-text="opt.label || opt.value"></option>- </select>- </div>-<p class="text-xs text-[var(--text-muted)] pt-1"><i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>${ t('upload.settingsApplyToAll') }diff --git a/tests/test_cov_initial_prompt_templates.py b/tests/test_cov_initial_prompt_templates.pyindex 944f83c4..f034e994 100644--- a/tests/test_cov_initial_prompt_templates.py+++ b/tests/test_cov_initial_prompt_templates.py@@ -66,19 +66,40 @@ def test_requires_auth():def test_create_and_list(client, user):resp = client.post('/api/initial-prompt-templates',- json={'name': 'Meeting', 'template': 'This is a meeting.'})+ json={'name': 'Meeting', 'template': 'This is a meeting.', 'hotwords': 'Acme, KPI'})assert resp.status_code == 201created = resp.get_json()assert created['name'] == 'Meeting'assert created['template'] == 'This is a meeting.'+ assert created['hotwords'] == 'Acme, KPI'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):+def test_create_hotwords_only(client):+ # A template may carry hotwords with no prompt.+ resp = client.post('/api/initial-prompt-templates',+ json={'name': 'Jargon', 'hotwords': 'CTranslate2, PyAnnote'})+ assert resp.status_code == 201+ created = resp.get_json()+ assert created['template'] == ''+ assert created['hotwords'] == 'CTranslate2, PyAnnote'+++def test_update_hotwords(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={'hotwords': 'foo, bar'})+ assert resp.status_code == 200+ assert resp.get_json()['hotwords'] == 'foo, bar'+++def test_create_requires_name_and_some_content(client):+ # Need a name AND at least one of prompt/hotwords.assert client.post('/api/initial-prompt-templates', json={'name': 'x'}).status_code == 400assert client.post('/api/initial-prompt-templates', json={'template': 'x'}).status_code == 400+ assert client.post('/api/initial-prompt-templates', json={'name': 'x', 'hotwords': ' '}).status_code == 400def test_single_default_enforced(client, user):