Preserve Windows processing styles and helper compatibility
This commit is contained in:
parent
ecc356be46
commit
c409366dde
7 changed files with 188 additions and 15 deletions
|
|
@ -5,7 +5,6 @@ from __future__ import annotations
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
|
||||||
import subprocess
|
import subprocess
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -144,7 +143,9 @@ def plan_chunk_ranges(
|
||||||
|
|
||||||
def _find_ffmpeg() -> str | None:
|
def _find_ffmpeg() -> str | None:
|
||||||
"""Ищет ffmpeg: сначала PATH, потом стандартные локации homebrew/macports."""
|
"""Ищет ffmpeg: сначала PATH, потом стандартные локации homebrew/macports."""
|
||||||
found = shutil.which("ffmpeg")
|
from voice_dictation.core.ffmpeg_setup import find_ffmpeg
|
||||||
|
|
||||||
|
found = find_ffmpeg(Path.home() / ".dictate" / "bin")
|
||||||
if found:
|
if found:
|
||||||
return found
|
return found
|
||||||
for path in _FFMPEG_FALLBACK_PATHS:
|
for path in _FFMPEG_FALLBACK_PATHS:
|
||||||
|
|
|
||||||
|
|
@ -144,6 +144,36 @@ def _config_from_dict(data: dict[str, object]) -> Config:
|
||||||
if val is not None and isinstance(val, str):
|
if val is not None and isinstance(val, str):
|
||||||
kwargs[key] = Path(val)
|
kwargs[key] = Path(val)
|
||||||
|
|
||||||
|
# Upgrade Windows mode-based settings before filtering obsolete keys.
|
||||||
|
if "summary_presets" not in kwargs and any(
|
||||||
|
key in kwargs for key in ("mode", "custom_modes", "summary_mode")
|
||||||
|
):
|
||||||
|
from voice_dictation.core.modes import DEFAULT_MODES
|
||||||
|
|
||||||
|
model = str(kwargs.get("proc_model", kwargs.get("summary_model", "gpt-4o-mini")))
|
||||||
|
selected = str(kwargs.get("mode", "summary" if kwargs.get("summary_mode") else "raw"))
|
||||||
|
presets = [
|
||||||
|
SummaryPreset(spec.label, model if spec.prompt else "", spec.prompt)
|
||||||
|
for spec in DEFAULT_MODES
|
||||||
|
]
|
||||||
|
selected_name = next(
|
||||||
|
(spec.label for spec in DEFAULT_MODES if spec.key == selected), presets[0].name
|
||||||
|
)
|
||||||
|
custom = kwargs.get("custom_modes")
|
||||||
|
if isinstance(custom, dict):
|
||||||
|
for name, prompt in custom.items():
|
||||||
|
if not isinstance(name, str) or not isinstance(prompt, str):
|
||||||
|
continue
|
||||||
|
# A custom label may equal a built-in label; keep both unambiguously.
|
||||||
|
label = name
|
||||||
|
while any(preset.name == label for preset in presets):
|
||||||
|
label += " (свой)"
|
||||||
|
presets.append(SummaryPreset(label, model, prompt))
|
||||||
|
if selected == f"custom:{name}":
|
||||||
|
selected_name = label
|
||||||
|
kwargs["summary_presets"] = [dataclasses.asdict(preset) for preset in presets]
|
||||||
|
kwargs.setdefault("active_preset", selected_name)
|
||||||
|
|
||||||
presets_raw = kwargs.get("summary_presets")
|
presets_raw = kwargs.get("summary_presets")
|
||||||
if isinstance(presets_raw, list):
|
if isinstance(presets_raw, list):
|
||||||
kwargs["summary_presets"] = [
|
kwargs["summary_presets"] = [
|
||||||
|
|
|
||||||
|
|
@ -60,6 +60,7 @@ class AppPaths:
|
||||||
self.custom_sounds_dir,
|
self.custom_sounds_dir,
|
||||||
self.tmp_dir,
|
self.tmp_dir,
|
||||||
self.sessions_dir,
|
self.sessions_dir,
|
||||||
|
self.bin_dir,
|
||||||
):
|
):
|
||||||
directory.mkdir(parents=True, exist_ok=True)
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
return self
|
return self
|
||||||
|
|
@ -68,3 +69,8 @@ class AppPaths:
|
||||||
def sessions_dir(self) -> Path:
|
def sessions_dir(self) -> Path:
|
||||||
"""Постоянные аудиосессии и промежуточные результаты транскрипции."""
|
"""Постоянные аудиосессии и промежуточные результаты транскрипции."""
|
||||||
return self.root / "sessions"
|
return self.root / "sessions"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bin_dir(self) -> Path:
|
||||||
|
"""Downloaded helper binaries, preserved across application updates."""
|
||||||
|
return self.root / "bin"
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
"""Автовставка на Windows через pynput (Ctrl+V)."""
|
"""Автовставка на Windows через Win32 keybd_event (Ctrl+V)."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
@ -11,7 +12,7 @@ logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class WinAutoPaste:
|
class WinAutoPaste:
|
||||||
"""Имитирует Ctrl+V в активном окне через pynput.
|
"""Имитирует Ctrl+V в активном окне через Win32.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
||||||
|
|
@ -24,22 +25,25 @@ class WinAutoPaste:
|
||||||
"""Нажимает Ctrl+V в активном окне.
|
"""Нажимает Ctrl+V в активном окне.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
PlatformError: Если pynput не может отправить событие.
|
PlatformError: Если Win32 не может отправить событие.
|
||||||
"""
|
"""
|
||||||
try:
|
|
||||||
from pynput.keyboard import Controller, Key
|
|
||||||
except ImportError as exc:
|
|
||||||
raise PlatformError("pynput не установлен") from exc
|
|
||||||
|
|
||||||
if self._paste_delay_ms > 0:
|
if self._paste_delay_ms > 0:
|
||||||
time.sleep(self._paste_delay_ms / 1000)
|
time.sleep(self._paste_delay_ms / 1000)
|
||||||
|
|
||||||
keyboard = Controller()
|
|
||||||
try:
|
try:
|
||||||
with keyboard.pressed(Key.ctrl):
|
send = ctypes.windll.user32.keybd_event # type: ignore[attr-defined]
|
||||||
keyboard.press("v")
|
for key in (0x11, 0x12, 0x10, 0x20):
|
||||||
keyboard.release("v")
|
send(key, 0, 0x0002, 0)
|
||||||
|
time.sleep(0.5)
|
||||||
|
send(0x11, 0, 0, 0)
|
||||||
|
time.sleep(0.05)
|
||||||
|
try:
|
||||||
|
send(0x56, 0, 0, 0)
|
||||||
|
time.sleep(0.05)
|
||||||
|
finally:
|
||||||
|
send(0x56, 0, 0x0002, 0)
|
||||||
|
send(0x11, 0, 0x0002, 0)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc
|
raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc
|
||||||
|
|
||||||
logger.debug("WinAutoPaste: Ctrl+V выполнен")
|
logger.debug("WinAutoPaste: Ctrl+V выполнен (keybd_event)")
|
||||||
|
|
|
||||||
|
|
@ -243,6 +243,7 @@ class SettingsWindow:
|
||||||
tabs.pack(fill="both", expand=True, padx=12, pady=12)
|
tabs.pack(fill="both", expand=True, padx=12, pady=12)
|
||||||
|
|
||||||
general_tab = tabs.add("Общие")
|
general_tab = tabs.add("Общие")
|
||||||
|
styles_tab = tabs.add("Стили")
|
||||||
sound_tab = tabs.add("Звук")
|
sound_tab = tabs.add("Звук")
|
||||||
dictionary_tab = tabs.add("Словарь")
|
dictionary_tab = tabs.add("Словарь")
|
||||||
stats_tab = tabs.add("Статистика")
|
stats_tab = tabs.add("Статистика")
|
||||||
|
|
@ -250,6 +251,7 @@ class SettingsWindow:
|
||||||
about_tab = tabs.add("О проекте")
|
about_tab = tabs.add("О проекте")
|
||||||
|
|
||||||
self._build_general_tab(general_tab, config)
|
self._build_general_tab(general_tab, config)
|
||||||
|
self._build_styles_tab(styles_tab, config)
|
||||||
self._build_sound_tab(sound_tab, config)
|
self._build_sound_tab(sound_tab, config)
|
||||||
self._build_dictionary_tab(dictionary_tab)
|
self._build_dictionary_tab(dictionary_tab)
|
||||||
self._build_stats_tab(stats_tab)
|
self._build_stats_tab(stats_tab)
|
||||||
|
|
@ -346,6 +348,59 @@ class SettingsWindow:
|
||||||
row=row, column=0, columnspan=2, pady=14
|
row=row, column=0, columnspan=2, pady=14
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _build_styles_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
||||||
|
from voice_dictation.core.config import Config, SummaryPreset
|
||||||
|
|
||||||
|
assert isinstance(config, Config)
|
||||||
|
ctk.CTkLabel(
|
||||||
|
parent,
|
||||||
|
text="Редактируйте режимы и добавляйте свои. Пустой промпт — без обработки.",
|
||||||
|
wraplength=660,
|
||||||
|
).pack(fill="x", padx=8, pady=8)
|
||||||
|
scroll = ctk.CTkScrollableFrame(parent)
|
||||||
|
scroll.pack(fill="both", expand=True, padx=8, pady=4)
|
||||||
|
slots: list[tuple[ctk.StringVar, ctk.StringVar, ctk.CTkTextbox]] = []
|
||||||
|
for index in range(len(config.summary_presets) + 6):
|
||||||
|
preset = (
|
||||||
|
config.summary_presets[index]
|
||||||
|
if index < len(config.summary_presets)
|
||||||
|
else SummaryPreset("", "gpt-4o-mini", "")
|
||||||
|
)
|
||||||
|
ctk.CTkLabel(scroll, text=f"Стиль {index + 1}: название / модель").pack(anchor="w")
|
||||||
|
name = ctk.StringVar(value=preset.name)
|
||||||
|
model = ctk.StringVar(value=preset.model)
|
||||||
|
ctk.CTkEntry(scroll, textvariable=name).pack(fill="x", pady=2)
|
||||||
|
ctk.CTkEntry(scroll, textvariable=model).pack(fill="x", pady=2)
|
||||||
|
prompt = ctk.CTkTextbox(scroll, height=70, wrap="word")
|
||||||
|
prompt.pack(fill="x", pady=(2, 8))
|
||||||
|
prompt.insert("1.0", preset.prompt)
|
||||||
|
slots.append((name, model, prompt))
|
||||||
|
|
||||||
|
def _save_styles() -> None:
|
||||||
|
presets = [
|
||||||
|
SummaryPreset(
|
||||||
|
name.get().strip(), model.get().strip(), prompt.get("1.0", "end").strip()
|
||||||
|
)
|
||||||
|
for name, model, prompt in slots
|
||||||
|
if name.get().strip()
|
||||||
|
]
|
||||||
|
if not presets or len({preset.name for preset in presets}) != len(presets):
|
||||||
|
self._toast("Нужен хотя бы один стиль; названия должны быть уникальными.")
|
||||||
|
return
|
||||||
|
current = self._config_store.current()
|
||||||
|
active = current.active_preset
|
||||||
|
# Preserve selection when an existing style is renamed in its slot.
|
||||||
|
for index, preset in enumerate(config.summary_presets):
|
||||||
|
if preset.name == active and slots[index][0].get().strip():
|
||||||
|
active = slots[index][0].get().strip()
|
||||||
|
break
|
||||||
|
if active not in {preset.name for preset in presets}:
|
||||||
|
active = presets[0].name
|
||||||
|
self._config_store.save(replace(current, summary_presets=presets, active_preset=active))
|
||||||
|
self._toast("Стили сохранены. Доступны в меню трея.")
|
||||||
|
|
||||||
|
ctk.CTkButton(parent, text="Сохранить стили", command=_save_styles).pack(pady=10)
|
||||||
|
|
||||||
def _build_sound_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
def _build_sound_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
||||||
from voice_dictation.core.config import Config
|
from voice_dictation.core.config import Config
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -117,3 +117,45 @@ def test_load_corrupted_json_returns_defaults(tmp_paths: AppPaths) -> None:
|
||||||
store = ConfigStore(tmp_paths.config_file)
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
config = store.load()
|
config = store.load()
|
||||||
assert config.hotkey == "cmd+alt+d"
|
assert config.hotkey == "cmd+alt+d"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", ["raw", "summary", "translate_en", "email", "custom:Мой"])
|
||||||
|
def test_windows_modes_migrate_and_round_trip(tmp_path: Path, mode: str) -> None:
|
||||||
|
"""Upgrading and saving preserves legacy prompts, model, and selected mode."""
|
||||||
|
from voice_dictation.core.modes import DEFAULT_MODES
|
||||||
|
|
||||||
|
path = tmp_path / "config.json"
|
||||||
|
path.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"mode": mode,
|
||||||
|
"proc_model": "my-model",
|
||||||
|
"custom_modes": {"Мой": "Keep all facts", "Деловое письмо": "Custom collision"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
store = ConfigStore(path)
|
||||||
|
config = store.load()
|
||||||
|
expected = (
|
||||||
|
"Мой"
|
||||||
|
if mode == "custom:Мой"
|
||||||
|
else next(spec.label for spec in DEFAULT_MODES if spec.key == mode)
|
||||||
|
)
|
||||||
|
assert config.active_preset == expected
|
||||||
|
assert len(config.summary_presets) == len(DEFAULT_MODES) + 2
|
||||||
|
assert config.summary_presets[-1].name != "Деловое письмо"
|
||||||
|
assert config.summary_presets[-1].prompt == "Custom collision"
|
||||||
|
assert all(p.model == "my-model" for p in config.summary_presets if p.prompt)
|
||||||
|
store.save(config)
|
||||||
|
assert ConfigStore(path).load() == config
|
||||||
|
|
||||||
|
|
||||||
|
def test_older_summary_toggle_migrates(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "config.json"
|
||||||
|
path.write_text('{"summary_mode": true, "summary_model": "legacy-model"}')
|
||||||
|
config = ConfigStore(path).load()
|
||||||
|
assert config.active_preset == "Summary (структурировать)"
|
||||||
|
assert (
|
||||||
|
next(p for p in config.summary_presets if p.name == config.active_preset).model
|
||||||
|
== "legacy-model"
|
||||||
|
)
|
||||||
|
|
|
||||||
35
tests/unit/test_windows_compat.py
Normal file
35
tests/unit/test_windows_compat.py
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
"""Cross-platform checks of Windows compatibility contracts."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
def test_downloaded_ffmpeg_is_discovered(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
from voice_dictation.core import compressor
|
||||||
|
from voice_dictation.core.ffmpeg_setup import _EXE_NAME
|
||||||
|
|
||||||
|
helper = tmp_path / ".dictate" / "bin" / _EXE_NAME
|
||||||
|
helper.parent.mkdir(parents=True)
|
||||||
|
helper.write_text("helper")
|
||||||
|
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||||
|
assert compressor._find_ffmpeg() == str(helper)
|
||||||
|
|
||||||
|
|
||||||
|
def test_autopaste_releases_hotkey_modifiers(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
from voice_dictation.platform.windows import autopaste
|
||||||
|
|
||||||
|
events: list[tuple[int, int, int, int]] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
autopaste.ctypes,
|
||||||
|
"windll",
|
||||||
|
SimpleNamespace(user32=SimpleNamespace(keybd_event=lambda *args: events.append(args))),
|
||||||
|
raising=False,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(autopaste.time, "sleep", lambda _: None)
|
||||||
|
autopaste.WinAutoPaste().paste()
|
||||||
|
assert events[:4] == [(key, 0, 2, 0) for key in (0x11, 0x12, 0x10, 0x20)]
|
||||||
|
assert events[4:] == [(0x11, 0, 0, 0), (0x56, 0, 0, 0), (0x56, 0, 2, 0), (0x11, 0, 2, 0)]
|
||||||
Loading…
Reference in a new issue