Skip to content

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

Python

One title step for processing and regenerate-title (#412): naming template from tag, then folder (was never used), then user default; template-only titles need no LLM call; regenerate re-exports the recording

Murtaza Nasir7cf6ef4bbdd7
diff --git a/src/api/recordings.py b/src/api/recordings.py
index d47035f6..f97b9ce3 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -1327,23 +1327,31 @@ def regenerate_title(recording_id):
if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'You do not have permission to edit this recording'}), 403
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- return jsonify({'error': 'No valid transcription available for title generation'}), 400
+ # Same title step as processing (naming template, AI title, fallbacks), so
+ # regenerating gives the title the pipeline would give (#412). The checks
+ # below apply only when the title needs an LLM call.
+ from src.services.titling import compute_title, needs_ai_title
+ if needs_ai_title(recording):
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ return jsonify({'error': 'No valid transcription available for title generation'}), 400
- if is_transcription_error(recording.transcription):
- return jsonify({'error': 'Cannot generate title: transcription failed. Please reprocess the transcription first.'}), 400
+ if is_transcription_error(recording.transcription):
+ return jsonify({'error': 'Cannot generate title: transcription failed. Please reprocess the transcription first.'}), 400
- if client is None:
- return jsonify({'error': 'Title generation service is not available (OpenRouter client not configured)'}), 503
+ if client is None:
+ return jsonify({'error': 'Title generation service is not available (OpenRouter client not configured)'}), 503
- from src.tasks.processing import _generate_ai_title
-
- new_title = _generate_ai_title(recording)
+ new_title = compute_title(recording, raise_budget_errors=True)
if not new_title:
return jsonify({'error': 'Failed to generate a title'}), 500
recording.title = new_title
db.session.commit()
+ # Keep the exported file in step with the new title, as /save does.
+ try:
+ export_recording(recording.id)
+ except Exception as export_error:
+ current_app.logger.warning(f"Export after title regeneration failed for {recording.id}: {export_error}")
recording_dict = recording.to_dict(viewer_user=current_user)
enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
diff --git a/src/services/titling.py b/src/services/titling.py
new file mode 100644
index 00000000..096529c3
--- /dev/null
+++ b/src/services/titling.py
@@ -0,0 +1,93 @@
+"""The title step of the processing pipeline.
+
+Every path that gives a recording its generated title calls these functions:
+the background title task after transcription and the regenerate-title
+endpoint (web and API v1). The title is therefore the same whichever path
+produced it, and a rule added here reaches all of them (#412).
+
+Order of the title rules:
+1. Naming template: the first tag on the recording with a template, then the
+ recording's folder, then the owner's default template.
+2. A template without {{ai_title}} needs no LLM call.
+3. Otherwise the AI title is generated and passed through the template.
+4. Fallback: template result, then AI title, then the filename without its
+ extension.
+"""
+
+import os
+
+from flask import current_app
+
+from src.database import db
+from src.models import Folder
+
+
+def resolve_naming_template(recording):
+ """The naming template for a recording: tag, then folder, then the owner's default.
+
+ Returns (template, source) where source is 'tag', 'folder', 'user' or None.
+ """
+ for tag in recording.tags:
+ if tag.naming_template_id and tag.naming_template:
+ return tag.naming_template, 'tag'
+ if recording.folder_id:
+ folder = db.session.get(Folder, recording.folder_id)
+ if folder and folder.naming_template_id and folder.naming_template:
+ return folder.naming_template, 'folder'
+ owner = recording.owner
+ if owner and owner.default_naming_template_id and owner.default_naming_template:
+ return owner.default_naming_template, 'user'
+ return None, None
+
+
+def needs_ai_title(recording):
+ """True when the title for this recording requires an LLM call."""
+ template, _ = resolve_naming_template(recording)
+ return template is None or template.needs_ai_title()
+
+
+def compute_title(recording, *, raise_budget_errors=False):
+ """The title the pipeline gives this recording now, without saving it.
+
+ TokenBudgetExceeded propagates when raise_budget_errors is True (the
+ interactive endpoint shows the reason); background callers skip the AI
+ title instead.
+ """
+ # Read through the processing module so tests and callers that patch
+ # processing.client / processing._generate_ai_title affect this step too.
+ from src.tasks import processing
+ from src.services.llm import TokenBudgetExceeded
+
+ template, source = resolve_naming_template(recording)
+ if template:
+ current_app.logger.info(
+ f"Using naming template '{template.name}' ({source}) for recording {recording.id}")
+
+ ai_title = None
+ if template is not None and not template.needs_ai_title():
+ current_app.logger.info(f"Naming template needs no AI title for recording {recording.id}")
+ elif processing.client is None:
+ current_app.logger.warning(f"Skipping AI title for {recording.id}: LLM client not configured.")
+ elif not recording.transcription or len(recording.transcription.strip()) < 10:
+ current_app.logger.warning(f"Transcription for recording {recording.id} is too short for an AI title.")
+ else:
+ try:
+ ai_title = processing._generate_ai_title(recording)
+ except TokenBudgetExceeded as e:
+ if raise_budget_errors:
+ raise
+ current_app.logger.warning(f"Skipping AI title for recording {recording.id}: {e}")
+
+ title = None
+ if template:
+ title = template.apply(
+ original_filename=recording.original_filename,
+ meeting_date=recording.meeting_date,
+ ai_title=ai_title,
+ )
+ if not title:
+ title = ai_title
+ if not title and recording.original_filename:
+ title = os.path.splitext(recording.original_filename)[0]
+ current_app.logger.info(f"Using filename as title for recording {recording.id}: '{title}'")
+ return title
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index a4335785..940a6b38 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -382,63 +382,10 @@ def generate_title_task(app_context, recording_id, will_auto_summarize=False):
db.session.commit()
return
- # Resolve naming template: first tag with template → user default → None
- naming_template = None
- for tag in recording.tags:
- if tag.naming_template_id:
- naming_template = tag.naming_template
- current_app.logger.info(f"Using naming template '{naming_template.name}' from tag '{tag.name}' for recording {recording_id}")
- break
-
- if not naming_template and recording.owner and recording.owner.default_naming_template_id:
- naming_template = recording.owner.default_naming_template
- if naming_template:
- current_app.logger.info(f"Using user's default naming template '{naming_template.name}' for recording {recording_id}")
-
- # Check if we need to generate AI title
- needs_ai_title = naming_template is None or naming_template.needs_ai_title()
-
- # Early exit conditions
- if not needs_ai_title:
- # Template doesn't need AI - we can skip LLM call entirely
- current_app.logger.info(f"Naming template doesn't require AI title for recording {recording_id}, skipping LLM call")
- ai_title = None
- elif client is None:
- current_app.logger.warning(f"Skipping AI title generation for {recording_id}: OpenRouter client not configured.")
- ai_title = None
- elif not recording.transcription or len(recording.transcription.strip()) < 10:
- current_app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping AI title generation.")
- ai_title = None
- else:
- # Generate AI title via LLM. A budget-exceeded error is actionable
- # by the user but must not fail the whole recording here — skip
- # titling and continue (the interactive endpoint surfaces it).
- try:
- ai_title = _generate_ai_title(recording)
- except TokenBudgetExceeded as e:
- current_app.logger.warning(f"Skipping AI title for recording {recording_id}: {e}")
- ai_title = None
-
- # Apply naming template if we have one
- final_title = None
- if naming_template:
- final_title = naming_template.apply(
- original_filename=recording.original_filename,
- meeting_date=recording.meeting_date,
- ai_title=ai_title
- )
- if final_title:
- current_app.logger.info(f"Applied naming template for recording {recording_id}: '{final_title}'")
-
- # Fallback chain: template result → AI title → filename
- if not final_title:
- if ai_title:
- final_title = ai_title
- elif recording.original_filename:
- # Use filename without extension as last resort
- import os
- final_title = os.path.splitext(recording.original_filename)[0]
- current_app.logger.info(f"Using filename as title for recording {recording_id}: '{final_title}'")
+ # The title step (naming template, AI title, fallbacks) is shared with the
+ # regenerate-title endpoint so both produce the same title (#412).
+ from src.services.titling import compute_title
+ final_title = compute_title(recording)
if final_title:
recording.title = final_title
diff --git a/tests/test_title_step.py b/tests/test_title_step.py
new file mode 100644
index 00000000..50abe2c2
--- /dev/null
+++ b/tests/test_title_step.py
@@ -0,0 +1,191 @@
+"""The title step is shared by processing and the regenerate-title endpoint (#412).
+
+Before #412 the regenerate button saved the raw AI title and ignored the
+naming template, and a folder's naming template was saved but never used.
+These tests pin the shared order (tag, then folder, then the owner's default),
+the template-only case without an LLM call, and that the background task and
+the button produce the same title for the same recording.
+
+SHARED-DB: everything created here is removed afterwards.
+"""
+
+import os
+import secrets
+import sys
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+from flask import g
+from flask.testing import FlaskClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import Folder, NamingTemplate, Recording, RecordingTag, Tag, User
+from src.services.titling import compute_title, resolve_naming_template
+from src.tasks import processing
+
+app.config["WTF_CSRF_ENABLED"] = False
+TRANSCRIPT = "Speaker 1: We agreed to move the launch to next quarter and review the budget on Monday."
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def world():
+ """A user with a recording, a tag, a folder and three naming templates."""
+ with app.app_context():
+ name = f"titlestep_{secrets.token_hex(4)}"
+ user = User(username=name, email=f"{name}@local.test")
+ db.session.add(user)
+ db.session.commit()
+ t_tag = NamingTemplate(user_id=user.id, name="tag-t", template="TAG {{ai_title}}")
+ t_folder = NamingTemplate(user_id=user.id, name="folder-t", template="FOLDER {{ai_title}}")
+ t_user = NamingTemplate(user_id=user.id, name="user-t", template="USER {{ai_title}}")
+ db.session.add_all([t_tag, t_folder, t_user])
+ db.session.commit()
+ tag = Tag(name=f"{name}-tag", user_id=user.id)
+ folder = Folder(name=f"{name}-folder", user_id=user.id)
+ db.session.add_all([tag, folder])
+ db.session.commit()
+ rec = Recording(user_id=user.id, title=f"Recording - {name}.wav", status="COMPLETED",
+ original_filename=f"{name}.wav", transcription=TRANSCRIPT,
+ meeting_date=datetime(2026, 10, 1, 6, 13))
+ db.session.add(rec)
+ db.session.commit()
+ ids = dict(user=user.id, rec=rec.id, tag=tag.id, folder=folder.id,
+ t_tag=t_tag.id, t_folder=t_folder.id, t_user=t_user.id)
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ RecordingTag.query.filter_by(recording_id=ids["rec"]).delete()
+ for model, key in ((Recording, "rec"), (Tag, "tag"), (Folder, "folder")):
+ obj = db.session.get(model, ids[key])
+ if obj is not None:
+ db.session.delete(obj)
+ db.session.commit()
+ u = db.session.get(User, ids["user"])
+ if u is not None:
+ u.default_naming_template_id = None
+ db.session.commit()
+ for key in ("t_tag", "t_folder", "t_user"):
+ obj = db.session.get(NamingTemplate, ids[key])
+ if obj is not None:
+ db.session.delete(obj)
+ db.session.delete(db.session.get(User, ids["user"]))
+ db.session.commit()
+
+
+def _setup(ids, tag=False, folder=False, user=False):
+ rec = db.session.get(Recording, ids["rec"])
+ if tag:
+ db.session.get(Tag, ids["tag"]).naming_template_id = ids["t_tag"]
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=ids["tag"], order=0))
+ if folder:
+ db.session.get(Folder, ids["folder"]).naming_template_id = ids["t_folder"]
+ rec.folder_id = ids["folder"]
+ if user:
+ db.session.get(User, ids["user"]).default_naming_template_id = ids["t_user"]
+ db.session.commit()
+ return db.session.get(Recording, ids["rec"])
+
+
+# ------------------------------------------------------------- resolution order
+
[email protected]("levels,expected", [
+ (dict(tag=True, folder=True, user=True), "tag"),
+ (dict(folder=True, user=True), "folder"),
+ (dict(user=True), "user"),
+ (dict(), None),
+])
+def test_naming_template_order_is_tag_then_folder_then_user(world, levels, expected):
+ with app.app_context():
+ rec = _setup(world, **levels)
+ _, source = resolve_naming_template(rec)
+ assert source == expected
+
+
+def test_folder_template_is_used_for_the_title(world):
+ with app.app_context():
+ rec = _setup(world, folder=True)
+ with patch.object(processing, "_generate_ai_title", return_value="Launch moved"), \
+ patch.object(processing, "client", object()):
+ assert compute_title(rec) == "FOLDER Launch moved"
+
+
+def test_template_without_ai_title_makes_no_llm_call(world):
+ with app.app_context():
+ rec = _setup(world)
+ t = db.session.get(NamingTemplate, world["t_user"])
+ t.template = "{{date}} call"
+ db.session.get(User, world["user"]).default_naming_template_id = t.id
+ db.session.commit()
+ rec = db.session.get(Recording, world["rec"])
+ with patch.object(processing, "_generate_ai_title", side_effect=AssertionError("LLM called")), \
+ patch.object(processing, "client", None):
+ assert compute_title(rec) == "2026-10-01 call"
+
+
+def test_no_template_and_no_llm_falls_back_to_the_filename(world):
+ with app.app_context():
+ rec = _setup(world)
+ with patch.object(processing, "client", None):
+ assert compute_title(rec) == os.path.splitext(rec.original_filename)[0]
+
+
+# ------------------------------------------------------ regenerate == pipeline
+
+def _regenerate(ids):
+ with app.app_context():
+ app.test_client_class = _Client
+ c = app.test_client()
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(ids["user"])
+ with patch.object(processing, "_generate_ai_title", return_value="Launch moved"), \
+ patch("src.api.recordings.client", object()), \
+ patch.object(processing, "client", object()), \
+ patch("src.api.recordings.export_recording") as exp:
+ resp = c.post(f"/recording/{ids['rec']}/regenerate_title")
+ return resp, exp
+
+
+def test_regenerate_applies_the_tag_template(world):
+ with app.app_context():
+ _setup(world, tag=True, user=True)
+ resp, exp = _regenerate(world)
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ assert resp.get_json()["title"] == "TAG Launch moved"
+ exp.assert_called_once_with(world["rec"])
+
+
+def test_regenerate_with_a_template_only_title_needs_no_llm(world):
+ with app.app_context():
+ _setup(world, user=True)
+ db.session.get(NamingTemplate, world["t_user"]).template = "{{date}} call"
+ db.session.commit()
+ app.test_client_class = _Client
+ c = app.test_client()
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(world["user"])
+ with patch("src.api.recordings.client", None), patch.object(processing, "client", None), \
+ patch("src.api.recordings.export_recording"):
+ resp = c.post(f"/recording/{world['rec']}/regenerate_title")
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ assert resp.get_json()["title"] == "2026-10-01 call"
+
+
+def test_background_task_and_regenerate_give_the_same_title(world):
+ with app.app_context():
+ _setup(world, folder=True, user=True)
+ with patch.object(processing, "_generate_ai_title", return_value="Launch moved"), \
+ patch.object(processing, "client", object()):
+ processing.generate_title_task(app.app_context(), world["rec"], will_auto_summarize=True)
+ task_title = db.session.get(Recording, world["rec"]).title
+ resp, _ = _regenerate(world)
+ assert task_title == "FOLDER Launch moved"
+ assert resp.get_json()["title"] == task_title