Skip to content

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

Python

One summary-prompt resolver; every processing step uses the owner's view of tags (#412 audit S3, S4, S5): an editor's personal tag no longer shapes a shared recording's summary, transcription settings or naming template

Murtaza Nasird2d36910d0f5
diff --git a/src/services/titling.py b/src/services/titling.py
index f3685737..e50e4a72 100644
--- a/src/services/titling.py
+++ b/src/services/titling.py
@@ -6,7 +6,7 @@ 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
+1. Naming template: the first tag (as the owner sees them) 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.
@@ -27,7 +27,9 @@ def resolve_naming_template(recording):
Returns (template, source) where source is 'tag', 'folder', 'user' or None.
"""
- for tag in recording.tags:
+ # The owner's view of the tags, as for prompts and transcription settings (#412 S3).
+ tags = recording.get_visible_tags(recording.owner) if recording.owner else []
+ for tag in tags or []:
if tag.naming_template_id and tag.naming_template:
return tag.naming_template, 'tag'
if recording.folder_id:
diff --git a/src/services/transcription_defaults.py b/src/services/transcription_defaults.py
index 634f0802..762d8531 100644
--- a/src/services/transcription_defaults.py
+++ b/src/services/transcription_defaults.py
@@ -119,12 +119,15 @@ def resolve_transcription_params(recording=None, overrides=None, *, tags=None, f
# Derive context from the recording when given; otherwise the caller (upload,
# which resolves before the row exists) supplies tags/folder/owner directly.
if recording is not None:
+ if owner is None:
+ owner = recording.owner
if tags is None:
- tags = recording.tags
+ # The owner's view of the tags, as for prompts and naming templates
+ # (#412 S3): another user's personal tag on a shared recording does
+ # not change how it is transcribed.
+ tags = recording.get_visible_tags(owner) if owner else []
if folder is None:
folder = recording.folder
- if owner is None:
- owner = recording.owner
tags = list(tags) if tags else []
def _override_str(key):
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 75ce9861..9b7a8c6a 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -458,6 +458,38 @@ def _user_title_instructions(user):
return DEFAULT_TITLE_PROMPT, 'default'
+def resolve_summary_instructions(recording):
+ """Instructions for a recording's summary, and which level supplied them.
+
+ tag > folder > user > admin default > shipped default (#412 audit S5).
+ Every tag the owner can see that carries a prompt contributes, in the order
+ the tags were added. The owner's view is used for every processing step,
+ so a summary does not depend on which editor asked for it (S3, S4).
+
+ Returns (instructions, source); source is 'tag', 'folder', 'user', 'admin'
+ or 'default'.
+ """
+ owner = recording.owner
+ if owner:
+ tag_prompts = [
+ tag.custom_prompt.strip()
+ for tag in (recording.get_visible_tags(owner) or [])
+ if tag.custom_prompt and tag.custom_prompt.strip()
+ ]
+ if tag_prompts:
+ return "\n\n".join(tag_prompts), 'tag'
+ folder = recording.folder
+ if folder and folder.custom_prompt and folder.custom_prompt.strip():
+ return folder.custom_prompt.strip(), 'folder'
+ if owner and owner.summary_prompt and owner.summary_prompt.strip():
+ return owner.summary_prompt, 'user'
+ admin_default = SystemSetting.get_setting('admin_default_summary_prompt', None)
+ if admin_default:
+ return admin_default, 'admin'
+ from src.config.prompts import DEFAULT_SUMMARY_PROMPT
+ return DEFAULT_SUMMARY_PROMPT, 'default'
+
+
def resolve_title_instructions(recording, viewer=None):
"""Instructions for a recording's AI title, and which level supplied them.
@@ -660,70 +692,9 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_override
emit_summary_result(db.session.get(Recording, recording_id), ok=True)
return
- # Get user preferences and tag custom prompts
- user_summary_prompt = None
- user_output_language = None
- tag_custom_prompt = None
-
- # Determine which user's perspective to use for tag visibility
- # If user_id is provided (e.g., from reprocess), use that user
- # Otherwise default to the recording owner
- viewer_user = None
- if user_id:
- viewer_user = db.session.get(User, user_id)
- if viewer_user:
- current_app.logger.info(f"Using user {viewer_user.username} (ID: {user_id}) for tag visibility filtering")
- else:
- current_app.logger.warning(f"User ID {user_id} not found, falling back to recording owner")
- viewer_user = recording.owner
- else:
- viewer_user = recording.owner
- if viewer_user:
- current_app.logger.info(f"Using recording owner {viewer_user.username} for tag visibility filtering")
-
- # Collect custom prompts from tags visible to the viewer user
- tag_custom_prompts = []
- if viewer_user:
- visible_tags = recording.get_visible_tags(viewer_user)
- if visible_tags:
- current_app.logger.info(f"Found {len(visible_tags)} visible tags for user {viewer_user.username} on recording {recording_id}")
- # Tags are ordered by the order they were added to this recording
- for tag in visible_tags:
- if tag.custom_prompt and tag.custom_prompt.strip():
- tag_custom_prompts.append({
- 'name': tag.name,
- 'prompt': tag.custom_prompt.strip()
- })
- current_app.logger.info(f"Found custom prompt from tag '{tag.name}' for recording {recording_id}")
- else:
- current_app.logger.warning(f"No viewer user available for tag filtering on recording {recording_id}")
-
- # Create merged prompt if we have multiple tag prompts
- if tag_custom_prompts:
- if len(tag_custom_prompts) == 1:
- tag_custom_prompt = tag_custom_prompts[0]['prompt']
- current_app.logger.info(f"Using single custom prompt from tag '{tag_custom_prompts[0]['name']}' for recording {recording_id}")
- else:
- # Merge multiple prompts seamlessly as unified instructions
- merged_parts = []
- for tag_prompt in tag_custom_prompts:
- merged_parts.append(tag_prompt['prompt'])
- tag_custom_prompt = "\n\n".join(merged_parts)
- tag_names = [tp['name'] for tp in tag_custom_prompts]
- current_app.logger.info(f"Combined custom prompts from {len(tag_custom_prompts)} tags in order added ({', '.join(tag_names)}) for recording {recording_id}")
- else:
- tag_custom_prompt = None
-
- # Get folder custom prompt (if recording has a folder)
- # Folder prompt has lower priority than tag prompts (tags override folders)
- folder_custom_prompt = None
- if recording.folder and recording.folder.custom_prompt and recording.folder.custom_prompt.strip():
- folder_custom_prompt = recording.folder.custom_prompt.strip()
- current_app.logger.info(f"Found custom prompt from folder '{recording.folder.name}' for recording {recording_id}")
-
- if recording.owner:
- user_summary_prompt = recording.owner.summary_prompt
- user_output_language = recording.owner.output_language
+ # Prompt levels come from resolve_summary_instructions (owner's view of
+ # tags, #412). user_id is kept for the job interface and logging.
+ user_output_language = recording.owner.output_language if recording.owner else None
# 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).
@@ -745,33 +716,15 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_override
language_directive = f"IMPORTANT: You MUST provide the summary in {user_output_language}. The entire response must be in {user_output_language}." if user_output_language else ""
- # Determine which summarization instructions to use.
- # Priority order: custom_prompt_override > tag custom prompt > folder custom prompt > user summary prompt > admin default prompt > hardcoded fallback.
- # When custom_prompt_append is True the override is appended to the resolved default rather than replacing it.
- summarization_instructions = ""
+ # Instructions: a replacing override, else the resolved level
+ # (tag > folder > user > admin > default). An appended override is
+ # added below.
if custom_prompt_override and not custom_prompt_append:
current_app.logger.info(f"Using custom prompt override for recording {recording_id} (length: {len(custom_prompt_override)})")
summarization_instructions = custom_prompt_override
- elif tag_custom_prompt:
- current_app.logger.info(f"Using tag custom prompt for recording {recording_id}")
- summarization_instructions = tag_custom_prompt
- elif folder_custom_prompt:
- current_app.logger.info(f"Using folder custom prompt for recording {recording_id}")
- summarization_instructions = folder_custom_prompt
- elif user_summary_prompt:
- current_app.logger.info(f"Using user custom prompt for recording {recording_id}")
- summarization_instructions = user_summary_prompt
else:
- # Get admin default prompt from system settings
- admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
- if admin_default_prompt:
- current_app.logger.info(f"Using admin default prompt for recording {recording_id}")
- summarization_instructions = admin_default_prompt
- else:
- # Fallback to the shipped default if admin hasn't set one.
- from src.config.prompts import DEFAULT_SUMMARY_PROMPT
- summarization_instructions = DEFAULT_SUMMARY_PROMPT
- current_app.logger.info(f"Using hardcoded default prompt for recording {recording_id}")
+ summarization_instructions, _source = resolve_summary_instructions(recording)
+ current_app.logger.info(f"Using {_source} summary prompt for recording {recording_id}")
# Append the user's per-run additions on top of the resolved default
# (issue / discussion #253). This is how a user supplies a meeting agenda
@@ -828,9 +781,9 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_override
if recording.folder:
context_parts.append(f"Folder: {recording.folder.name}")
- # Add selected tags information (only visible tags)
- if viewer_user:
- visible_tags = recording.get_visible_tags(viewer_user)
+ # Add selected tags information (the owner's view of the tags, #412)
+ if recording.owner:
+ visible_tags = recording.get_visible_tags(recording.owner)
if visible_tags:
tag_names = [tag.name for tag in visible_tags]
context_parts.append(f"Tags applied to this transcript by the user: {', '.join(tag_names)}")
diff --git a/tests/test_prompt_resolution.py b/tests/test_prompt_resolution.py
new file mode 100644
index 00000000..55846158
--- /dev/null
+++ b/tests/test_prompt_resolution.py
@@ -0,0 +1,99 @@
+"""Summary prompt resolution and the owner's view of tags (#412 audit S3, S4, S5).
+
+S5: the summary prompt order (tag > folder > user > admin > default) lives in
+resolve_summary_instructions, next to the title resolver.
+S3/S4: every processing step uses the tags the owner can see. Before, a
+summary reprocessed by an editor used the editor's personal tag prompts, and
+transcription settings and naming templates used every tag on the recording,
+including another user's personal tag.
+
+SHARED-DB: users, tags and the recording are removed afterwards.
+"""
+
+import os
+import sys
+import uuid
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+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, Recording, RecordingTag, SystemSetting, Tag, User
+import src.tasks.processing as proc
+from src.services.transcription_defaults import resolve_transcription_params
+
+
+def world():
+ with app.app_context():
+ s = uuid.uuid4().hex[:8]
+ owner = User(username=f"own_{s}", email=f"own_{s}@local.test", password="x",
+ summary_prompt="OWNER PROMPT", transcription_language="en")
+ editor = User(username=f"ed_{s}", email=f"ed_{s}@local.test", password="x")
+ db.session.add_all([owner, editor])
+ db.session.commit()
+ own_tag = Tag(name=f"own-{s}", user_id=owner.id, custom_prompt="OWNER TAG PROMPT")
+ ed_tag = Tag(name=f"ed-{s}", user_id=editor.id, custom_prompt="EDITOR TAG PROMPT", default_language="fr")
+ folder = Folder(name=f"f-{s}", user_id=owner.id, custom_prompt="FOLDER PROMPT")
+ db.session.add_all([own_tag, ed_tag, folder])
+ db.session.commit()
+ r = Recording(user_id=owner.id, title="Sync", original_filename="s.wav", status="COMPLETED",
+ transcription="Speaker 1: " + "we agreed on the plan. " * 5)
+ db.session.add(r)
+ db.session.commit()
+ ids = dict(owner=owner.id, editor=editor.id, own_tag=own_tag.id, ed_tag=ed_tag.id,
+ folder=folder.id, rec=r.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, "own_tag"), (Tag, "ed_tag"), (Folder, "folder"),
+ (User, "editor"), (User, "owner")):
+ obj = db.session.get(model, ids[key])
+ if obj is not None:
+ db.session.delete(obj)
+ db.session.commit()
+
+
+def _attach(ids, *tag_keys, folder=False):
+ for order, key in enumerate(tag_keys):
+ db.session.add(RecordingTag(recording_id=ids["rec"], tag_id=ids[key], order=order))
+ if folder:
+ db.session.get(Recording, ids["rec"]).folder_id = ids["folder"]
+ db.session.commit()
+ return db.session.get(Recording, ids["rec"])
+
+
[email protected]("tags,folder,expected", [
+ (("own_tag",), True, ("OWNER TAG PROMPT", "tag")),
+ ((), True, ("FOLDER PROMPT", "folder")),
+ ((), False, ("OWNER PROMPT", "user")),
+])
+def test_summary_prompt_order(world, tags, folder, expected):
+ with app.app_context():
+ rec = _attach(world, *tags, folder=folder)
+ assert proc.resolve_summary_instructions(rec) == expected
+
+
+def test_an_editors_personal_tag_does_not_shape_the_summary(world):
+ with app.app_context():
+ _attach(world, "ed_tag")
+ seen = []
+
+ def fake(messages, **kw):
+ seen.append("\n".join(m["content"] for m in messages))
+ return MagicMock(choices=[MagicMock(message=MagicMock(content="## Summary", reasoning=None))])
+
+ with patch.object(proc, "client", MagicMock()), patch.object(proc, "call_llm_completion", side_effect=fake), \
+ patch.object(proc, "finish_processing"):
+ proc.generate_summary_only_task(app.app_context(), world["rec"], user_id=world["editor"])
+ assert "EDITOR TAG PROMPT" not in seen[0]
+ assert "OWNER PROMPT" in seen[0]
+
+
+def test_an_editors_personal_tag_does_not_change_transcription_settings(world):
+ with app.app_context():
+ rec = _attach(world, "ed_tag")
+ assert resolve_transcription_params(rec)["language"] == "en"