From 037ee8165a75c6c7cf3d2b008333713a991bb574 Mon Sep 17 00:00:00 2001 From: Vickenty Zherebov Date: Tue, 20 Oct 2026 11:45:49 +0300 Subject: [PATCH] Expose cloud model selection and support GPT Transcribe --- CONTRIBUTING.md | 4 +- docs/beta-testing.md | 20 ++++ src/voice_dictation/__init__.py | 2 +- src/voice_dictation/core/enums.py | 1 + src/voice_dictation/core/orchestrator.py | 12 ++- src/voice_dictation/core/pricing.py | 1 + src/voice_dictation/core/transcriber.py | 40 +++++++- src/voice_dictation/ui/recognition_tab.py | 86 ++++++++++++----- src/voice_dictation/ui/settings_window.py | 11 --- tests/unit/test_orchestrator.py | 40 ++++++++ tests/unit/test_pricing.py | 4 + tests/unit/test_transcriber.py | 110 ++++++++++++++++++++++ 12 files changed, 286 insertions(+), 45 deletions(-) create mode 100644 tests/unit/test_transcriber.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4953673..2e99c2f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,9 +46,9 @@ Actions включены для репозитория. До первого ус ## Изолированная macOS beta -Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b2`). +Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b3`). Метаданные пакета и macOS bundle берут версию оттуда; CFBundleShortVersionString -содержит `0.3.0`, CFBundleVersion — `0.3.0.2`. +содержит `0.3.0`, CFBundleVersion — `0.3.0.3`. ```bash # В собственной .venv; не менять venv работающей установки. diff --git a/docs/beta-testing.md b/docs/beta-testing.md index 8e396b9..d4a6669 100644 --- a/docs/beta-testing.md +++ b/docs/beta-testing.md @@ -46,6 +46,26 @@ Windows-совместимость проверена unit-тестами, на требует отдельной проверки. Base — компактный вариант для запуска, не победитель сравнения качества. GigaAM сравним отдельно на тех же записях с эталоном человека. +## Выбор облачной модели + +Во вкладке «Распознавание» выберите OpenAI API: здесь же выбирается облачная +модель. Для локального режима показан отдельный список скачиваемых моделей. +В «Общих» больше нет второго выбора облачной модели. Сохранение действует +для следующей записи; уже начатая запись использует свой снимок настроек. + +Добавлен gpt-transcribe: стоимость оценивается по $0.0045 за минуту, +языковая подсказка передаётся через languages[], а прежние модели продолжают +использовать language. Выбранная ранее облачная модель автоматически не меняется. +Новые запросы проверены синтетическими HTTP-ответами; доступность модели на +реальном аккаунте и качество требуют отдельного облачного теста по выбору пользователя. + +OpenAI объявил отключение whisper-1, gpt-4o-transcribe, +gpt-4o-mini-transcribe и gpt-4o-transcribe-diarize 26 февраля 2027 года. +[Официальное объявление](https://developers.openai.com/api/docs/deprecations#2026-08-26-transcription-models). +Для готовых записей рекомендован gpt-transcribe; gpt-live-transcribe относится +к отдельному сценарию распознавания живого потока и в бету не добавлен. +[Выбор сценария](https://developers.openai.com/api/docs/guides/transcription). + ## Экспериментальный GigaAM В списке моделей добавлены GigaAM v3 E2E CTC и Multilingual Large CTC. diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index 4df067f..766a09d 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.3.0b2" +__version__ = "0.3.0b3" diff --git a/src/voice_dictation/core/enums.py b/src/voice_dictation/core/enums.py index b325d1a..64bcd8b 100644 --- a/src/voice_dictation/core/enums.py +++ b/src/voice_dictation/core/enums.py @@ -25,6 +25,7 @@ class SoundKind(Enum): class WhisperModel(StrEnum): """Доступные модели транскрипции Whisper API.""" + GPT_TRANSCRIBE = "gpt-transcribe" WHISPER_1 = "whisper-1" GPT_4O_TRANSCRIBE = "gpt-4o-transcribe" GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe" diff --git a/src/voice_dictation/core/orchestrator.py b/src/voice_dictation/core/orchestrator.py index b17fb5c..4752f31 100644 --- a/src/voice_dictation/core/orchestrator.py +++ b/src/voice_dictation/core/orchestrator.py @@ -457,14 +457,18 @@ class DictationOrchestrator: self._session_store.complete(session_dir, stitch.text, stitch.removed_prefix_words) self._cleanup_successful_session(session_dir, archive_path) + if effective_model == "gpt-transcribe": + languages = {result.language for result in results} + detected_language = next(iter(languages)) if len(languages) == 1 else None + else: + detected_language = next( + (result.language for result in results if result.language), config.language + ) return TranscriptionResult( text=stitch.text, duration_sec=recording.duration_sec, model=effective_model, - language=next( - (result.language for result in results if result.language), - config.language, - ), + language=detected_language, prompt_used=base_prompt or None, requested_at=min( (result.requested_at for result in results), diff --git a/src/voice_dictation/core/pricing.py b/src/voice_dictation/core/pricing.py index 0361c75..e7e6326 100644 --- a/src/voice_dictation/core/pricing.py +++ b/src/voice_dictation/core/pricing.py @@ -17,6 +17,7 @@ class PriceCalculator: PRICES_PER_MINUTE: Final[Mapping[str, Decimal]] = MappingProxyType( { + "gpt-transcribe": Decimal("0.0045"), "gpt-4o-mini-transcribe": Decimal("0.003"), "gpt-4o-transcribe": Decimal("0.006"), "whisper-1": Decimal("0.006"), diff --git a/src/voice_dictation/core/transcriber.py b/src/voice_dictation/core/transcriber.py index c331778..1edf836 100644 --- a/src/voice_dictation/core/transcriber.py +++ b/src/voice_dictation/core/transcriber.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import math import wave from datetime import UTC, datetime from decimal import Decimal @@ -153,7 +154,8 @@ class WhisperTranscriber: "response_format": response_format, } if language: - data["language"] = language + # GPT-Transcribe uses repeated multipart languages[] hints. + data["languages[]" if model == "gpt-transcribe" else "language"] = language if prompt: data["prompt"] = prompt @@ -183,14 +185,42 @@ class WhisperTranscriber: except Exception as exc: raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc - text: str = body.get("text", "").strip() - api_duration = float(body.get("duration", 0.0)) - duration_sec: float = ( + if not isinstance(body, dict) or not isinstance(body.get("text"), str): + raise TranscriptionError("Невалидная структура ответа транскрипции") + text = body["text"].strip() + duration_value: object = body.get("duration", 0.0) + if model == "gpt-transcribe": + usage = body.get("usage") + if isinstance(usage, dict) and usage.get("type") == "duration": + duration_value = usage.get("seconds", 0.0) + if ( + isinstance(duration_value, bool) + or not isinstance(duration_value, (float, int)) + or not math.isfinite(duration_value) + or duration_value < 0 + ): + raise TranscriptionError("Невалидная длительность в ответе транскрипции") + api_duration = float(duration_value) + duration_sec = ( api_duration or (duration_hint if duration_hint and duration_hint > 0 else 0.0) or _wav_duration(audio_path) ) - detected_language: str | None = body.get("language") or language + detected_language: str | None + if model == "gpt-transcribe": + detected = body.get("languages", []) + if not isinstance(detected, list) or any( + not isinstance(item, dict) + or not isinstance(item.get("code"), str) + or not item["code"].strip() + for item in detected + ): + raise TranscriptionError("Невалидные языки в ответе транскрипции") + # The current result schema is singular: do not misrepresent multiple + # detected languages, an empty array or a requested hint as detection. + detected_language = detected[0]["code"] if len(detected) == 1 else None + else: + detected_language = body.get("language") or language cost = PriceCalculator.cost(model, duration_sec) diff --git a/src/voice_dictation/ui/recognition_tab.py b/src/voice_dictation/ui/recognition_tab.py index b9e4298..2d1a992 100644 --- a/src/voice_dictation/ui/recognition_tab.py +++ b/src/voice_dictation/ui/recognition_tab.py @@ -15,6 +15,8 @@ from voice_dictation.core.config import ConfigStore from voice_dictation.core.model_manager import CATALOG, DownloadCancelled, ModelError, ModelManager from voice_dictation.core.paths import AppPaths +CLOUD_MODELS = ("gpt-transcribe", "gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1") + def build_recognition_tab( parent: ctk.CTkFrame, @@ -34,27 +36,63 @@ def build_recognition_tab( ) selected = ctk.StringVar(value=initial_label) ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4)) - ctk.CTkOptionMenu(parent, values=["Локально", "OpenAI API"], variable=backend).pack( - anchor="w", padx=12 - ) - ctk.CTkLabel( + backend_menu = ctk.CTkOptionMenu( parent, - text="Локально: аудио и текст не отправляются в облако.\n" - "Облачные стили обработки отключены. Наш сервер — в следующем этапе.", + values=["Локально", "OpenAI API"], + variable=backend, + command=lambda _: show_backend(), + ) + backend_menu.pack(anchor="w", padx=12) + privacy = ctk.CTkLabel(parent, text="", justify="left", wraplength=620) + privacy.pack(anchor="w", padx=12, pady=8) + engine_area = ctk.CTkFrame(parent, fg_color="transparent") + engine_area.pack(fill="both", expand=True) + cloud_frame = ctk.CTkFrame(engine_area, fg_color="transparent") + cloud_model = ctk.StringVar(value=config.model) + cloud_values = list(CLOUD_MODELS) + if config.model not in cloud_values: + cloud_values.append(config.model) + ctk.CTkLabel(cloud_frame, text="Модель OpenAI:").pack(anchor="w", padx=12, pady=6) + cloud_menu = ctk.CTkOptionMenu( + cloud_frame, values=cloud_values, variable=cloud_model, width=460 + ) + cloud_menu.pack(anchor="w", padx=12, pady=6) + ctk.CTkLabel( + cloud_frame, + text="gpt-transcribe — новая рекомендуемая модель для аудиофайлов.\n" + "Прежние модели будут отключены 26.02.2027.\n" + "Сохранённая модель меняется только по вашему выбору.", justify="left", wraplength=620, ).pack(anchor="w", padx=12, pady=8) + local_frame = ctk.CTkFrame(engine_area, fg_color="transparent") + + def show_backend() -> None: + local_frame.pack_forget() + cloud_frame.pack_forget() + if backend.get() == "Локально": + local_frame.pack(fill="both", expand=True) + privacy.configure( + text="Локально: аудио и текст не отправляются в облако.\n" + "Облачные стили обработки отключены." + ) + else: + cloud_frame.pack(fill="both", expand=True) + privacy.configure( + text="OpenAI API: запись отправляется в OpenAI для распознавания.\n" + "Выбранные облачные стили могут также отправлять текст на обработку." + ) + ctk.CTkLabel( - parent, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):" + local_frame, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):" ).pack(anchor="w", padx=12) - ctk.CTkOptionMenu(parent, values=list(labels), variable=selected, width=460).pack( - anchor="w", padx=12, pady=6 - ) + local_menu = ctk.CTkOptionMenu(local_frame, values=list(labels), variable=selected, width=460) + local_menu.pack(anchor="w", padx=12, pady=6) status = ctk.CTkLabel( - parent, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620 + local_frame, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620 ) status.pack(anchor="w", padx=12, pady=6) - bar = ctk.CTkProgressBar(parent, width=460) + bar = ctk.CTkProgressBar(local_frame, width=460) bar.set(0) bar.pack(anchor="w", padx=12, pady=6) events: queue.Queue[tuple[str, float]] = queue.Queue() @@ -66,7 +104,7 @@ def build_recognition_tab( last_update = 0.0 buttons: list[ctk.CTkButton] = [] - journal = ctk.CTkTextbox(parent, width=620, height=100) + journal = ctk.CTkTextbox(local_frame, width=620, height=100) journal.pack(anchor="w", padx=12, pady=6) journal.configure(state="disabled") @@ -138,8 +176,8 @@ def build_recognition_tab( last_update = 0.0 cancel.clear() cancel_button.configure(state="normal" if action == "download" else "disabled") - for button in buttons: - button.configure(state="disabled") + for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button): + control.configure(state="disabled") message = { "check": "Проверяю модель…", "download": "Подготавливаю загрузку…", @@ -177,13 +215,13 @@ def build_recognition_tab( status.configure(text=message) bar.set(max(0, value)) busy = False - for button in buttons: - button.configure(state="normal") + for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button): + control.configure(state="normal") except queue.Empty: pass parent.after(100, poll) - row = ctk.CTkFrame(parent, fg_color="transparent") + row = ctk.CTkFrame(local_frame, fg_color="transparent") row.pack(anchor="w", padx=12, pady=6) for title, action in [("Скачать", "download"), ("Проверить", "check"), ("Удалить", "delete")]: button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a)) @@ -204,6 +242,8 @@ def build_recognition_tab( cancel_button.pack(side="left") def save() -> None: + if busy: + return if backend.get() == "Локально" and labels[selected.get()].startswith("gigaam-"): from voice_dictation.core.gigaam_transcriber import runtime_python from voice_dictation.infrastructure.errors import TranscriptionError @@ -217,15 +257,15 @@ def build_recognition_tab( store.load(), transcription_backend="local" if backend.get() == "Локально" else "openai", local_model=labels[selected.get()], + model=cloud_model.get(), ) store.save(updated) toast("Сохранено. Новый режим применяется к следующей записи.") - ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save).pack( - anchor="w", padx=12, pady=12 - ) + save_button = ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save) + save_button.pack(anchor="w", padx=12, pady=12) ctk.CTkLabel( - parent, + local_frame, text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}", justify="left", wraplength=620, @@ -234,3 +274,5 @@ def build_recognition_tab( "", lambda event: cancel.set() if event.widget == parent else None, add="+" ) parent.after(100, poll) + + show_backend() diff --git a/src/voice_dictation/ui/settings_window.py b/src/voice_dictation/ui/settings_window.py index bcf5962..d2dd89c 100644 --- a/src/voice_dictation/ui/settings_window.py +++ b/src/voice_dictation/ui/settings_window.py @@ -23,7 +23,6 @@ if TYPE_CHECKING: _HOTKEY_PRESETS = ["cmd+space", "cmd+shift+space", "cmd+alt+d", "cmd+shift+d", "ctrl+alt+d"] -_MODELS = ["gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1"] _LANGUAGES = ["ru", "en", "auto"] _ABOUT_TEXT = """Voice Dictation — голосовая диктовка под macOS / Windows. @@ -288,15 +287,6 @@ class SettingsWindow: hotkey_box = ctk.CTkComboBox(parent, values=_HOTKEY_PRESETS, variable=hotkey_var, width=240) hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8) - row += 1 - ctk.CTkLabel(parent, text="Модель OpenAI:").grid( - row=row, column=0, sticky="w", padx=8, pady=8 - ) - model_var = ctk.StringVar(value=config.model) - ctk.CTkComboBox(parent, values=_MODELS, variable=model_var, width=240).grid( - row=row, column=1, sticky="w", padx=8, pady=8 - ) - row += 1 ctk.CTkLabel(parent, text="Язык:").grid(row=row, column=0, sticky="w", padx=8, pady=8) language_var = ctk.StringVar(value=config.language or "auto") @@ -365,7 +355,6 @@ class SettingsWindow: updated = replace( current, hotkey=new_hotkey, - model=model_var.get(), language=None if language_choice == "auto" else language_choice, notifications_enabled=notif_var.get(), show_cost_in_notification=cost_var.get(), diff --git a/tests/unit/test_orchestrator.py b/tests/unit/test_orchestrator.py index 0a60d75..7764232 100644 --- a/tests/unit/test_orchestrator.py +++ b/tests/unit/test_orchestrator.py @@ -5,6 +5,8 @@ from __future__ import annotations import time from pathlib import Path +import pytest + from tests.fakes.fake_components import ( FakeAutoPaste, FakeClipboard, @@ -398,3 +400,41 @@ def test_unavailable_audio_directory_does_not_start_or_fallback(tmp_paths, tmp_p assert orchestrator.state == RecordingState.IDLE assert not list(tmp_paths.sessions_dir.glob("*/source.wav")) orchestrator.shutdown() + + +@pytest.mark.parametrize( + ("model", "languages", "expected"), + [ + ("gpt-transcribe", ["ru", "ru", "ru"], "ru"), + ("gpt-transcribe", ["ru", None, "ru"], None), + ("gpt-transcribe", ["ru", "en", "ru"], None), + ("gpt-transcribe", [None, None, None], None), + ("gpt-4o-mini-transcribe", [None, None, None], "ru"), + ("gpt-4o-mini-transcribe", [None, "en", "ru"], "en"), + ], +) +def test_chunk_language_aggregation_preserves_unknown_and_legacy( + tmp_paths, monkeypatch, model, languages, expected +): + from dataclasses import replace + + from voice_dictation.core.models import RecordingResult + + transcriber = FakeTranscriber() + original = transcriber.transcribe + detected = iter(languages) + + def respond(*args, **kwargs): + return replace(original(*args, **kwargs), language=next(detected)) + + monkeypatch.setattr(transcriber, "transcribe", respond) + config = Config(model=model, language="ru", chunk_duration_sec=3, chunk_overlap_sec=1) + orchestrator = _make_orchestrator( + tmp_paths, transcriber=transcriber, config=config, compressor=_FakeChunkCompressor() + ) + audio = orchestrator._session_store.create() + audio.write_bytes(b"synthetic") + result = orchestrator._transcribe_session(RecordingResult(audio, 7), config) + assert result.language == expected + assert len(transcriber.calls) == 3 + orchestrator.shutdown() diff --git a/tests/unit/test_pricing.py b/tests/unit/test_pricing.py index e31285b..84c2c4d 100644 --- a/tests/unit/test_pricing.py +++ b/tests/unit/test_pricing.py @@ -60,3 +60,7 @@ def test_prices_immutable() -> None: """PRICES_PER_MINUTE нельзя изменить (MappingProxyType).""" with pytest.raises(TypeError): PriceCalculator.PRICES_PER_MINUTE["new-model"] = Decimal("1.0") # type: ignore[index] + + +def test_gpt_transcribe_one_minute(): + assert PriceCalculator.cost("gpt-transcribe", 60) == Decimal("0.004500") diff --git a/tests/unit/test_transcriber.py b/tests/unit/test_transcriber.py new file mode 100644 index 0000000..af3bd5d --- /dev/null +++ b/tests/unit/test_transcriber.py @@ -0,0 +1,110 @@ +"""HTTP contracts with synthetic bytes and MockTransport only.""" + +from __future__ import annotations + +from decimal import Decimal + +import httpx +import pytest + +from voice_dictation.core.transcriber import WhisperTranscriber +from voice_dictation.infrastructure.errors import TranscriptionError + + +def _engine(payload, model="gpt-transcribe"): + requests = [] + + def respond(request): + requests.append(request.read()) + return httpx.Response(200, json=payload) + + engine = WhisperTranscriber("synthetic-key", model=model) + engine._client.close() + engine._client = httpx.Client(transport=httpx.MockTransport(respond)) + return engine, requests + + +def test_gpt_transcribe_multipart_language_and_duration_price(tmp_path): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic audio placeholder") + engine, requests = _engine( + { + "text": " Test ", + "languages": [{"code": "ru"}], + "usage": {"type": "duration", "seconds": 60.0}, + } + ) + try: + result = engine.transcribe(audio, language="ru", prompt="domain context", duration_sec=20) + finally: + engine.close() + body = requests[0] + assert b'name="languages[]"\r\n\r\nru' in body + assert b'name="language"' not in body + assert b'name="keywords[]"' not in body + assert b'name="prompt"\r\n\r\ndomain context' in body + assert b'name="response_format"\r\n\r\njson' in body + assert result.text == "Test" + assert result.language == "ru" + assert result.duration_sec == 60 + assert result.cost_usd == Decimal("0.004500") + + +@pytest.mark.parametrize("model", ["whisper-1", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"]) +def test_existing_models_keep_singular_language(tmp_path, model): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, requests = _engine({"text": "test"}, model=model) + try: + result = engine.transcribe(audio, language="ru", duration_sec=60) + finally: + engine.close() + assert b'name="language"\r\n\r\nru' in requests[0] + assert b'name="languages[]"' not in requests[0] + assert result.language == "ru" + expected = Decimal("0.003000") if model == "gpt-4o-mini-transcribe" else Decimal("0.006000") + assert result.cost_usd == expected + + +@pytest.mark.parametrize("languages", [[], [{"code": "ru"}, {"code": "en"}]]) +def test_language_hint_is_not_reported_as_detected(tmp_path, languages): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, _ = _engine({"text": "text", "languages": languages}) + try: + assert engine.transcribe(audio, language="ru", duration_sec=1).language is None + finally: + engine.close() + + +@pytest.mark.parametrize( + "payload", + [ + [], + {"text": None}, + {"text": "x", "languages": ["ru"]}, + {"text": "x", "usage": {"type": "duration", "seconds": True}}, + ], +) +def test_invalid_response_rejected(tmp_path, payload): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, _ = _engine(payload) + try: + with pytest.raises(TranscriptionError): + engine.transcribe(audio) + finally: + engine.close() + + +def test_auto_language_omits_hints_and_uses_audio_duration_hint(tmp_path): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, requests = _engine({"text": "test", "languages": []}) + try: + result = engine.transcribe(audio, language=None, duration_sec=30) + finally: + engine.close() + assert b'name="languages[]"' not in requests[0] + assert result.duration_sec == 30 + assert result.cost_usd == Decimal("0.002250")