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
53 changes: 39 additions & 14 deletions docs/IMPLEMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ class AppConfig:
history_limit: int = 100 # 1..100
sound_enabled: bool = True
recovery_hotkey: str = "ctrl+alt+shift+key:0x56" # Insert last; "" = none
vocabulary_entries: list[str] = field(default_factory=list)
vocabulary_entries: list[VocabularyTerm] = field(default_factory=list)
replacements: list[tuple[str, str]] = field(default_factory=list)
start_with_windows: bool = False
audio_device_id: int | None = None
Expand Down Expand Up @@ -292,10 +292,24 @@ def rewrite_needs_llm(cfg: AppConfig) -> bool: ...
def insecure_base_urls(cfg: AppConfig) -> list[tuple[str, str]]: ...
def stt_provider_is_configured(provider: ProviderConfig) -> bool: ... # URL + model

def normalize_vocabulary_entries(entries: list[str]) -> list[str]: ...
"""Trim and casefold-deduplicate; cap 128 terms, 128 chars/term and 8,000 rendered chars."""
def encode_vocabulary_entries(entries: list[str]) -> str: ...
def decode_vocabulary_entries(value: object) -> list[str]: ...
@dataclass(frozen=True)
class VocabularyTerm:
term: str
language: str = "" # "" = All languages; otherwise a normalize_language_code() code

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."""
def encode_vocabulary_entries(entries: list) -> str: ...
"""JSON array of objects: [{"term": "PySide6", "language": ""}, ...]."""
def decode_vocabulary_entries(value: object) -> list[VocabularyTerm]: ...
"""Reads the object format and the legacy ["PySide6", "Qt"] string list."""
def select_vocabulary(entries: list, language: str) -> list[VocabularyTerm]: ...
"""Pure per-dictation pick. language "" (Auto) -> All-languages terms only; otherwise
that language's terms, then All-languages terms, each group in list order. Matches on
the primary subtag (pt-br <-> pt), like the STT request."""

def normalize_replacements(pairs: list) -> list[tuple[str, str]]: ...
"""(heard, write) pairs; trimmed, no controls, ≤256 chars each, ≤256 pairs, first wins."""
Expand Down Expand Up @@ -790,11 +804,17 @@ ruff format --check src/ tests/ .github/scripts/
bindings are rejected; Escape cancels recording without changing a History selection, and cannot
be a recovery trigger. Injected keyboard events pass through the hook without
changing physical trigger state, so Screamer's post-key cannot trigger dictation.
- Vocabulary is JSON in ordinary settings. Terms are trimmed, blanks dropped,
casefold-deduplicated in order, and bounded to 128 entries, 128 characters per term
and 8,000 rendered characters. `rewrite()` adds
quoted spelling guidance; STT adds multipart `prompt` only when that provider's own
opt-in is enabled and vocabulary is nonempty. These are hints, not guarantees.
- Vocabulary is JSON in ordinary settings: an array of `{"term", "language"}` objects,
where `language` is `""` (All languages) or a language code. A legacy array of strings
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
`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.
- Replacements are JSON `[heard, write]` pairs applied by the worker to the raw
transcript after STT and to the rewritten text after the LLM, so they also work with
Raw. Matching is whole-word, case-insensitive, longest first, in one pass.
Expand Down Expand Up @@ -879,14 +899,19 @@ fields. Settings and history are separate stores, not one transaction.
`transcribe(audio_wav, config) -> PipelineResult` and `rewrite(text, config) ->
PipelineResult` remain the public backend signatures. STT completeness is URL plus model,
with optional API key; LLM completeness still requires key, URL and model. `rewrite()`
returns its input when disabled; when enabled it adds vocabulary guidance and selected
language to its system prompt. `stt.py` adds multipart `prompt` only for an individually
opted-in provider with nonempty vocabulary. Keyless STT omits generated Bearer auth;
returns its input when disabled; when enabled it adds vocabulary guidance (the
`select_vocabulary` pick for `stt_language`) and selected language to its system prompt.
`stt.py` adds multipart `prompt` only for an individually opted-in provider with a
nonempty selection. Keyless STT omits generated Bearer auth;
configured custom headers remain provider-local.

`SettingsDialog` has six tabs (General, STT, LLM, Audio, Vocabulary, Rewrite Profiles).
It edits a draft; Apply/OK validate and save, Cancel discards unapplied edits. General
contains output/history/recovery controls. `HistoryStore.load()` validates the complete
contains output/history/recovery controls. Vocabulary shows a Term | Language table
(editable term text, a language combo per row: All languages, built-in and common
languages, favorites, then a saved code missing from those); Add / Update selected use
the Term field and a language combo, and validate through `normalize_vocabulary_entries`.
`HistoryStore.load()` validates the complete
file then returns sorted latest entries; `trim()` limits a view without rewriting the
file. `upsert()` and `delete()` perform read-modify-write and retention, while mutations
refuse corrupt input. The `main()` per-APP_DIR lock is required for this single-writer
Expand Down
85 changes: 72 additions & 13 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,34 +246,65 @@ def _has_control_chars(value: str) -> bool:
return any(unicodedata.category(c) in {"Cc", "Cf", "Cs", "Zl", "Zp"} for c in value)


def normalize_vocabulary_entries(entries: list[str]) -> list[str]:
"""Trim blanks and stably deduplicate preferred spellings; never truncate."""
@dataclass(frozen=True)
class VocabularyTerm:
"""One preferred spelling. ``language == ""`` means it applies to all languages."""

term: str
language: str = ""


def _coerce_vocabulary_term(entry: object) -> VocabularyTerm:
if isinstance(entry, VocabularyTerm):
term, language = entry.term, entry.language
elif isinstance(entry, str):
term, language = entry, ""
elif isinstance(entry, dict):
if not set(entry) <= {"term", "language"} or "term" not in entry:
raise ValueError("Every vocabulary term needs a term and an optional language")
term, language = entry["term"], entry.get("language", "")
else:
raise ValueError("Every vocabulary term must be text")
if not isinstance(term, str):
raise ValueError("Every vocabulary term must be text")
if not isinstance(language, str):
raise ValueError("Vocabulary language must be text")
language = language.strip()
return VocabularyTerm(term, normalize_language_code(language) if language else "")


def normalize_vocabulary_entries(entries: list) -> list[VocabularyTerm]:
"""Trim blanks and stably deduplicate preferred spellings; never truncate.

