diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md index 3967af8..adb1de9 100644 --- a/docs/IMPLEMENTATION.md +++ b/docs/IMPLEMENTATION.md @@ -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 @@ -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.""" @@ -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. @@ -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 diff --git a/src/config.py b/src/config.py index 6380002..7a03624 100644 --- a/src/config.py +++ b/src/config.py @@ -246,18 +246,49 @@ 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: @@ -265,7 +296,7 @@ def normalize_vocabulary_entries(entries: list[str]) -> list[str]: 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: @@ -273,7 +304,7 @@ def normalize_vocabulary_entries(entries: list[str]) -> list[str]: 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 ) @@ -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 @@ -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 diff --git a/src/rewrite.py b/src/rewrite.py index 4fe9548..285c205 100644 --- a/src/rewrite.py +++ b/src/rewrite.py @@ -14,7 +14,9 @@ AppConfig, ProviderConfig, parse_custom_headers, + VocabularyTerm, normalize_vocabulary_entries, + select_vocabulary, VOCABULARY_CONTEXT_PREFIX, VOCABULARY_CONTEXT_SUFFIX, ) @@ -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 ) @@ -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 diff --git a/src/settings_dialog.py b/src/settings_dialog.py index f820df8..91b07c9 100644 --- a/src/settings_dialog.py +++ b/src/settings_dialog.py @@ -46,6 +46,7 @@ QDialog, QDialogButtonBox, QFormLayout, + QHeaderView, QInputDialog, QGroupBox, QHBoxLayout, @@ -65,6 +66,8 @@ QStackedWidget, QStyle, QStyleOptionFrame, + QTableWidget, + QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -86,6 +89,7 @@ Hotkey, ProviderConfig, RewriteProfile, + VocabularyTerm, builtin_rewrite_profiles, decode_rewrite_catalog, encode_rewrite_catalog, @@ -1036,7 +1040,7 @@ def _build_stt_tab(self) -> None: form.addRow("Language:", self._stt_lang) self._stt_favorites = QListWidget() self._stt_favorites.setMaximumHeight(170) - self._stt_favorites.itemChanged.connect(lambda _item: self._refresh_language_choices()) + self._stt_favorites.itemChanged.connect(self._on_favorites_changed) form.addRow("Also show in tray:", self._stt_favorites) self._stt_prompt_primary_check = ToggleSwitch("Send vocabulary to this provider") @@ -1073,6 +1077,11 @@ def _favorite_codes(self) -> list[str]: if self._stt_favorites.item(i).checkState() == Qt.CheckState.Checked ] + def _on_favorites_changed(self, _item=None) -> None: + self._refresh_language_choices() + if hasattr(self, "_vocabulary_table"): + self._refresh_vocabulary_language_combos() + def _refresh_language_choices(self, active: str | None = None) -> None: if active is None: active = self._stt_lang.currentData() or "" @@ -1517,14 +1526,31 @@ def _build_vocabulary_tab(self) -> None: ) hint.setWordWrap(True) form.addRow(_hint(hint)) - self._vocabulary_list = QListWidget() - self._vocabulary_list.setMaximumHeight(160) - self._vocabulary_list.itemSelectionChanged.connect(self._on_vocabulary_selected) - form.addRow("Terms:", self._vocabulary_list) + language_hint = QLabel( + "Tag a term with a language to send it only when that language is selected; " + "All languages terms are always sent." + ) + language_hint.setWordWrap(True) + form.addRow(_hint(language_hint)) + self._vocabulary_table = QTableWidget(0, 2) + self._vocabulary_table.setHorizontalHeaderLabels(["Term", "Language"]) + self._vocabulary_table.setMinimumHeight(160) + self._vocabulary_table.setMaximumHeight(220) + self._vocabulary_table.verticalHeader().setVisible(False) + self._vocabulary_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) + self._vocabulary_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection) + header = self._vocabulary_table.horizontalHeader() + header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + self._vocabulary_table.itemSelectionChanged.connect(self._on_vocabulary_selected) + form.addRow("Terms:", self._vocabulary_table) self._vocabulary_input = QLineEdit() self._vocabulary_input.setPlaceholderText("e.g. PySide6") - _mono(self._vocabulary_list, self._vocabulary_input) + _mono(self._vocabulary_table, self._vocabulary_input) form.addRow("Term:", self._vocabulary_input) + self._vocabulary_language = QComboBox() + self._fill_vocabulary_language_combo(self._vocabulary_language, "") + form.addRow("Language:", _leading(self._vocabulary_language)) self._vocabulary_add_btn = QPushButton("Add") self._vocabulary_add_btn.clicked.connect(self._on_vocabulary_add) self._vocabulary_edit_btn = QPushButton("Update selected") @@ -1566,42 +1592,98 @@ def _build_vocabulary_tab(self) -> None: _style_form(form) self._tabs.addTab(tab, "Vocabulary") - def _vocabulary_values(self) -> list[str]: - return [self._vocabulary_list.item(i).text() for i in range(self._vocabulary_list.count())] + def _vocabulary_language_codes(self, extra: str = "") -> list[str]: + """All languages, built-ins without Auto, common languages, favorites, then *extra*.""" + codes = [""] + candidates = [code for code, _label in LANGUAGE_OPTIONS if code] + candidates += [code for code, _label in COMMON_LANGUAGES] + candidates += self._favorite_codes() if hasattr(self, "_stt_favorites") else [] + for code in [*candidates, extra]: + if code and code not in codes: + codes.append(code) + return codes + + def _fill_vocabulary_language_combo(self, combo: QComboBox, selected: str) -> None: + combo.blockSignals(True) + combo.clear() + for code in self._vocabulary_language_codes(selected): + combo.addItem("All languages" if not code else f"{language_label(code)} ({code})", code) + combo.setCurrentIndex(_combo_index(combo, selected)) + combo.blockSignals(False) + + def _vocabulary_values(self) -> list[VocabularyTerm]: + result = [] + for row in range(self._vocabulary_table.rowCount()): + item = self._vocabulary_table.item(row, 0) + combo = self._vocabulary_table.cellWidget(row, 1) + result.append( + VocabularyTerm( + item.text() if item is not None else "", + (combo.currentData() or "") if combo is not None else "", + ) + ) + return result + + def _populate_vocabulary_table(self, entries: list[VocabularyTerm]) -> None: + table = self._vocabulary_table + table.setRowCount(0) + table.setRowCount(len(entries)) + for row, entry in enumerate(entries): + table.setItem(row, 0, QTableWidgetItem(entry.term)) + combo = QComboBox() + self._fill_vocabulary_language_combo(combo, entry.language) + table.setCellWidget(row, 1, combo) def _on_vocabulary_selected(self) -> None: - item = self._vocabulary_list.currentItem() - if item is not None: - self._vocabulary_input.setText(item.text()) + row = self._vocabulary_table.currentRow() + if 0 <= row < self._vocabulary_table.rowCount(): + entry = self._vocabulary_values()[row] + self._vocabulary_input.setText(entry.term) + self._fill_vocabulary_language_combo(self._vocabulary_language, entry.language) + + def _new_vocabulary_term(self) -> VocabularyTerm: + return VocabularyTerm( + self._vocabulary_input.text(), self._vocabulary_language.currentData() or "" + ) - def _set_vocabulary_values(self, entries: list[str]) -> None: + def _set_vocabulary_values(self, entries: list[VocabularyTerm]) -> None: try: normalized = normalize_vocabulary_entries(entries) except ValueError as e: QMessageBox.warning(self, "Invalid Vocabulary", str(e)) self._vocabulary_input.setFocus() return - self._vocabulary_list.clear() - self._vocabulary_list.addItems(normalized) + self._populate_vocabulary_table(normalized) self._vocabulary_input.clear() def _on_vocabulary_add(self) -> None: - self._set_vocabulary_values([*self._vocabulary_values(), self._vocabulary_input.text()]) + self._set_vocabulary_values([*self._vocabulary_values(), self._new_vocabulary_term()]) def _on_vocabulary_edit(self) -> None: - row = self._vocabulary_list.currentRow() + row = self._vocabulary_table.currentRow() if row < 0: return entries = self._vocabulary_values() - entries[row] = self._vocabulary_input.text() + entries[row] = self._new_vocabulary_term() self._set_vocabulary_values(entries) def _on_vocabulary_remove(self) -> None: - row = self._vocabulary_list.currentRow() + row = self._vocabulary_table.currentRow() if row >= 0: - self._vocabulary_list.takeItem(row) + self._vocabulary_table.removeRow(row) self._vocabulary_input.clear() + def _refresh_vocabulary_language_combos(self) -> None: + """Offer newly checked favorites without changing any chosen language.""" + combos = [self._vocabulary_language] + combos += [ + self._vocabulary_table.cellWidget(row, 1) + for row in range(self._vocabulary_table.rowCount()) + ] + for combo in combos: + if combo is not None: + self._fill_vocabulary_language_combo(combo, combo.currentData() or "") + def _refresh_replacement_list(self) -> None: self._replacement_list.clear() for source, target in self._replacements: @@ -1692,9 +1774,9 @@ def _populate(self, cfg: AppConfig) -> None: self._rms_label.setText(f"Threshold: {cfg.rms_threshold:.1f}") # Vocabulary - self._vocabulary_list.clear() - self._vocabulary_list.addItems(cfg.vocabulary_entries) + self._populate_vocabulary_table(normalize_vocabulary_entries(cfg.vocabulary_entries)) self._vocabulary_input.clear() + self._fill_vocabulary_language_combo(self._vocabulary_language, "") self._replacements = list(cfg.replacements) self._refresh_replacement_list() @@ -1996,9 +2078,11 @@ def _save_or_warn(self) -> bool: from src.utils import ScreamerError try: - self._working.vocabulary_entries = normalize_vocabulary_entries( - self._working.vocabulary_entries - ) + normalized = normalize_vocabulary_entries(self._working.vocabulary_entries) + self._working.vocabulary_entries = normalized + if normalized != self._vocabulary_values(): + # Cell edits can leave blank or duplicate rows that the save drops. + self._populate_vocabulary_table(normalized) recovery = Hotkey.parse(self._working.recovery_hotkey) if recovery is not None: self._working.recovery_hotkey = recovery.to_canonical() diff --git a/src/stt.py b/src/stt.py index b2c1e3c..ea8bf60 100644 --- a/src/stt.py +++ b/src/stt.py @@ -13,7 +13,7 @@ AppConfig, ProviderConfig, parse_custom_headers, - normalize_vocabulary_entries, + select_vocabulary, stt_provider_is_configured, ) from src.utils import AppError, PipelineResult, ScreamerError, log_duration @@ -45,10 +45,10 @@ def transcribe(audio_wav: bytes, config: AppConfig) -> PipelineResult: vocabulary_prompt = "" if config.stt_prompt_primary_enabled or config.stt_prompt_fallback_enabled: - terms = normalize_vocabulary_entries(config.vocabulary_entries) + terms = select_vocabulary(config.vocabulary_entries, config.stt_language) if terms: vocabulary_prompt = "Preferred spellings: " + ", ".join( - json.dumps(term, ensure_ascii=False) for term in terms + json.dumps(item.term, ensure_ascii=False) for item in terms ) for is_fallback, provider, language in ( diff --git a/src/theme.py b/src/theme.py index cd87f6f..8df49b3 100644 --- a/src/theme.py +++ b/src/theme.py @@ -317,6 +317,16 @@ def _palette() -> QPalette: background: rgba(255, 122, 77, 0.14); color: $text; } QListWidget:disabled { color: $text_3; } +QTableWidget { + background: $surface; color: $text; border: 1px solid $line; border-radius: 10px; + gridline-color: $line; outline: 0; +} +QTableWidget::item { padding: 4px 8px; } +QTableWidget::item:selected { background: rgba(255, 122, 77, 0.14); color: $text; } +QHeaderView::section { + background: $surface; color: $text_2; border: none; + border-bottom: 1px solid $line; padding: 4px 8px; +} QListWidget#hushNav { background: transparent; border: none; padding: 0; } QListWidget#hushNav::item { padding: 8px 12px; margin: 1px 0; color: $text_2; border-radius: 8px; diff --git a/tests/test_profiles.py b/tests/test_profiles.py index 4b67763..b0935cb 100644 --- a/tests/test_profiles.py +++ b/tests/test_profiles.py @@ -12,6 +12,7 @@ AppMapping, DEFAULT_LLM_SYSTEM_PROMPT, RewriteProfile, + VocabularyTerm, decode_rewrite_catalog, encode_rewrite_catalog, load_config, @@ -332,7 +333,7 @@ def test_effective_profile_and_target_freeze_once_before_recording(self): [custom], [AppMapping("C:\\Tools\\editor.exe", custom.id)] ), post_type_key="enter", - vocabulary_entries=["QThread"], + vocabulary_entries=[VocabularyTerm("QThread", "cs")], ) target = WindowIdentity(100, 200, "C:\\Tools\\editor.exe") with patch("src.main.get_foreground_target", return_value=target): @@ -348,7 +349,7 @@ def test_effective_profile_and_target_freeze_once_before_recording(self): self.tray._finalize_recording() self.assertIs(self.tray._worker._config, snapshot) self.assertEqual(snapshot.stt_language, "cs") - self.assertEqual(snapshot.vocabulary_entries, ["QThread"]) + self.assertEqual(snapshot.vocabulary_entries, [VocabularyTerm("QThread", "cs")]) with ( patch("src.main.transcribe", return_value=PipelineResult("raw")), patch("src.main.rewrite", return_value=PipelineResult("clean")) as cleanup, diff --git a/tests/test_roadmap_backends.py b/tests/test_roadmap_backends.py index e3457ce..21098d5 100644 --- a/tests/test_roadmap_backends.py +++ b/tests/test_roadmap_backends.py @@ -9,7 +9,14 @@ import httpx -from src.config import AppConfig, ProviderConfig, load_config, save_config, validate_config +from src.config import ( + AppConfig, + ProviderConfig, + VocabularyTerm, + load_config, + save_config, + validate_config, +) from src.rewrite import rewrite from src.stt import transcribe from src.utils import AppError, ScreamerError @@ -27,7 +34,10 @@ def test_vocabulary_roundtrip_preserves_display_spelling_and_order(self): ) save_config(cfg) restored = load_config() - self.assertEqual(restored.vocabulary_entries, ["Screamer", "QThread", "Stra\u00dfe"]) + self.assertEqual( + restored.vocabulary_entries, + [VocabularyTerm("Screamer"), VocabularyTerm("QThread"), VocabularyTerm("Stra\u00dfe")], + ) self.assertFalse(restored.stt_prompt_primary_enabled) self.assertFalse(restored.stt_prompt_fallback_enabled) @@ -110,7 +120,7 @@ def transcribe_via_fallback(self, *, primary_enabled, fallback_enabled): stt_fallback_base_url="https://fallback.test/v1", stt_fallback_model="fallback", stt_language="cs", - vocabulary_entries=["Screamer", "QThread"], + vocabulary_entries=[VocabularyTerm("Screamer"), VocabularyTerm("QThread")], stt_prompt_primary_enabled=primary_enabled, stt_prompt_fallback_enabled=fallback_enabled, ) @@ -185,7 +195,7 @@ def test_rewrite_guidance_is_separate_from_literal_transcript(self): llm_base_url="https://primary.test", llm_model="model", llm_system_prompt="Keep my exact policy.\r\n", - vocabulary_entries=["Screamer", "QThread"], + vocabulary_entries=[VocabularyTerm("Screamer"), VocabularyTerm("QThread")], stt_language="cs", ) with patch( @@ -205,7 +215,9 @@ def test_rewrite_guidance_is_separate_from_literal_transcript(self): post.call_args.kwargs["json"]["messages"][1], {"role": "user", "content": raw} ) self.assertEqual(result.text, "candidate") - self.assertEqual(cfg.vocabulary_entries, ["Screamer", "QThread"]) + self.assertEqual( + cfg.vocabulary_entries, [VocabularyTerm("Screamer"), VocabularyTerm("QThread")] + ) class KeylessSttTests(unittest.TestCase): diff --git a/tests/test_roadmap_settings.py b/tests/test_roadmap_settings.py index 3e65431..4a7d91b 100644 --- a/tests/test_roadmap_settings.py +++ b/tests/test_roadmap_settings.py @@ -7,7 +7,7 @@ from PySide6.QtWidgets import QApplication, QMessageBox -from src.config import AppConfig, load_config, save_config +from src.config import AppConfig, VocabularyTerm, load_config, save_config from src.settings_dialog import SettingsDialog _app = QApplication.instance() or QApplication([]) @@ -35,7 +35,10 @@ def test_vocabulary_and_provider_flags_apply_without_mutating_live_config(self): self.dialog._stt_prompt_fallback_check.setChecked(False) self.dialog._on_apply() restored = load_config() - self.assertEqual(restored.vocabulary_entries, ["Screamer", "QThread"]) + self.assertEqual( + restored.vocabulary_entries, + [VocabularyTerm("Screamer"), VocabularyTerm("QThread")], + ) self.assertTrue(restored.stt_prompt_primary_enabled) self.assertFalse(restored.stt_prompt_fallback_enabled) self.assertEqual(self.cfg.vocabulary_entries, []) diff --git a/tests/test_vocabulary_languages.py b/tests/test_vocabulary_languages.py new file mode 100644 index 0000000..876068c --- /dev/null +++ b/tests/test_vocabulary_languages.py @@ -0,0 +1,278 @@ +"""Language-tagged vocabulary: model, selection, persistence, requests and settings UI.""" + +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import httpx +from PySide6.QtWidgets import QApplication + +from src.config import ( + AppConfig, + VocabularyTerm, + decode_vocabulary_entries, + encode_vocabulary_entries, + load_config, + normalize_vocabulary_entries, + save_config, + select_vocabulary, + validate_config, +) +from src.rewrite import rewrite +from src.settings_dialog import SettingsDialog +from src.stt import transcribe + +_app = QApplication.instance() or QApplication([]) + +T = VocabularyTerm + +ENTRIES = [ + T("Screamer"), + T("ahoj", "cs"), + T("QThread"), + T("hello", "en"), + T("obrigado", "pt-br"), + T("Kotlin", "cs"), +] + + +class SelectVocabularyTests(unittest.TestCase): + def test_auto_selects_only_all_language_terms(self): + self.assertEqual(select_vocabulary(ENTRIES, ""), [T("Screamer"), T("QThread")]) + + def test_language_terms_come_first_then_all_languages_in_list_order(self): + self.assertEqual( + select_vocabulary(ENTRIES, "cs"), + [T("ahoj", "cs"), T("Kotlin", "cs"), T("Screamer"), T("QThread")], + ) + + def test_primary_subtag_matches_both_ways(self): + self.assertEqual( + select_vocabulary(ENTRIES, "pt"), [T("obrigado", "pt-br"), T("Screamer"), T("QThread")] + ) + pt_entries = [T("Lisboa", "pt"), T("Screamer")] + self.assertEqual(select_vocabulary(pt_entries, "pt-br"), [T("Lisboa", "pt"), T("Screamer")]) + + def test_other_language_gets_no_foreign_terms(self): + self.assertEqual(select_vocabulary(ENTRIES, "de"), [T("Screamer"), T("QThread")]) + + def test_empty_vocabulary(self): + self.assertEqual(select_vocabulary([], "cs"), []) + + +class NormalizeVocabularyTests(unittest.TestCase): + def test_accepts_terms_dicts_and_legacy_strings(self): + self.assertEqual( + normalize_vocabulary_entries( + [" PySide6 ", {"term": "ahoj", "language": " CS "}, T("hello", "en")] + ), + [T("PySide6"), T("ahoj", "cs"), T("hello", "en")], + ) + + def test_dedup_across_languages_first_occurrence_wins(self): + self.assertEqual( + normalize_vocabulary_entries([T("Qt", "cs"), T("qt"), T("QT", "en")]), [T("Qt", "cs")] + ) + + def test_invalid_language_code_is_rejected(self): + for language in ("c", "cs_CZ", "123", "x" * 40): + with self.subTest(language=language), self.assertRaises(ValueError): + normalize_vocabulary_entries([T("term", language)]) + + def test_malformed_entries_are_rejected(self): + for entry in (42, {"language": "cs"}, {"term": "a", "extra": 1}, {"term": 1}): + with self.subTest(entry=entry), self.assertRaises(ValueError): + normalize_vocabulary_entries([entry]) + + def test_limits_apply_to_whole_list(self): + with self.assertRaises(ValueError): + normalize_vocabulary_entries([T(f"t{i}", "cs" if i % 2 else "") for i in range(129)]) + with self.assertRaises(ValueError): + normalize_vocabulary_entries([T("x" * 129, "en")]) + with self.assertRaises(ValueError): + normalize_vocabulary_entries([T(f"{i:03}" + "x" * 120, "cs") for i in range(70)]) + + def test_validate_config_reports_bad_language(self): + cfg = AppConfig( + stt_base_url="http://127.0.0.1:8000/v1", + stt_model="local", + vocabulary_entries=[T("term", "not a code")], + ) + self.assertTrue(any("vocabulary" in i.message.lower() for i in validate_config(cfg))) + + +class VocabularyPersistenceTests(unittest.TestCase): + def setUp(self): + self.tmp = self.enterContext(tempfile.TemporaryDirectory()) + self.enterContext(patch("src.config.APP_DIR", self.tmp)) + self.enterContext(patch("src.config._dpapi_available", return_value=False)) + + def test_encode_writes_objects_and_decode_roundtrips(self): + encoded = encode_vocabulary_entries([T("PySide6"), T("ahoj", "cs")]) + self.assertEqual( + json.loads(encoded), + [{"term": "PySide6", "language": ""}, {"term": "ahoj", "language": "cs"}], + ) + self.assertEqual(decode_vocabulary_entries(encoded), [T("PySide6"), T("ahoj", "cs")]) + + def test_legacy_string_list_migrates_on_next_save(self): + from src.config import _get_qsettings + + settings = _get_qsettings() + settings.setValue("vocabulary_entries", '["PySide6", "Qt"]') + settings.sync() + cfg = load_config() + self.assertEqual(cfg.vocabulary_entries, [T("PySide6"), T("Qt")]) + self.assertEqual(cfg._damaged_settings, []) + save_config(cfg) + self.assertEqual( + json.loads(_get_qsettings().value("vocabulary_entries")), + [{"term": "PySide6", "language": ""}, {"term": "Qt", "language": ""}], + ) + + def test_damaged_tagged_vocabulary_is_backed_up_and_reset(self): + from src.config import _get_qsettings + + settings = _get_qsettings() + damaged = '[{"term": "ahoj", "language": "??"}]' + settings.setValue("vocabulary_entries", damaged) + settings.sync() + cfg = load_config() + self.assertEqual(cfg.vocabulary_entries, []) + self.assertEqual(cfg._damaged_settings, ["vocabulary_entries"]) + backup = Path(settings.fileName()).parent / "settings-damaged.txt" + self.assertIn(f"vocabulary_entries = {damaged}", backup.read_text(encoding="utf-8")) + + +class VocabularyRequestSelectionTests(unittest.TestCase): + def _cfg(self, language): + return AppConfig( + stt_api_key="key", + stt_base_url="https://stt.test/v1", + stt_model="model", + stt_language=language, + stt_prompt_primary_enabled=True, + llm_enabled=True, + llm_api_key="key", + llm_base_url="https://llm.test", + llm_model="model", + vocabulary_entries=list(ENTRIES), + ) + + def _stt_prompt(self, language): + with patch( + "src.http_client.post", return_value=httpx.Response(200, json={"text": "raw"}) + ) as post: + transcribe(b"wav", self._cfg(language)) + return post.call_args.kwargs["data"].get("prompt", "") + + def _rewrite_prompt(self, language): + with patch( + "src.http_client.post", + return_value=httpx.Response(200, json={"choices": [{"message": {"content": "x"}}]}), + ) as post: + rewrite("raw", self._cfg(language)) + return post.call_args.kwargs["json"]["messages"][0]["content"] + + def test_stt_prompt_uses_selected_language_terms(self): + self.assertEqual( + self._stt_prompt("cs"), + 'Preferred spellings: "ahoj", "Kotlin", "Screamer", "QThread"', + ) + self.assertEqual(self._stt_prompt(""), 'Preferred spellings: "Screamer", "QThread"') + + def test_rewrite_uses_same_selection(self): + prompt = self._rewrite_prompt("en") + self.assertIn('- "hello"\n- "Screamer"\n- "QThread"', prompt) + self.assertNotIn("ahoj", prompt) + self.assertNotIn("obrigado", prompt) + + +class VocabularySettingsTests(unittest.TestCase): + def setUp(self): + directory = self.enterContext(tempfile.TemporaryDirectory()) + self.enterContext(patch("src.config.APP_DIR", directory)) + self.enterContext(patch("src.config._dpapi_available", return_value=False)) + self.enterContext(patch("src.settings_dialog.is_supported", return_value=False)) + self.cfg = AppConfig( + stt_base_url="http://127.0.0.1:8000/v1", + stt_model="local", + stt_language_favorites=["xx-test"], + vocabulary_entries=[T("Screamer"), T("legacy", "tlh")], + ) + save_config(self.cfg) + self.dialog = SettingsDialog(self.cfg, devices=[]) + self.addCleanup(self.dialog.deleteLater) + + def _combo_codes(self, combo): + return [combo.itemData(i) for i in range(combo.count())] + + def test_language_combo_offers_all_builtins_common_favorites_and_saved_code(self): + codes = self._combo_codes(self.dialog._vocabulary_table.cellWidget(1, 1)) + self.assertEqual(codes[:3], ["", "cs", "en"]) + self.assertIn("de", codes) + self.assertIn("xx-test", codes) + self.assertEqual(codes[-1], "tlh") + self.assertEqual(self.dialog._vocabulary_table.cellWidget(1, 1).currentData(), "tlh") + self.assertEqual(self.dialog._vocabulary_language.itemText(0), "All languages") + + def test_add_term_with_language_change_cell_and_reload(self): + self.dialog._vocabulary_input.setText("ahoj") + combo = self.dialog._vocabulary_language + combo.setCurrentIndex(combo.findData("cs")) + self.dialog._vocabulary_add_btn.click() + self.assertEqual(self.dialog._vocabulary_table.rowCount(), 3) + self.assertEqual(self.dialog._vocabulary_input.text(), "") + + cell = self.dialog._vocabulary_table.cellWidget(0, 1) + cell.setCurrentIndex(cell.findData("en")) + self.dialog._vocabulary_table.item(1, 0).setText("Klingon") + + self.dialog._on_apply() + expected = [T("Screamer", "en"), T("Klingon", "tlh"), T("ahoj", "cs")] + self.assertEqual(load_config().vocabulary_entries, expected) + self.assertEqual(self.cfg.vocabulary_entries, [T("Screamer"), T("legacy", "tlh")]) + + reopened = SettingsDialog(load_config(), devices=[]) + self.addCleanup(reopened.deleteLater) + self.assertEqual(reopened._vocabulary_values(), expected) + + def test_update_selected_changes_term_and_language(self): + self.dialog._vocabulary_table.selectRow(0) + self.assertEqual(self.dialog._vocabulary_input.text(), "Screamer") + self.dialog._vocabulary_input.setText("Screamer app") + combo = self.dialog._vocabulary_language + combo.setCurrentIndex(combo.findData("de")) + self.dialog._vocabulary_edit_btn.click() + self.assertEqual( + self.dialog._vocabulary_values(), [T("Screamer app", "de"), T("legacy", "tlh")] + ) + + def test_duplicate_across_languages_is_merged(self): + self.dialog._vocabulary_input.setText("screamer") + combo = self.dialog._vocabulary_language + combo.setCurrentIndex(combo.findData("cs")) + self.dialog._vocabulary_add_btn.click() + self.assertEqual(self.dialog._vocabulary_values(), [T("Screamer"), T("legacy", "tlh")]) + + def test_apply_syncs_table_with_saved_vocabulary_after_cell_edits(self): + self.dialog._vocabulary_table.item(1, 0).setText(" screamer ") + self.dialog._on_apply() + self.assertEqual(load_config().vocabulary_entries, [T("Screamer")]) + self.assertEqual(self.dialog._vocabulary_values(), [T("Screamer")]) + + def test_invalid_term_shows_warning(self): + self.dialog._vocabulary_input.setText("x" * 129) + with patch("src.settings_dialog.QMessageBox.warning") as warning: + self.dialog._vocabulary_add_btn.click() + warning.assert_called_once() + self.assertEqual(self.dialog._vocabulary_table.rowCount(), 2) + + +if __name__ == "__main__": + unittest.main()