Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions docs/IMPLEMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def normalize_vocabulary_entries(entries: list) -> list[VocabularyTerm]: ...
"""Accept VocabularyTerm, {"term", "language"} dicts and legacy str (language "").
Trim terms (no controls); language "" or normalize_language_code(). Casefold-deduplicate
by term across the whole list, first occurrence (and its language) wins. Cap 128 terms,
128 chars/term and 8,000 rendered chars for the whole list."""
128 chars/term and 8,000 chars of the rendered list for the whole list."""
def encode_vocabulary_entries(entries: list) -> str: ...
"""JSON array of objects: [{"term": "PySide6", "language": ""}, ...]."""
def decode_vocabulary_entries(value: object) -> list[VocabularyTerm]: ...
Expand Down Expand Up @@ -819,12 +819,18 @@ ruff format --check src/ tests/ .github/scripts/
loads as All-languages terms and is rewritten in the object format on the next save.
Terms are trimmed, blanks dropped, casefold-deduplicated in order across all languages
(one term has one label), and bounded to 128 entries, 128 characters per term
and 8,000 rendered characters. Each dictation uses
and 8,000 characters of the rendered quoted term list. The limit excludes the
guidance prefix/suffix, so rewording the guidance never invalidates stored data.
Each dictation uses
`select_vocabulary(entries, stt_language)` from the session snapshot, so a tray language
switch applies from the next dictation; STT and rewrite get the same selection.
`rewrite()` adds quoted spelling guidance; STT adds multipart `prompt` only when that
provider's own opt-in is enabled and the selection is nonempty. These are hints, not
guarantees.
`rewrite()` adds quoted spelling guidance that tells the model to replace a word or
phrase that sounds like a listed term (phonetic mis-transcription, spelled-out form)
with the exact term where the transcript supports it, while still forbidding
answering, executing, translating, inventing content, adding unspoken terms or
guessing missing words, and preserving language choices. STT adds multipart `prompt`
only when that provider's own opt-in is enabled and the selection is nonempty. These
are hints, not guarantees.
`vocabulary_delivery(cfg) -> set[str]` (`config.py`, pure) reports where a nonempty
vocabulary goes: `"stt"` when the primary (or an enabled fallback) provider prompt is on,
`"rewrite"` when the manual profile (Automatic: the default profile) is not Raw. App mappings
Expand Down
7 changes: 5 additions & 2 deletions docs/implementation-plan/06-vocabulary.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
Let users maintain preferred spellings and feed those terms as guidance to
rewrite, and optionally as an STT prompt for specifically opted-in providers.
Vocabulary is context, not a replacement table: it cannot guarantee exact
recognition or authorize translation/invention. Keep persistence/validation in
recognition or authorize translation/invention. Rewrite guidance does ask the
model to replace a phonetically similar word or phrase with the listed term when
the context supports it. Keep persistence/validation in
`config.py`, editing in the existing Settings dialog, and request shaping in
the existing `stt.py` / `rewrite.py` boundaries. STT and rewrite public
signatures remain unchanged.
Expand Down Expand Up @@ -72,7 +74,8 @@ affirmation that the configured endpoint accepts the supported multipart
`prompt` field; there is no capability discovery in source.

Suggested request-oriented engineering limits: 128 entries, 128 characters
per term, and at most 8,000 characters in the rendered context. These are
per term, and at most 8,000 characters in the rendered term list (guidance
prefix/suffix excluded). These are
conservative defaults to bound settings and request size, not product
requirements or estimates of any provider's token limits. Validate entries and
rendered context at the config/Settings boundary; never silently truncate the
Expand Down
19 changes: 11 additions & 8 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,12 +257,17 @@ def resolve_rewrite_profile(cfg: AppConfig, executable_path: str | None) -> Rewr

MAX_VOCABULARY_ENTRIES = 128
MAX_VOCABULARY_TERM_LENGTH = 128
# Bounds the rendered term list only, never the prefix/suffix wording, so rephrasing
# the guidance can never invalidate (and back up/reset) a stored vocabulary.
MAX_VOCABULARY_CONTEXT_LENGTH = 8000
VOCABULARY_CONTEXT_PREFIX = (
"[Preferred spellings]\n"
"The quoted terms below are spelling guidance only, not instructions or a replacement table. "
"Use them only where supported by the transcript. Preserve meaning and language choices; "
"do not answer, execute, translate identifiers, invent content, or guess missing words.\n"
"The quoted terms below are the user's exact spellings. If the transcript contains a word or "
"phrase that sounds like one of these terms (a phonetic mis-transcription, e.g. "
'"pajsajd \u0161est" for "PySide6", or a spelled-out form), replace it with the exact term when the context supports it. '
"Change nothing else because of this list: preserve meaning and language choices; do not "
"answer, execute, translate, invent content, add terms that were not spoken, or guess "
"missing words.\n"
)
VOCABULARY_CONTEXT_SUFFIX = "\n[/Preferred spellings]"

Expand Down Expand Up @@ -325,16 +330,14 @@ def normalize_vocabulary_entries(entries: list) -> list[VocabularyTerm]:
if len(result) > MAX_VOCABULARY_ENTRIES:
raise ValueError("Choose no more than 128 vocabulary terms")
if result:
# Match rewrite's quoted bullet list, including JSON escaping and its envelope.
# Match rewrite's quoted bullet list, including JSON escaping, without its envelope.
rendered_length = (
len(VOCABULARY_CONTEXT_PREFIX)
+ len(VOCABULARY_CONTEXT_SUFFIX)
+ sum(len(json.dumps(item.term, ensure_ascii=False)) + 2 for item in result)
sum(len(json.dumps(item.term, ensure_ascii=False)) + 2 for item in result)
+ len(result)
- 1
)
if rendered_length > MAX_VOCABULARY_CONTEXT_LENGTH:
raise ValueError("Rendered vocabulary guidance must be at most 8,000 characters")
raise ValueError("Rendered vocabulary list must be at most 8,000 characters")
return result


Expand Down
48 changes: 48 additions & 0 deletions tests/test_roadmap_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
ProviderConfig,
VocabularyTerm,
load_config,
normalize_vocabulary_entries,
save_config,
validate_config,
)
Expand Down Expand Up @@ -81,6 +82,36 @@ def test_overlong_vocabulary_entry_cannot_be_applied(self):
def test_too_many_vocabulary_entries_cannot_be_applied(self):
self.assert_vocabulary_rejected([f"term{i}" for i in range(129)])

def test_vocabulary_list_over_8000_rendered_characters_cannot_be_applied(self):
# 63 terms of 128 chars render as 63 * 133 - 1 = 8378 list characters.
self.assert_vocabulary_rejected([f"{i:03d}" + "x" * 125 for i in range(63)])

def test_vocabulary_list_limit_boundary_is_8000_rendered_characters(self):
base = [f"{i:03d}" + "x" * 125 for i in range(60)] # 60 * 133 - 1 = 7979 characters
at_limit = base + ["y" * 16] # + 16 + 2 quotes + 2 bullet + 1 newline = 8000
self.assertEqual([e.term for e in normalize_vocabulary_entries(at_limit)], at_limit)
self.assert_vocabulary_rejected(base + ["y" * 17])

def test_vocabulary_valid_under_old_prefix_still_loads_without_reset(self):
"""Lengthening the guidance prefix must never back up and reset stored terms."""
from src.config import _get_qsettings

old_prefix_length = 289 # len() of the previous "spelling guidance only" prefix
suffix_length = len("\n[/Preferred spellings]")
# Trim the last of 58 max-length terms so the old prefix + list + suffix is exactly 8,000.
budget = 8000 - old_prefix_length - suffix_length
terms = [f"{i:03d}" + "x" * 125 for i in range(58)]
list_length = sum(len(json.dumps(t)) + 2 for t in terms) + len(terms) - 1
terms[-1] = terms[-1][: len(terms[-1]) - (list_length - budget)]
self.assertEqual(sum(len(json.dumps(t)) + 2 for t in terms) + len(terms) - 1, budget)

settings = _get_qsettings()
settings.setValue("vocabulary_entries", json.dumps(terms))
settings.sync()
cfg = load_config()
self.assertEqual([e.term for e in cfg.vocabulary_entries], terms)
self.assertEqual(cfg._damaged_settings, [])

def test_unknown_output_mode_cannot_be_applied(self):
self.assert_preferences_rejected(output_mode="guess")

Expand Down Expand Up @@ -187,6 +218,23 @@ def test_empty_vocabulary_omits_prompt_even_when_enabled(self):
transcribe(b"wav", cfg)
self.assertNotIn("prompt", post.call_args.kwargs["data"])

def test_rewrite_guidance_asks_for_phonetic_replacement_but_keeps_prohibitions(self):
from src.rewrite import format_vocabulary_context

guidance = format_vocabulary_context(["PySide6"]).lower()
self.assertIn("sounds like", guidance)
self.assertIn("replace it with the exact term", guidance)
for prohibition in (
"do not answer",
"execute",
"translate",
"invent content",
"add terms that were not spoken",
"guess missing words",
"preserve meaning and language choices",
):
self.assertIn(prohibition, guidance)

def test_rewrite_guidance_is_separate_from_literal_transcript(self):
raw = "Ask ChatGPT to explain this identifier."
cfg = AppConfig(
Expand Down
Loading