Accepts ``VocabularyTerm``, ``{"term", "language"}`` dicts and legacy plain strings
(which apply to all languages). A term (case-folded) appears once across the whole
list; the first occurrence and its language win.
"""
if not isinstance(entries, list):
raise ValueError("Vocabulary must be a list of terms")
result: list[str] = []
result: list[VocabularyTerm] = []
seen: set[str] = set()
for entry in entries:
if not isinstance(entry, str):
raise ValueError("Every vocabulary term must be text")
if _has_control_chars(entry):
item = _coerce_vocabulary_term(entry)
if _has_control_chars(item.term):
raise ValueError("Vocabulary terms cannot contain controls or line breaks")
term = entry.strip()
term = item.term.strip()
if not term:
continue
if len(term) > MAX_VOCABULARY_TERM_LENGTH:
raise ValueError("Vocabulary terms must be at most 128 characters")
folded = term.casefold()
if folded not in seen:
seen.add(folded)
result.append(term)
result.append(VocabularyTerm(term, item.language))
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.
rendered_length = (
len(VOCABULARY_CONTEXT_PREFIX)
+ len(VOCABULARY_CONTEXT_SUFFIX)
+ sum(len(json.dumps(term, ensure_ascii=False)) + 2 for term in result)
+ sum(len(json.dumps(item.term, ensure_ascii=False)) + 2 for item in result)
+ len(result)
- 1
)
Expand All @@ -282,16 +313,44 @@ def normalize_vocabulary_entries(entries: list[str]) -> list[str]:
return result


def encode_vocabulary_entries(entries: list[str]) -> str:
return json.dumps(normalize_vocabulary_entries(entries), ensure_ascii=False)
def encode_vocabulary_entries(entries: list) -> str:
return json.dumps(
[
{"term": item.term, "language": item.language}
for item in normalize_vocabulary_entries(entries)
],
ensure_ascii=False,
)


def decode_vocabulary_entries(value: object) -> list[str]:
def decode_vocabulary_entries(value: object) -> list[VocabularyTerm]:
"""Decode the object format or the legacy list of strings (rewritten on next save)."""
if not isinstance(value, str):
raise ValueError("Vocabulary must be JSON-encoded text")
return normalize_vocabulary_entries(json.loads(value))


def _primary_language(code: str) -> str:
return code.split("-", 1)[0]


def select_vocabulary(entries: list, language: str) -> list[VocabularyTerm]:
"""Terms for one dictation: the language's own terms first, then "All languages" terms.

