Skip to content

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

Python

Fix PWA shared files getting no AI title; unify title logic into shared helper

Murtaza Nasir482614c7285c
diff --git a/src/api/recordings.py b/src/api/recordings.py
index cc00422d..e0b7d572 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -73,6 +73,7 @@ def _resolve_transcription_model(value):
return default or None
from src.tasks.processing import format_transcription_for_llm
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
from src.services.speaker_embedding_matcher import update_speaker_embedding
from src.services.speaker_snippets import create_speaker_snippets
@@ -2131,8 +2132,12 @@ def share_target():
# Build the recording row. Tags and folder cannot be inferred from a
# share sheet, so we leave them empty; the user can adjust from the
# recording detail view. Title comes from the share sheet's title field
- # if present, else from the filename stem.
- share_title = (request.form.get('title') or os.path.splitext(safe_filename)[0]).strip() or 'Shared recording'
+ # if present; otherwise we use the SAME placeholder a normal upload gets
+ # (resolve_upload_title) so the AI title task recognises it and generates
+ # a title — previously the filename stem was used, which the title task
+ # treated as a user-chosen title and skipped, leaving shared files untitled.
+ from src.utils.titles import resolve_upload_title
+ share_title = resolve_upload_title(request.form.get('title'), original_filename)
notes_parts = []
for key in ('title', 'text', 'url'):
@@ -2613,7 +2618,7 @@ def upload_file():
recording = Recording(
audio_path=filepath,
original_filename=original_filename,
- title=user_title.strip() if user_title and user_title.strip() else f"Recording - {original_filename}",
+ title=resolve_upload_title(user_title, original_filename),
file_size=final_file_size,
status='PENDING',
meeting_date=meeting_date,
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 0eb42516..f4bbb5ae 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -244,12 +244,12 @@ def generate_title_task(app_context, recording_id, will_auto_summarize=False):
current_app.logger.error(f"Error: Recording {recording_id} not found for title generation.")
return
- # Skip title generation if user provided a non-placeholder title
- placeholder_patterns = [
- f"Recording - {recording.original_filename}",
- f"Auto-processed - {recording.original_filename}",
- ]
- if recording.title and recording.title not in placeholder_patterns:
+ # Skip title generation if the user provided a non-placeholder title.
+ # is_placeholder_title is the shared source of truth (also used by the
+ # upload + share-target routes) so every entry point's title is
+ # recognised here and gets an AI title unless the user chose one.
+ from src.utils.titles import is_placeholder_title
+ if not is_placeholder_title(recording.title, recording.original_filename):
current_app.logger.info(f"Recording {recording_id} has user-provided title '{recording.title}', skipping AI title generation")
if not will_auto_summarize:
recording.status = 'COMPLETED'
diff --git a/src/utils/titles.py b/src/utils/titles.py
new file mode 100644
index 00000000..1c7dc069
--- /dev/null
+++ b/src/utils/titles.py
@@ -0,0 +1,51 @@
+"""Helpers for recording titles at upload/share time.
+
+These are the single source of truth for two related decisions that were
+previously duplicated inline across the upload route, the PWA share-target
+route, and the AI-title-generation task:
+
+1. What title a freshly-created recording should get (`resolve_upload_title`).
+2. Whether a title is an auto-generated placeholder that the AI title
+ generator is allowed to overwrite (`is_placeholder_title`).
+
+Keeping these together guarantees every entry point (drag-drop upload, share
+target, black-hole auto-import) produces a title that the title task
+recognises, so shared/auto-imported files get an AI title exactly like a
+normal upload instead of being silently skipped.
+"""
+
+
+def placeholder_title(original_filename):
+ """The default placeholder title for an upload with no user-supplied title."""
+ return f"Recording - {original_filename}"
+
+
+def placeholder_titles(original_filename):
+ """All placeholder titles the AI title generator may overwrite."""
+ return (
+ f"Recording - {original_filename}",
+ f"Auto-processed - {original_filename}",
+ )
+
+
+def resolve_upload_title(user_title, original_filename):
+ """The title a newly-uploaded or shared recording should be created with.
+
+ A non-empty user-supplied title is used as-is (and the AI title task will
+ leave it alone). Otherwise we return a placeholder the title task
+ recognises, so AI title generation runs.
+ """
+ if user_title and user_title.strip():
+ return user_title.strip()
+ return placeholder_title(original_filename)
+
+
+def is_placeholder_title(title, original_filename):
+ """True if `title` is empty or an auto-generated placeholder.
+
+ The AI title generator overwrites placeholders; a non-placeholder title is
+ treated as user-chosen and left untouched.
+ """
+ if not title:
+ return True
+ return title in placeholder_titles(original_filename)
diff --git a/tests/test_share_target.py b/tests/test_share_target.py
index cd5bd814..f8838d69 100644
--- a/tests/test_share_target.py
+++ b/tests/test_share_target.py
@@ -118,6 +118,47 @@ def test_share_target_creates_recording_and_enqueues_job():
db.session.commit()
+def test_share_target_without_title_gets_ai_titleable_placeholder():
+ """Regression: a file shared WITHOUT an explicit title must get the same
+ placeholder ('Recording - <filename>') a normal upload gets, so the AI
+ title task recognises it and generates a title. Previously the share
+ target used the filename STEM, which the title task treated as a
+ user-chosen title and skipped, leaving shared files untitled."""
+ from src.utils.titles import is_placeholder_title
+
+ with app.app_context():
+ user = _setup_user("share_notitle")
+ client = app.test_client()
+ _login(client, user)
+
+ with patch("src.services.job_queue.job_queue.enqueue", return_value=1), \
+ patch("src.api.recordings.os.path.getsize", return_value=12345):
+ resp = client.post(
+ "/share-target",
+ data={
+ # No "title" field — the common case from a share sheet.
+ "shared_audio": (io.BytesIO(b"fake-audio-bytes"), "voice_memo_001.webm"),
+ },
+ content_type="multipart/form-data",
+ follow_redirects=False,
+ )
+ assert resp.status_code == 302, resp.data
+
+ rec = Recording.query.filter_by(user_id=user.id).one()
+ # The title must be the recognised placeholder, NOT the filename stem.
+ assert rec.title == "Recording - voice_memo_001.webm", rec.title
+ assert is_placeholder_title(rec.title, rec.original_filename) is True
+
+ if rec.audio_path and os.path.exists(rec.audio_path):
+ try:
+ os.remove(rec.audio_path)
+ except OSError:
+ pass
+ db.session.delete(rec)
+ db.session.delete(user)
+ db.session.commit()
+
+
def test_share_target_requires_login():
"""Unauthenticated POSTs hit @login_required and redirect to /login."""
with app.app_context():
diff --git a/tests/test_upload_title_and_date.py b/tests/test_upload_title_and_date.py
index 681a5e16..3b20a31b 100644
--- a/tests/test_upload_title_and_date.py
+++ b/tests/test_upload_title_and_date.py
@@ -11,25 +11,26 @@ from unittest.mock import MagicMock, patch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+# Real source helpers (single source of truth for upload/share-target/title-task).
+from src.utils.titles import resolve_upload_title, is_placeholder_title
-def test_placeholder_pattern_detection():
- """Placeholder titles should be detected, user titles should not."""
- original_filename = "interview.mp3"
- placeholder_patterns = [
- f"Recording - {original_filename}",
- f"Auto-processed - {original_filename}",
- ]
- # Placeholders match
- assert "Recording - interview.mp3" in placeholder_patterns
- assert "Auto-processed - interview.mp3" in placeholder_patterns
+def test_placeholder_pattern_detection():
+ """is_placeholder_title (the real helper the title task uses) detects
+ placeholders and empties, and treats user titles as non-placeholders."""
+ fn = "interview.mp3"
- # User titles don't match
- assert "My Custom Title" not in placeholder_patterns
- assert "Interview with John" not in placeholder_patterns
- assert "" not in placeholder_patterns
+ # Placeholders + empty/None are overwritable by the AI title generator
+ assert is_placeholder_title(f"Recording - {fn}", fn) is True
+ assert is_placeholder_title(f"Auto-processed - {fn}", fn) is True
+ assert is_placeholder_title("", fn) is True
+ assert is_placeholder_title(None, fn) is True
- print(" PASS: placeholder pattern detection")
+ # User titles are NOT placeholders -> AI title generation is skipped
+ assert is_placeholder_title("My Custom Title", fn) is False
+ assert is_placeholder_title("Interview with John", fn) is False
+ # A placeholder for a DIFFERENT filename must not match
+ assert is_placeholder_title("Recording - other.mp3", fn) is False
def test_meeting_date_iso_parsing():
@@ -63,25 +64,29 @@ def test_meeting_date_iso_parsing():
def test_user_title_applied():
- """User-provided title should be used instead of placeholder."""
- original_filename = "test.mp3"
-
- # With user title
- user_title = " My Custom Title "
- result = user_title.strip() if user_title and user_title.strip() else f"Recording - {original_filename}"
- assert result == "My Custom Title"
-
- # Empty string falls back to placeholder
- user_title = " "
- result = user_title.strip() if user_title and user_title.strip() else f"Recording - {original_filename}"
- assert result == f"Recording - {original_filename}"
-
- # None falls back to placeholder
- user_title = None
- result = user_title.strip() if user_title and user_title.strip() else f"Recording - {original_filename}"
- assert result == f"Recording - {original_filename}"
-
- print(" PASS: user title application logic")
+ """resolve_upload_title: a user title is used (trimmed); blank/None falls
+ back to the placeholder."""
+ fn = "test.mp3"
+ assert resolve_upload_title(" My Custom Title ", fn) == "My Custom Title"
+ assert resolve_upload_title(" ", fn) == f"Recording - {fn}"
+ assert resolve_upload_title(None, fn) == f"Recording - {fn}"
+
+
+def test_resolve_upload_title_produces_recognized_placeholder():
+ """THE invariant the share-target bug violated: when no user title is
+ given, resolve_upload_title must produce a title that is_placeholder_title
+ recognises — otherwise the AI title task skips generation and the
+ recording is left with a non-AI title (e.g. the filename stem). Every
+ entry point (upload, share-target) must satisfy this."""
+ for fn in ("interview.mp3", "voice memo 001.m4a", "clip.webm"):
+ # No user-supplied title -> placeholder -> AI generation runs
+ title = resolve_upload_title(None, fn)
+ assert is_placeholder_title(title, fn) is True, (
+ f"resolve_upload_title({fn!r}) returned {title!r}, which the title "
+ f"task would NOT treat as a placeholder -> no AI title (the share bug)"
+ )
+ # A real user title -> NOT a placeholder -> AI generation skipped
+ assert is_placeholder_title(resolve_upload_title("Chosen", fn), fn) is False
def test_meeting_date_priority():
@@ -149,7 +154,7 @@ def test_neither_title_nor_date():
user_meeting_date = None
# Title falls back to placeholder
- title = user_title.strip() if user_title and user_title.strip() else f"Recording - {original_filename}"
+ title = resolve_upload_title(user_title, original_filename)
assert title == "Recording - audio.mp3"
# meeting_date falls through to next priority
@@ -173,6 +178,7 @@ def main():
test_placeholder_pattern_detection,
test_meeting_date_iso_parsing,
test_user_title_applied,
+ test_resolve_upload_title_produces_recognized_placeholder,
test_meeting_date_priority,
test_summary_context_includes_metadata,
test_neither_title_nor_date,