Skip to content

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

Python

Substitute mustache-style variables in resolved summary prompts and accept sanitized prompt_variables on upload

Murtaza Nasir162e1a1ce15e
diff --git a/src/api/recordings.py b/src/api/recordings.py
index c14eab2c..19571d4e 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2258,6 +2258,22 @@ def upload_file():
initial_prompt = request.form.get('initial_prompt', '').strip() or None
transcription_model = request.form.get('transcription_model', '').strip() or None
+ # Per-recording prompt-template variables. Sent as a JSON string from
+ # the upload form so multiple values fit in a single form field. The
+ # sanitiser enforces identifier-shaped keys and per-value / total
+ # size caps so an arbitrary JSON blob cannot bloat the column.
+ from src.utils.prompt_variables import sanitize_variable_values
+ prompt_variables = None
+ raw_prompt_variables = request.form.get('prompt_variables')
+ if raw_prompt_variables:
+ try:
+ parsed_vars = json.loads(raw_prompt_variables)
+ prompt_variables = sanitize_variable_values(parsed_vars)
+ except (TypeError, ValueError):
+ current_app.logger.warning(
+ f"Could not parse prompt_variables form field as JSON: {raw_prompt_variables[:200]}"
+ )
+
# Convert to int if provided
if min_speakers:
try:
@@ -2375,7 +2391,8 @@ def upload_file():
notes=notes,
folder_id=selected_folder.id if selected_folder else None,
processing_source='upload', # Track that this was manually uploaded
- file_hash=file_hash
+ file_hash=file_hash,
+ prompt_variables=prompt_variables,
)
db.session.add(recording)
db.session.commit()
diff --git a/src/models/recording.py b/src/models/recording.py
index 2c2574af..6c4bd767 100644
--- a/src/models/recording.py
+++ b/src/models/recording.py
@@ -289,6 +289,7 @@ class Recording(db.Model):
'folder': self.folder.to_dict() if self.folder else None,
'tags': [tag.to_dict() for tag in visible_tags] if visible_tags else [],
'events': [event.to_dict() for event in self.events] if self.events else [],
+ 'prompt_variables': self.prompt_variables or {},
'duplicate_info': self.get_duplicate_info(),
'shared_with_count': shared_with_count,
'public_share_count': public_share_count
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index e353865e..e2d56ed1 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -541,6 +541,28 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_override
- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
current_app.logger.info(f"Using hardcoded default prompt for recording {recording_id}")
+ # Substitute {{variable}} placeholders in the resolved prompt with the
+ # values the user supplied at upload time (or via a later edit). This
+ # turns tag/folder prompts that contain `{{agenda}}` etc. into concrete
+ # instructions for this specific recording.
+ from src.utils.prompt_variables import (
+ extract_template_variables,
+ substitute_template_variables,
+ )
+ prompt_variables = recording.prompt_variables or {}
+ used_variables = extract_template_variables(summarization_instructions)
+ if used_variables:
+ missing = [v for v in used_variables if not prompt_variables.get(v)]
+ if missing:
+ current_app.logger.warning(
+ f"Recording {recording_id} prompt references {len(used_variables)} "
+ f"variable(s); {len(missing)} have no value: {missing}. "
+ f"Empty strings will be substituted."
+ )
+ summarization_instructions = substitute_template_variables(
+ summarization_instructions, prompt_variables
+ )
+
# 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
# or one-off context without rewriting their saved summary prompt.
diff --git a/src/utils/prompt_variables.py b/src/utils/prompt_variables.py
new file mode 100644
index 00000000..6850f7c7
--- /dev/null
+++ b/src/utils/prompt_variables.py
@@ -0,0 +1,130 @@
+"""
+Templated prompt variables.
+
+Authors of custom summarisation prompts (on tags, folders, users, or admin
+defaults) can embed `{{variable_name}}` placeholders. At upload time the user
+fills in values for whichever variables appear in the resolved prompt; the
+values are stored on the recording and substituted into the prompt at
+summarisation time.
+
+Variable naming follows simple identifier rules so the regex never
+accidentally matches natural prose: must start with a letter or underscore,
+followed by letters, digits, or underscores. Whitespace inside the braces is
+allowed (`{{ name }}`).
+"""
+
+import re
+
+# Match `{{ name }}` with optional whitespace, capture the bare identifier.
+_VARIABLE_PATTERN = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}")
+
+
+def extract_template_variables(text):
+ """
+ Return a list of unique variable names that appear in `text`, in the
+ order of their first occurrence. An empty or non-string input returns [].
+ """
+ if not text or not isinstance(text, str):
+ return []
+ seen = []
+ for match in _VARIABLE_PATTERN.finditer(text):
+ name = match.group(1)
+ if name not in seen:
+ seen.append(name)
+ return seen
+
+
+def substitute_template_variables(text, values):
+ """
+ Replace every `{{name}}` placeholder in `text` with `values.get(name, '')`.
+ Whitespace inside the braces is tolerated. Returns the substituted string.
+ A missing or non-string `text` is returned unchanged. A non-dict `values`
+ is treated as empty.
+ """
+ if not text or not isinstance(text, str):
+ return text
+ if not isinstance(values, dict):
+ values = {}
+
+ def _replace(match):
+ name = match.group(1)
+ replacement = values.get(name, '')
+ if replacement is None:
+ return ''
+ return str(replacement)
+
+ return _VARIABLE_PATTERN.sub(_replace, text)
+
+
+def infer_label(variable_name):
+ """
+ Derive a human-readable label from a variable name. `meeting_date` becomes
+ "Meeting date"; `agenda` becomes "Agenda". Used by the upload form so the
+ user does not have to declare labels separately.
+ """
+ if not variable_name:
+ return ''
+ cleaned = variable_name.replace('_', ' ').strip()
+ if not cleaned:
+ return ''
+ return cleaned[0].upper() + cleaned[1:]
+
+
+# Hard limits enforced on user-supplied variable maps so a malicious or buggy
+# client cannot blow up storage or downstream LLM calls.
+MAX_VARIABLES = 50
+MAX_VALUE_CHARS = 8000
+MAX_TOTAL_CHARS = 32000
+
+# Keys must match the same identifier shape as the regex above so we never
+# store names that the substitution pass cannot match anyway.
+_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+
+def sanitize_variable_values(raw):
+ """
+ Coerce a user-supplied variable map into a safe canonical form.
+
+ - Returns a plain ``{str: str}`` dict, or ``None`` if the input is empty
+ or unusable.
+ - Drops keys that are not valid identifiers (the substitution regex would
+ not match them anyway).
+ - Drops empty / whitespace-only values so the column stays ``None`` when
+ nothing was supplied.
+ - Caps the number of entries, each value's length, and the total size to
+ prevent abuse of an unbounded JSON column.
+ - Strips control characters except ``\\n``, ``\\r``, and ``\\t``.
+
+ The function is deliberately defensive: bad input becomes empty rather
+ than raising, so callers can use it as the only validation step.
+ """
+ if not isinstance(raw, dict):
+ return None
+
+ cleaned = {}
+ total = 0
+ for key, value in raw.items():
+ if len(cleaned) >= MAX_VARIABLES:
+ break
+ if not isinstance(key, str) or not _KEY_PATTERN.match(key):
+ continue
+ if value is None:
+ continue
+ text = str(value)
+ # Strip C0 control characters except common whitespace; this stops
+ # null bytes and other oddities from landing in the prompt.
+ text = ''.join(
+ ch for ch in text
+ if ch in ('\n', '\r', '\t') or ord(ch) >= 0x20
+ )
+ text = text.strip()
+ if not text:
+ continue
+ if len(text) > MAX_VALUE_CHARS:
+ text = text[:MAX_VALUE_CHARS]
+ if total + len(text) > MAX_TOTAL_CHARS:
+ break
+ cleaned[key] = text
+ total += len(text)
+
+ return cleaned or None
diff --git a/tests/test_prompt_variables.py b/tests/test_prompt_variables.py
new file mode 100644
index 00000000..4f4d84d3
--- /dev/null
+++ b/tests/test_prompt_variables.py
@@ -0,0 +1,177 @@
+"""
+Tests for the prompt-template variable utility.
+
+These cover the public surface: extract, substitute, infer_label, and the
+sanitise step that gates user input before it lands in the database.
+"""
+
+import pytest
+
+from src.utils.prompt_variables import (
+ extract_template_variables,
+ substitute_template_variables,
+ infer_label,
+ sanitize_variable_values,
+ MAX_VARIABLES,
+ MAX_VALUE_CHARS,
+ MAX_TOTAL_CHARS,
+)
+
+
+# ---------------------------------------------------------------------------
+# extract_template_variables
+# ---------------------------------------------------------------------------
+
+def test_extract_returns_unique_in_first_seen_order():
+ assert extract_template_variables('Hi {{name}}, {{agenda}} and again {{name}}') == ['name', 'agenda']
+
+
+def test_extract_tolerates_whitespace_inside_braces():
+ assert extract_template_variables('{{ name }} and {{ agenda }}') == ['name', 'agenda']
+
+
+def test_extract_ignores_text_without_placeholders():
+ assert extract_template_variables('plain text without variables') == []
+
+
+def test_extract_handles_empty_input():
+ assert extract_template_variables('') == []
+ assert extract_template_variables(None) == []
+ assert extract_template_variables(123) == []
+
+
+def test_extract_does_not_match_single_braces():
+ assert extract_template_variables('this {is not} a placeholder') == []
+
+
+def test_extract_rejects_invalid_identifier_starts():
+ # Numeric-leading identifiers must not match
+ assert extract_template_variables('hi {{1bad}}') == []
+
+
+# ---------------------------------------------------------------------------
+# substitute_template_variables
+# ---------------------------------------------------------------------------
+
+def test_substitute_replaces_known_keys():
+ assert substitute_template_variables('Hi {{name}}', {'name': 'Anna'}) == 'Hi Anna'
+
+
+def test_substitute_uses_empty_string_for_missing_keys():
+ assert substitute_template_variables('Hi {{name}}', {}) == 'Hi '
+
+
+def test_substitute_coerces_non_string_values():
+ assert substitute_template_variables('count {{n}}', {'n': 42}) == 'count 42'
+
+
+def test_substitute_passes_html_unchanged_to_caller():
+ # The substitution layer is text-only; XSS sanitisation is a downstream
+ # concern of the summary renderer, not the variable substituter.
+ raw = substitute_template_variables('hi {{x}}', {'x': '<script>alert(1)</script>'})
+ assert raw == 'hi <script>alert(1)</script>'
+
+
+def test_substitute_no_template_engine_invocation():
+ # Even a value that looks like Python format-string mischief is treated as
+ # plain text on the value side.
+ out = substitute_template_variables('A {{x}} B', {'x': '{0.__class__.__bases__}'})
+ assert out == 'A {0.__class__.__bases__} B'
+
+
+def test_substitute_handles_empty_input():
+ assert substitute_template_variables('', {'x': 'y'}) == ''
+ assert substitute_template_variables(None, {'x': 'y'}) is None
+
+
+def test_substitute_with_non_dict_values_treated_as_empty():
+ assert substitute_template_variables('Hi {{name}}', None) == 'Hi '
+ assert substitute_template_variables('Hi {{name}}', 'not-a-dict') == 'Hi '
+
+
+# ---------------------------------------------------------------------------
+# infer_label
+# ---------------------------------------------------------------------------
+
+def test_infer_label_basic_cases():
+ assert infer_label('agenda') == 'Agenda'
+ assert infer_label('meeting_date') == 'Meeting date'
+ assert infer_label('whoIsHere') == 'WhoIsHere'
+
+
+def test_infer_label_handles_empty():
+ assert infer_label('') == ''
+ assert infer_label(None) == ''
+
+
+# ---------------------------------------------------------------------------
+# sanitize_variable_values
+# ---------------------------------------------------------------------------
+
+def test_sanitize_strips_invalid_keys():
+ cleaned = sanitize_variable_values({
+ 'good': 'value',
+ '1bad': 'starts with digit',
+ 'has space': 'no spaces',
+ 'with-dash': 'no dashes',
+ })
+ assert cleaned == {'good': 'value'}
+
+
+def test_sanitize_drops_empty_and_whitespace_values():
+ assert sanitize_variable_values({'a': '', 'b': ' ', 'c': 'real'}) == {'c': 'real'}
+
+
+def test_sanitize_returns_none_for_empty_result():
+ assert sanitize_variable_values({}) is None
+ assert sanitize_variable_values({'a': ''}) is None
+
+
+def test_sanitize_returns_none_for_non_dict_input():
+ assert sanitize_variable_values(['a', 'b']) is None
+ assert sanitize_variable_values('hello') is None
+ assert sanitize_variable_values(None) is None
+
+
+def test_sanitize_strips_control_characters():
+ cleaned = sanitize_variable_values({'k': 'hello\x00\x01\x02world'})
+ assert cleaned == {'k': 'helloworld'}
+
+
+def test_sanitize_preserves_common_whitespace():
+ cleaned = sanitize_variable_values({'k': 'line1\nline2\ttabbed'})
+ assert cleaned == {'k': 'line1\nline2\ttabbed'}
+
+
+def test_sanitize_caps_variable_count():
+ raw = {f'k{i}': 'v' for i in range(MAX_VARIABLES + 20)}
+ cleaned = sanitize_variable_values(raw)
+ assert len(cleaned) == MAX_VARIABLES
+
+
+def test_sanitize_caps_value_length():
+ cleaned = sanitize_variable_values({'k': 'A' * (MAX_VALUE_CHARS + 1000)})
+ assert len(cleaned['k']) == MAX_VALUE_CHARS
+
+
+def test_sanitize_caps_total_size():
+ big_value = 'A' * 4000
+ raw = {f'k{i}': big_value for i in range(20)}
+ cleaned = sanitize_variable_values(raw)
+ total = sum(len(v) for v in cleaned.values())
+ assert total <= MAX_TOTAL_CHARS
+
+
+def test_sanitize_coerces_non_string_values():
+ cleaned = sanitize_variable_values({'count': 42, 'flag': True})
+ assert cleaned == {'count': '42', 'flag': 'True'}
+
+
+def test_sanitize_dunder_keys_are_safe_lookups():
+ # __class__ is allowed by the identifier regex but the substitution path
+ # is a plain dict lookup with no code execution. Verify the value is
+ # returned verbatim.
+ cleaned = sanitize_variable_values({'__class__': 'value'})
+ assert cleaned == {'__class__': 'value'}
+ out = substitute_template_variables('a {{__class__}} b', cleaned)
+ assert out == 'a value b'