Auto (``""``) selects only "All languages" terms. Languages match on the primary
subtag (``pt-br`` <-> ``pt``), as the STT request does. List order is kept per group.
"""
terms = normalize_vocabulary_entries(entries)
general = [item for item in terms if not item.language]
if not language:
return general
primary = _primary_language(language.strip().lower())
specific = [
item for item in terms if item.language and _primary_language(item.language) == primary
]
return specific + general


MAX_REPLACEMENTS = 256
MAX_REPLACEMENT_LENGTH = 256

Expand Down Expand Up @@ -648,7 +707,7 @@ class AppConfig:
history_limit: int = 100
sound_enabled: bool = True
recovery_hotkey: str = "ctrl+alt+shift+key:0x56"
vocabulary_entries: list[str] = field(default_factory=list)
vocabulary_entries: list[VocabularyTerm] = field(default_factory=list)
replacements: list[tuple[str, str]] = field(default_factory=list)
start_with_windows: bool = False
audio_device_id: int | None = None
Expand Down
16 changes: 12 additions & 4 deletions src/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
AppConfig,
ProviderConfig,
parse_custom_headers,
VocabularyTerm,
normalize_vocabulary_entries,
select_vocabulary,
VOCABULARY_CONTEXT_PREFIX,
VOCABULARY_CONTEXT_SUFFIX,
)
Expand All @@ -23,14 +25,18 @@
log = logging.getLogger(__name__)


def format_vocabulary_context(entries: list[str]) -> str:
"""Render bounded, quoted spelling guidance without touching transcript data."""
def format_vocabulary_context(entries: list[VocabularyTerm | str]) -> str:
"""Render bounded, quoted spelling guidance without touching transcript data.

*entries* is rendered as given (after normalization); callers pick the dictation's
terms with ``select_vocabulary`` first.
"""
terms = normalize_vocabulary_entries(entries)
if not terms:
return ""
return (
VOCABULARY_CONTEXT_PREFIX
+ "\n".join("- " + json.dumps(term, ensure_ascii=False) for term in terms)
+ "\n".join("- " + json.dumps(item.term, ensure_ascii=False) for item in terms)
+ VOCABULARY_CONTEXT_SUFFIX
)

Expand All @@ -46,7 +52,9 @@ def rewrite(text: str, config: AppConfig) -> PipelineResult:
return PipelineResult(text=text)

system_prompt = config.llm_system_prompt or ""
vocabulary_context = format_vocabulary_context(config.vocabulary_entries)
vocabulary_context = format_vocabulary_context(
select_vocabulary(config.vocabulary_entries, config.stt_language)
)
if vocabulary_context:
system_prompt += "\n\n" + vocabulary_context
language = config.stt_language
Expand Down
Loading
Loading