Skip to content

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

Python

Add per-feature transcript timestamp toggles for summary and chat with default-or-template format selection (#304)

Murtaza Nasir426a0a806b0e
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index a0d39224..b7dd521b 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2353,7 +2353,7 @@ def start_summarization(recording_id):
def chat_with_recording(recording_id):
"""Chat about a recording's content."""
from src.services.llm import chat_client, call_chat_completion
- from src.tasks.processing import format_transcription_for_llm
+ from src.tasks.processing import format_transcription_for_llm, _resolve_timestamp_template_format
from src.models import SystemSetting
recording = db.session.get(Recording, recording_id)
@@ -2377,8 +2377,14 @@ def chat_with_recording(recording_id):
if chat_client is None:
return jsonify({'error': 'Chat service not available'}), 503
- # Format transcription
- formatted_transcription = format_transcription_for_llm(recording.transcription)
+ # Format transcription (optionally with timestamps per the user's setting, #304)
+ _chat_ts = bool(current_user.chat_include_timestamps)
+ formatted_transcription = format_transcription_for_llm(
+ recording.transcription,
+ include_timestamps=_chat_ts,
+ template_format=_resolve_timestamp_template_format(
+ current_user, current_user.chat_timestamp_template_id) if _chat_ts else None,
+ )
# Get transcript limit
transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
diff --git a/src/api/auth.py b/src/api/auth.py
index 8d16c234..661adfbd 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -608,6 +608,22 @@ def account():
initial_prompt = request.form.get('transcription_initial_prompt')
current_user.transcription_initial_prompt = initial_prompt if initial_prompt else None
+ # Per-feature transcript timestamp settings (#304). A template id is
+ # only accepted if it belongs to the user; otherwise fall back to the
+ # built-in default format (None).
+ def _ts_template_id(field):
+ raw = (request.form.get(field) or '').strip()
+ if not raw.isdigit():
+ return None
+ from src.models import TranscriptTemplate
+ tpl = TranscriptTemplate.query.filter_by(id=int(raw), user_id=current_user.id).first()
+ return tpl.id if tpl else None
+
+ current_user.summary_include_timestamps = 'summary_include_timestamps' in request.form
+ current_user.summary_timestamp_template_id = _ts_template_id('summary_timestamp_template_id')
+ current_user.chat_include_timestamps = 'chat_include_timestamps' in request.form
+ current_user.chat_timestamp_template_id = _ts_template_id('chat_timestamp_template_id')
+
# Only update diarize if it's not locked by env var
if 'ASR_DIARIZE' not in os.environ:
current_user.diarize = 'diarize' in request.form
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 1aeb0e46..9476a965 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -72,7 +72,7 @@ def _resolve_transcription_model(value):
# Fall back to admin-saved default when no override flowed through.
default = SystemSetting.get_setting('transcription_default_model', None)
return default or None
-from src.tasks.processing import format_transcription_for_llm
+from src.tasks.processing import format_transcription_for_llm, _resolve_timestamp_template_format
from src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundError
from src.utils.titles import resolve_upload_title
from src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text
@@ -3023,7 +3023,13 @@ def chat_incognito():
user_title = current_user.job_title if current_user.is_authenticated and current_user.job_title else "a professional"
user_company = current_user.company if current_user.is_authenticated and current_user.company else "their organization"
- formatted_transcription = format_transcription_for_llm(transcription)
+ _chat_ts = bool(current_user.is_authenticated and current_user.chat_include_timestamps)
+ formatted_transcription = format_transcription_for_llm(
+ transcription,
+ include_timestamps=_chat_ts,
+ template_format=_resolve_timestamp_template_format(
+ current_user, current_user.chat_timestamp_template_id) if _chat_ts else None,
+ )
# Get configurable transcript length limit for chat
transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
@@ -3747,7 +3753,14 @@ def chat_with_transcription():
user_title = current_user.job_title if current_user.is_authenticated and current_user.job_title else "a professional"
user_company = current_user.company if current_user.is_authenticated and current_user.company else "their organization"
- formatted_transcription = format_transcription_for_llm(recording.transcription)
+ # Optionally include timestamps in the chat transcript per the user's setting (#304).
+ _chat_ts = bool(current_user.is_authenticated and current_user.chat_include_timestamps)
+ formatted_transcription = format_transcription_for_llm(
+ recording.transcription,
+ include_timestamps=_chat_ts,
+ template_format=_resolve_timestamp_template_format(
+ current_user, current_user.chat_timestamp_template_id) if _chat_ts else None,
+ )
# Get configurable transcript length limit for chat
transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
diff --git a/src/init_db.py b/src/init_db.py
index 7e842171..931ffd06 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -339,6 +339,16 @@ def initialize_database(app):
if add_column_if_not_exists(engine, 'user', 'transcription_initial_prompt', 'TEXT'):
app.logger.info("Added transcription_initial_prompt column to user table")
+ # Per-feature transcript timestamp settings (#304)
+ if add_column_if_not_exists(engine, 'user', 'summary_include_timestamps', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added summary_include_timestamps column to user table")
+ if add_column_if_not_exists(engine, 'user', 'summary_timestamp_template_id', 'INTEGER'):
+ app.logger.info("Added summary_timestamp_template_id column to user table")
+ if add_column_if_not_exists(engine, 'user', 'chat_include_timestamps', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added chat_include_timestamps column to user table")
+ if add_column_if_not_exists(engine, 'user', 'chat_timestamp_template_id', 'INTEGER'):
+ app.logger.info("Added chat_timestamp_template_id column to user table")
+
# UI/display preferences
if add_column_if_not_exists(engine, 'user', 'show_timestamps_simple_view', 'BOOLEAN DEFAULT 0'):
app.logger.info("Added show_timestamps_simple_view column to user table")
diff --git a/src/models/templates.py b/src/models/templates.py
index 1d98da1b..778d0a63 100644
--- a/src/models/templates.py
+++ b/src/models/templates.py
@@ -21,8 +21,10 @@ class TranscriptTemplate(db.Model):
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('transcript_templates', lazy=True, cascade='all, delete-orphan'))
+ # Relationships. foreign_keys is explicit because User also has FK columns
+ # pointing back here (summary/chat timestamp template, #304), which would
+ # otherwise make this join ambiguous.
+ user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('transcript_templates', lazy=True, cascade='all, delete-orphan'))
def to_dict(self):
"""Convert model to dictionary representation."""
diff --git a/src/models/user.py b/src/models/user.py
index cc5863e1..28c6f036 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -62,6 +62,14 @@ class User(db.Model, UserMixin):
transcription_hotwords = db.Column(db.Text, nullable=True)
transcription_initial_prompt = db.Column(db.Text, nullable=True)
+ # Include timestamps in the transcript sent to the summarizer / chat (#304).
+ # Independent per feature; the *_template_id selects a transcript template to
+ # format the timestamps (null = a built-in default timestamp format).
+ summary_include_timestamps = db.Column(db.Boolean, default=False)
+ summary_timestamp_template_id = db.Column(db.Integer, db.ForeignKey('transcript_template.id', ondelete='SET NULL'), nullable=True)
+ chat_include_timestamps = db.Column(db.Boolean, default=False)
+ chat_timestamp_template_id = db.Column(db.Integer, db.ForeignKey('transcript_template.id', ondelete='SET NULL'), nullable=True)
+
# UI/display preferences
show_timestamps_simple_view = db.Column(db.Boolean, default=False)
editor_autosave = db.Column(db.Boolean, default=False)
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 64005510..e5456fb2 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -204,11 +204,32 @@ def apply_team_tag_auto_shares(recording_id):
current_app.logger.info(f"Created {shares_created} auto-shares for recording {recording_id} after processing completed")
-def format_transcription_for_llm(transcription_text):
+def _resolve_timestamp_template_format(user, template_id):
+ """Return the format string of a user's transcript template, or None (#304).
+
+ Scoped to the user's own templates so one user can't reference another's.
+ """
+ if not template_id or user is None:
+ return None
+ from src.models import TranscriptTemplate
+ tpl = TranscriptTemplate.query.filter_by(id=template_id, user_id=user.id).first()
+ return tpl.template if tpl else None
+
+
+def format_transcription_for_llm(transcription_text, include_timestamps=False, template_format=None):
"""
Formats transcription for LLM. If it's our simplified JSON, convert it to plain text.
Otherwise, return as is.
+
+ When include_timestamps is True the transcript is rendered with a transcript
+ template (the given template_format, or a built-in default timestamp format)
+ so the summarizer / chat can reference times (#304).
"""
+ if include_timestamps:
+ from src.utils.transcript_render import render_transcription
+ rendered = render_transcription(transcription_text, template_format)
+ if rendered is not None:
+ return rendered
try:
transcription_data = json.loads(transcription_text)
if isinstance(transcription_data, list):
@@ -607,8 +628,16 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_override
user_summary_prompt = recording.owner.summary_prompt
user_output_language = recording.owner.output_language
- # Format transcription for LLM (convert JSON to clean text format like clipboard copy)
- formatted_transcription = format_transcription_for_llm(recording.transcription)
+ # Format transcription for LLM (convert JSON to clean text format like clipboard copy).
+ # Optionally include timestamps for the summarizer per the owner's setting (#304).
+ _owner = recording.owner
+ _summary_ts = bool(_owner and _owner.summary_include_timestamps)
+ formatted_transcription = format_transcription_for_llm(
+ recording.transcription,
+ include_timestamps=_summary_ts,
+ template_format=_resolve_timestamp_template_format(
+ _owner, _owner.summary_timestamp_template_id) if _summary_ts else None,
+ )
# Get configurable transcript length limit
transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
diff --git a/src/utils/transcript_render.py b/src/utils/transcript_render.py
new file mode 100644
index 00000000..8d274ff6
--- /dev/null
+++ b/src/utils/transcript_render.py
@@ -0,0 +1,74 @@
+"""
+Render the stored simplified-JSON transcript into text using a transcript-template
+format string. Used to inject timestamps into the transcript sent to the
+summarizer / chat (#304). Mirrors the placeholder/filter handling in
+file_exporter.format_transcription_with_template so the formats line up.
+
+Segment schema (see TranscriptionResponse.to_storage_format):
+ {"speaker": str, "sentence": str, "start_time": float|None, "end_time": float|None}
+
+Supported placeholders: {{index}} {{speaker}} {{text}} {{start_time}} {{end_time}}
+Supported filters: |upper, and |srt on start_time/end_time.
+"""
+
+import json
+import re
+from datetime import timedelta
+
+# Built-in default used when timestamps are requested but no template is chosen.
+DEFAULT_TIMESTAMP_FORMAT = "[{{start_time}}] {{speaker}}: {{text}}"
+
+
+def _fmt_time(seconds):
+ if seconds is None:
+ return "00:00:00"
+ td = timedelta(seconds=seconds)
+ total = td.total_seconds()
+ return f"{int(total // 3600):02d}:{int((total % 3600) // 60):02d}:{int(total % 60):02d}"
+
+
+def _fmt_srt_time(seconds):
+ if seconds is None:
+ return "00:00:00,000"
+ td = timedelta(seconds=seconds)
+ total = td.total_seconds()
+ return (f"{int(total // 3600):02d}:{int((total % 3600) // 60):02d}:"
+ f"{int(total % 60):02d},{int((total % 1) * 1000):03d}")
+
+
+def render_transcription(transcription_text, template_format):
+ """Render the transcript JSON with `template_format`.
+
+ Returns the rendered text, or None if the input isn't our segment-list JSON
+ (caller should then fall back to its plain-text handling).
+ """
+ try:
+ data = json.loads(transcription_text)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(data, list):
+ return None
+
+ fmt = template_format or DEFAULT_TIMESTAMP_FORMAT
+ lines = []
+ for index, segment in enumerate(data, 1):
+ line = fmt
+ replacements = {
+ '{{index}}': str(index),
+ '{{speaker}}': segment.get('speaker', 'Unknown'),
+ '{{text}}': segment.get('sentence', ''),
+ '{{start_time}}': _fmt_time(segment.get('start_time')),
+ '{{end_time}}': _fmt_time(segment.get('end_time')),
+ }
+ # SRT-time filters first (more specific than the |upper sweep).
+ line = line.replace('{{start_time|srt}}', _fmt_srt_time(segment.get('start_time')))
+ line = line.replace('{{end_time|srt}}', _fmt_srt_time(segment.get('end_time')))
+ line = re.sub(
+ r'\{\{(.*?)\|upper\}\}',
+ lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(),
+ line,
+ )
+ for key, value in replacements.items():
+ line = line.replace(key, value)
+ lines.append(line)
+ return '\n'.join(lines)
diff --git a/static/locales/de.json b/static/locales/de.json
index a9a6a8e0..33556610 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -1612,6 +1612,13 @@
"hints": "Hinweise",
"hintsUsed": "Für diese Aufnahme verwendete Transkriptionshinweise"
},
+ "timestamps": {
+ "title": "Transkript-Zeitstempel",
+ "description": "Fügen Sie dem an die KI gesendeten Transkript Zeitmarken hinzu, damit sie sich darauf beziehen kann, wann etwas gesagt wurde. Verwenden Sie das Standardformat oder eine Ihrer Transkriptvorlagen.",
+ "summaryLabel": "Zeitstempel zum Transkript des Zusammenfassers hinzufügen",
+ "chatLabel": "Zeitstempel zum Chat-Transkript hinzufügen",
+ "defaultFormat": "Standard-Zeitstempelformat"
+ },
"transcription": {
"autoIdentifySpeakers": "Sprecher automatisch identifizieren",
"bubble": "Blase",
diff --git a/static/locales/en.json b/static/locales/en.json
index 891231e9..e604881a 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -1621,6 +1621,13 @@
"hints": "Hints",
"hintsUsed": "Transcription hints used for this recording"
},
+ "timestamps": {
+ "title": "Transcript Timestamps",
+ "description": "Include time markers in the transcript sent to the AI so it can reference when things were said. Use the default format, or one of your transcript templates.",
+ "summaryLabel": "Add timestamps to the summarizer's transcript",
+ "chatLabel": "Add timestamps to the chat transcript",
+ "defaultFormat": "Default timestamp format"
+ },
"transcription": {
"autoIdentifySpeakers": "Auto-identify Speakers",
"bubble": "Bubble",
diff --git a/static/locales/es.json b/static/locales/es.json
index b38a484a..ae88dc99 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -1612,6 +1612,13 @@
"hints": "Indicaciones",
"hintsUsed": "Indicaciones de transcripción usadas en esta grabación"
},
+ "timestamps": {
+ "title": "Marcas de tiempo de la transcripción",
+ "description": "Incluye marcas de tiempo en la transcripción enviada a la IA para que pueda indicar cuándo se dijo algo. Usa el formato predeterminado o una de tus plantillas de transcripción.",
+ "summaryLabel": "Añadir marcas de tiempo a la transcripción del resumen",
+ "chatLabel": "Añadir marcas de tiempo a la transcripción del chat",
+ "defaultFormat": "Formato de marca de tiempo predeterminado"
+ },
"transcription": {
"autoIdentifySpeakers": "Identificar Hablantes Automáticamente",
"bubble": "Burbuja",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 6f31a851..8d5001eb 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -1612,6 +1612,13 @@
"hints": "Indices",
"hintsUsed": "Indices de transcription utilisés pour cet enregistrement"
},
+ "timestamps": {
+ "title": "Horodatage de la transcription",
+ "description": "Ajoutez des repères temporels à la transcription envoyée à l'IA afin qu'elle puisse indiquer à quel moment les choses ont été dites. Utilisez le format par défaut ou l'un de vos modèles de transcription.",
+ "summaryLabel": "Ajouter des horodatages à la transcription du résumé",
+ "chatLabel": "Ajouter des horodatages à la transcription du chat",
+ "defaultFormat": "Format d'horodatage par défaut"
+ },
"transcription": {
"autoIdentifySpeakers": "Identifier Automatiquement les Orateurs",
"bubble": "Bulle",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index e32b6487..2e4fb64f 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -1612,6 +1612,13 @@
"hints": "Dicas",
"hintsUsed": "Dicas de transcrição usadas nesta gravação"
},
+ "timestamps": {
+ "title": "Marcações de tempo da transcrição",
+ "description": "Inclua marcações de tempo na transcrição enviada à IA para que ela possa indicar quando algo foi dito. Use o formato padrão ou um dos seus modelos de transcrição.",
+ "summaryLabel": "Adicionar marcações de tempo à transcrição do resumo",
+ "chatLabel": "Adicionar marcações de tempo à transcrição do chat",
+ "defaultFormat": "Formato de marcação de tempo padrão"
+ },
"transcription": {
"autoIdentifySpeakers": "Identificar Oradores Automaticamente",
"bubble": "Bolha",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index def94994..8dd7c585 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -1612,6 +1612,13 @@
"hints": "Подсказки",
"hintsUsed": "Подсказки транскрипции, использованные для этой записи"
},
+ "timestamps": {
+ "title": "Метки времени транскрипции",
+ "description": "Добавляйте метки времени в транскрипцию, отправляемую ИИ, чтобы он мог ссылаться на то, когда что-то было сказано. Используйте формат по умолчанию или один из ваших шаблонов транскрипции.",
+ "summaryLabel": "Добавлять метки времени в транскрипцию для резюме",
+ "chatLabel": "Добавлять метки времени в транскрипцию для чата",
+ "defaultFormat": "Формат меток времени по умолчанию"
+ },
"transcription": {
"autoIdentifySpeakers": "Автоопределение спикеров",
"bubble": "Пузыри",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 8a933ee6..62306b2d 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -1612,6 +1612,13 @@
"hints": "提示",
"hintsUsed": "本次录音使用的转录提示"
},
+ "timestamps": {
+ "title": "转录时间戳",
+ "description": "在发送给 AI 的转录中加入时间标记,使其能够引用某句话的发生时间。使用默认格式,或选择您的某个转录模板。",
+ "summaryLabel": "为摘要使用的转录添加时间戳",
+ "chatLabel": "为聊天使用的转录添加时间戳",
+ "defaultFormat": "默认时间戳格式"
+ },
"transcription": {
"autoIdentifySpeakers": "自动识别发言人",
"bubble": "气泡",
diff --git a/templates/account.html b/templates/account.html
index 2f87f11b..7e9d7aea 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -868,6 +868,49 @@
</div>
</div>
+ <!-- Transcript Timestamps (#304) -->
+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">
+ <i class="fas fa-clock mr-2"></i>
+ <span data-i18n="timestamps.title">Transcript Timestamps</span>
+ </h3>
+ <p class="text-xs text-[var(--text-muted)] mb-4" data-i18n="timestamps.description">
+ Include time markers in the transcript sent to the AI so it can reference when things were said. Use the default format, or one of your transcript templates.
+ </p>
+
+ <div class="mb-4">
+ <label class="flex items-start space-x-3">
+ <input type="checkbox" name="summary_include_timestamps" id="summary_include_timestamps"
+ {% if current_user.summary_include_timestamps %}checked{% endif %}
+ class="mt-1 h-4 w-4 text-[var(--border-accent)] focus:ring-[var(--border-focus)] border-[var(--border-secondary)] rounded">
+ <div>
+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="timestamps.summaryLabel">Add timestamps to the summarizer's transcript</span>
+ </div>
+ </label>
+ <select name="summary_timestamp_template_id" id="summary_timestamp_template_id"
+ data-selected="{{ current_user.summary_timestamp_template_id or '' }}"
+ class="ts-template-picker mt-2 ml-7 w-[calc(100%-1.75rem)] px-3 py-2 border border-[var(--border-secondary)] rounded-md sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="" data-i18n="timestamps.defaultFormat">Default timestamp format</option>
+ </select>
+ </div>
+
+ <div>
+ <label class="flex items-start space-x-3">
+ <input type="checkbox" name="chat_include_timestamps" id="chat_include_timestamps"
+ {% if current_user.chat_include_timestamps %}checked{% endif %}
+ class="mt-1 h-4 w-4 text-[var(--border-accent)] focus:ring-[var(--border-focus)] border-[var(--border-secondary)] rounded">
+ <div>
+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="timestamps.chatLabel">Add timestamps to the chat transcript</span>
+ </div>
+ </label>
+ <select name="chat_timestamp_template_id" id="chat_timestamp_template_id"
+ data-selected="{{ current_user.chat_timestamp_template_id or '' }}"
+ class="ts-template-picker mt-2 ml-7 w-[calc(100%-1.75rem)] px-3 py-2 border border-[var(--border-secondary)] rounded-md sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="" data-i18n="timestamps.defaultFormat">Default timestamp format</option>
+ </select>
+ </div>
+ </div>
+
</form>
</div><!-- /.tab-scroll -->
<div class="tab-footer">
@@ -3174,6 +3217,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
loadSystemInfo();
} else if (targetName === 'prompts') {
ensureInitialPromptTemplatesLoaded();
+ loadTimestampTemplatePickers();
}
}
@@ -7051,10 +7095,13 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
// ============================================
// Initial-Prompt (Transcription) Templates
// ============================================
- let ipTemplates = [];
- let ipCurrentTemplate = null;
- let ipIsEditing = false;
- let ipTemplatesLoaded = false;
+ // var (not let) so these hoist: the prompts tab can be activated from a
+ // #prompts hash during page init, before this line runs, and the handler
+ // reads ipTemplatesLoaded — a `let` would throw a TDZ ReferenceError.
+ var ipTemplates = [];
+ var ipCurrentTemplate = null;
+ var ipIsEditing = false;
+ var ipTemplatesLoaded = false;
async function loadInitialPromptTemplates() {
try {
@@ -7082,6 +7129,28 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
await loadInitialPromptTemplates();
}
+ // Populate the per-feature timestamp-format dropdowns (#304) with the
+ // user's transcript templates, preserving each one's saved selection.
+ async function loadTimestampTemplatePickers() {
+ const pickers = document.querySelectorAll('select.ts-template-picker');
+ if (!pickers.length) return;
+ try {
+ const resp = await fetch('/api/transcript-templates');
+ if (!resp.ok) return;
+ const tts = await resp.json();
+ pickers.forEach(sel => {
+ while (sel.options.length > 1) sel.remove(1); // keep the "Default" option
+ tts.forEach(tpl => {
+ const opt = document.createElement('option');
+ opt.value = String(tpl.id);
+ opt.textContent = tpl.name;
+ sel.appendChild(opt);
+ });
+ sel.value = sel.dataset.selected || '';
+ });
+ } catch (_) { /* leave default-only */ }
+ }
+
function renderIpTemplatesList() {
const list = document.getElementById('ipTemplatesList');
if (!list) return;
diff --git a/tests/test_transcript_timestamps.py b/tests/test_transcript_timestamps.py
new file mode 100644
index 00000000..fec7604a
--- /dev/null
+++ b/tests/test_transcript_timestamps.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""
+#304: optional timestamps in the transcript handed to the summarizer / chat.
+
+Covers the pure rendering layer (no app/DB needed):
+ - render_transcription with the default + custom template formats
+ - format_transcription_for_llm: timestamps on/off and plain-text passthrough
+
+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_transcript_timestamps.py -q"
+"""
+
+import json
+
+from src.utils.transcript_render import render_transcription, DEFAULT_TIMESTAMP_FORMAT
+from src.tasks.processing import format_transcription_for_llm
+
+SEGMENTS = json.dumps([
+ {"speaker": "Alice", "sentence": "Hello there", "start_time": 0.0, "end_time": 2.0},
+ {"speaker": "Bob", "sentence": "Hi", "start_time": 65.0, "end_time": 67.0},
+])
+
+
+def test_render_default_format_has_hms_timestamps():
+ out = render_transcription(SEGMENTS, DEFAULT_TIMESTAMP_FORMAT)
+ assert out == "[00:00:00] Alice: Hello there\n[00:01:05] Bob: Hi"
+
+
+def test_render_custom_template_and_srt_filter():
+ out = render_transcription(SEGMENTS, "{{start_time|srt}} {{speaker|upper}}: {{text}}")
+ assert out.splitlines()[0] == "00:00:00,000 ALICE: Hello there"
+ assert out.splitlines()[1] == "00:01:05,000 BOB: Hi"
+
+
+def test_render_returns_none_for_plain_text():
+ # Not our JSON segment list -> caller falls back to plain handling.
+ assert render_transcription("just a plain transcript", DEFAULT_TIMESTAMP_FORMAT) is None
+
+
+def test_format_for_llm_timestamps_off_is_plain():
+ out = format_transcription_for_llm(SEGMENTS, include_timestamps=False)
+ assert out == "[Alice]: Hello there\n[Bob]: Hi"
+
+
+def test_format_for_llm_timestamps_on_default():
+ out = format_transcription_for_llm(SEGMENTS, include_timestamps=True)
+ assert out == "[00:00:00] Alice: Hello there\n[00:01:05] Bob: Hi"
+
+
+def test_format_for_llm_timestamps_on_custom_template():
+ out = format_transcription_for_llm(
+ SEGMENTS, include_timestamps=True, template_format="{{start_time}} {{speaker}}")
+ assert out == "00:00:00 Alice\n00:01:05 Bob"
+
+
+def test_format_for_llm_plain_text_passthrough_even_with_timestamps():
+ # A non-JSON transcript can't be timestamped; it must pass through unchanged.
+ assert format_transcription_for_llm("plain text", include_timestamps=True) == "plain text"