Expose cloud model selection and support GPT Transcribe
This commit is contained in:
parent
1bb441261d
commit
037ee8165a
12 changed files with 286 additions and 45 deletions
|
|
@ -46,9 +46,9 @@ Actions включены для репозитория. До первого ус
|
||||||
|
|
||||||
## Изолированная macOS beta
|
## Изолированная macOS beta
|
||||||
|
|
||||||
Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b2`).
|
Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b3`).
|
||||||
Метаданные пакета и macOS bundle берут версию оттуда; CFBundleShortVersionString
|
Метаданные пакета и macOS bundle берут версию оттуда; CFBundleShortVersionString
|
||||||
содержит `0.3.0`, CFBundleVersion — `0.3.0.2`.
|
содержит `0.3.0`, CFBundleVersion — `0.3.0.3`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# В собственной .venv; не менять venv работающей установки.
|
# В собственной .venv; не менять venv работающей установки.
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,26 @@ Windows-совместимость проверена unit-тестами, на
|
||||||
требует отдельной проверки. Base — компактный вариант для запуска, не победитель
|
требует отдельной проверки. Base — компактный вариант для запуска, не победитель
|
||||||
сравнения качества. GigaAM сравним отдельно на тех же записях с эталоном человека.
|
сравнения качества. 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
|
||||||
|
|
||||||
В списке моделей добавлены GigaAM v3 E2E CTC и Multilingual Large CTC.
|
В списке моделей добавлены GigaAM v3 E2E CTC и Multilingual Large CTC.
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.3.0b2"
|
__version__ = "0.3.0b3"
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ class SoundKind(Enum):
|
||||||
class WhisperModel(StrEnum):
|
class WhisperModel(StrEnum):
|
||||||
"""Доступные модели транскрипции Whisper API."""
|
"""Доступные модели транскрипции Whisper API."""
|
||||||
|
|
||||||
|
GPT_TRANSCRIBE = "gpt-transcribe"
|
||||||
WHISPER_1 = "whisper-1"
|
WHISPER_1 = "whisper-1"
|
||||||
GPT_4O_TRANSCRIBE = "gpt-4o-transcribe"
|
GPT_4O_TRANSCRIBE = "gpt-4o-transcribe"
|
||||||
GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe"
|
GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe"
|
||||||
|
|
|
||||||
|
|
@ -457,14 +457,18 @@ class DictationOrchestrator:
|
||||||
|
|
||||||
self._session_store.complete(session_dir, stitch.text, stitch.removed_prefix_words)
|
self._session_store.complete(session_dir, stitch.text, stitch.removed_prefix_words)
|
||||||
self._cleanup_successful_session(session_dir, archive_path)
|
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(
|
return TranscriptionResult(
|
||||||
text=stitch.text,
|
text=stitch.text,
|
||||||
duration_sec=recording.duration_sec,
|
duration_sec=recording.duration_sec,
|
||||||
model=effective_model,
|
model=effective_model,
|
||||||
language=next(
|
language=detected_language,
|
||||||
(result.language for result in results if result.language),
|
|
||||||
config.language,
|
|
||||||
),
|
|
||||||
prompt_used=base_prompt or None,
|
prompt_used=base_prompt or None,
|
||||||
requested_at=min(
|
requested_at=min(
|
||||||
(result.requested_at for result in results),
|
(result.requested_at for result in results),
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ class PriceCalculator:
|
||||||
|
|
||||||
PRICES_PER_MINUTE: Final[Mapping[str, Decimal]] = MappingProxyType(
|
PRICES_PER_MINUTE: Final[Mapping[str, Decimal]] = MappingProxyType(
|
||||||
{
|
{
|
||||||
|
"gpt-transcribe": Decimal("0.0045"),
|
||||||
"gpt-4o-mini-transcribe": Decimal("0.003"),
|
"gpt-4o-mini-transcribe": Decimal("0.003"),
|
||||||
"gpt-4o-transcribe": Decimal("0.006"),
|
"gpt-4o-transcribe": Decimal("0.006"),
|
||||||
"whisper-1": Decimal("0.006"),
|
"whisper-1": Decimal("0.006"),
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import math
|
||||||
import wave
|
import wave
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
@ -153,7 +154,8 @@ class WhisperTranscriber:
|
||||||
"response_format": response_format,
|
"response_format": response_format,
|
||||||
}
|
}
|
||||||
if language:
|
if language:
|
||||||
data["language"] = language
|
# GPT-Transcribe uses repeated multipart languages[] hints.
|
||||||
|
data["languages[]" if model == "gpt-transcribe" else "language"] = language
|
||||||
if prompt:
|
if prompt:
|
||||||
data["prompt"] = prompt
|
data["prompt"] = prompt
|
||||||
|
|
||||||
|
|
@ -183,14 +185,42 @@ class WhisperTranscriber:
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc
|
raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc
|
||||||
|
|
||||||
text: str = body.get("text", "").strip()
|
if not isinstance(body, dict) or not isinstance(body.get("text"), str):
|
||||||
api_duration = float(body.get("duration", 0.0))
|
raise TranscriptionError("Невалидная структура ответа транскрипции")
|
||||||
duration_sec: float = (
|
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
|
api_duration
|
||||||
or (duration_hint if duration_hint and duration_hint > 0 else 0.0)
|
or (duration_hint if duration_hint and duration_hint > 0 else 0.0)
|
||||||
or _wav_duration(audio_path)
|
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)
|
cost = PriceCalculator.cost(model, duration_sec)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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.model_manager import CATALOG, DownloadCancelled, ModelError, ModelManager
|
||||||
from voice_dictation.core.paths import AppPaths
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
CLOUD_MODELS = ("gpt-transcribe", "gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1")
|
||||||
|
|
||||||
|
|
||||||
def build_recognition_tab(
|
def build_recognition_tab(
|
||||||
parent: ctk.CTkFrame,
|
parent: ctk.CTkFrame,
|
||||||
|
|
@ -34,27 +36,63 @@ def build_recognition_tab(
|
||||||
)
|
)
|
||||||
selected = ctk.StringVar(value=initial_label)
|
selected = ctk.StringVar(value=initial_label)
|
||||||
ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4))
|
ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4))
|
||||||
ctk.CTkOptionMenu(parent, values=["Локально", "OpenAI API"], variable=backend).pack(
|
backend_menu = ctk.CTkOptionMenu(
|
||||||
anchor="w", padx=12
|
|
||||||
)
|
|
||||||
ctk.CTkLabel(
|
|
||||||
parent,
|
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",
|
justify="left",
|
||||||
wraplength=620,
|
wraplength=620,
|
||||||
).pack(anchor="w", padx=12, pady=8)
|
).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(
|
ctk.CTkLabel(
|
||||||
parent, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):"
|
local_frame, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):"
|
||||||
).pack(anchor="w", padx=12)
|
).pack(anchor="w", padx=12)
|
||||||
ctk.CTkOptionMenu(parent, values=list(labels), variable=selected, width=460).pack(
|
local_menu = ctk.CTkOptionMenu(local_frame, values=list(labels), variable=selected, width=460)
|
||||||
anchor="w", padx=12, pady=6
|
local_menu.pack(anchor="w", padx=12, pady=6)
|
||||||
)
|
|
||||||
status = ctk.CTkLabel(
|
status = ctk.CTkLabel(
|
||||||
parent, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620
|
local_frame, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620
|
||||||
)
|
)
|
||||||
status.pack(anchor="w", padx=12, pady=6)
|
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.set(0)
|
||||||
bar.pack(anchor="w", padx=12, pady=6)
|
bar.pack(anchor="w", padx=12, pady=6)
|
||||||
events: queue.Queue[tuple[str, float]] = queue.Queue()
|
events: queue.Queue[tuple[str, float]] = queue.Queue()
|
||||||
|
|
@ -66,7 +104,7 @@ def build_recognition_tab(
|
||||||
last_update = 0.0
|
last_update = 0.0
|
||||||
buttons: list[ctk.CTkButton] = []
|
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.pack(anchor="w", padx=12, pady=6)
|
||||||
journal.configure(state="disabled")
|
journal.configure(state="disabled")
|
||||||
|
|
||||||
|
|
@ -138,8 +176,8 @@ def build_recognition_tab(
|
||||||
last_update = 0.0
|
last_update = 0.0
|
||||||
cancel.clear()
|
cancel.clear()
|
||||||
cancel_button.configure(state="normal" if action == "download" else "disabled")
|
cancel_button.configure(state="normal" if action == "download" else "disabled")
|
||||||
for button in buttons:
|
for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button):
|
||||||
button.configure(state="disabled")
|
control.configure(state="disabled")
|
||||||
message = {
|
message = {
|
||||||
"check": "Проверяю модель…",
|
"check": "Проверяю модель…",
|
||||||
"download": "Подготавливаю загрузку…",
|
"download": "Подготавливаю загрузку…",
|
||||||
|
|
@ -177,13 +215,13 @@ def build_recognition_tab(
|
||||||
status.configure(text=message)
|
status.configure(text=message)
|
||||||
bar.set(max(0, value))
|
bar.set(max(0, value))
|
||||||
busy = False
|
busy = False
|
||||||
for button in buttons:
|
for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button):
|
||||||
button.configure(state="normal")
|
control.configure(state="normal")
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
pass
|
pass
|
||||||
parent.after(100, poll)
|
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)
|
row.pack(anchor="w", padx=12, pady=6)
|
||||||
for title, action in [("Скачать", "download"), ("Проверить", "check"), ("Удалить", "delete")]:
|
for title, action in [("Скачать", "download"), ("Проверить", "check"), ("Удалить", "delete")]:
|
||||||
button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a))
|
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")
|
cancel_button.pack(side="left")
|
||||||
|
|
||||||
def save() -> None:
|
def save() -> None:
|
||||||
|
if busy:
|
||||||
|
return
|
||||||
if backend.get() == "Локально" and labels[selected.get()].startswith("gigaam-"):
|
if backend.get() == "Локально" and labels[selected.get()].startswith("gigaam-"):
|
||||||
from voice_dictation.core.gigaam_transcriber import runtime_python
|
from voice_dictation.core.gigaam_transcriber import runtime_python
|
||||||
from voice_dictation.infrastructure.errors import TranscriptionError
|
from voice_dictation.infrastructure.errors import TranscriptionError
|
||||||
|
|
@ -217,15 +257,15 @@ def build_recognition_tab(
|
||||||
store.load(),
|
store.load(),
|
||||||
transcription_backend="local" if backend.get() == "Локально" else "openai",
|
transcription_backend="local" if backend.get() == "Локально" else "openai",
|
||||||
local_model=labels[selected.get()],
|
local_model=labels[selected.get()],
|
||||||
|
model=cloud_model.get(),
|
||||||
)
|
)
|
||||||
store.save(updated)
|
store.save(updated)
|
||||||
toast("Сохранено. Новый режим применяется к следующей записи.")
|
toast("Сохранено. Новый режим применяется к следующей записи.")
|
||||||
|
|
||||||
ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save).pack(
|
save_button = ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save)
|
||||||
anchor="w", padx=12, pady=12
|
save_button.pack(anchor="w", padx=12, pady=12)
|
||||||
)
|
|
||||||
ctk.CTkLabel(
|
ctk.CTkLabel(
|
||||||
parent,
|
local_frame,
|
||||||
text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}",
|
text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}",
|
||||||
justify="left",
|
justify="left",
|
||||||
wraplength=620,
|
wraplength=620,
|
||||||
|
|
@ -234,3 +274,5 @@ def build_recognition_tab(
|
||||||
"<Destroy>", lambda event: cancel.set() if event.widget == parent else None, add="+"
|
"<Destroy>", lambda event: cancel.set() if event.widget == parent else None, add="+"
|
||||||
)
|
)
|
||||||
parent.after(100, poll)
|
parent.after(100, poll)
|
||||||
|
|
||||||
|
show_backend()
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,6 @@ if TYPE_CHECKING:
|
||||||
|
|
||||||
|
|
||||||
_HOTKEY_PRESETS = ["cmd+space", "cmd+shift+space", "cmd+alt+d", "cmd+shift+d", "ctrl+alt+d"]
|
_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"]
|
_LANGUAGES = ["ru", "en", "auto"]
|
||||||
|
|
||||||
_ABOUT_TEXT = """Voice Dictation — голосовая диктовка под macOS / Windows.
|
_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 = ctk.CTkComboBox(parent, values=_HOTKEY_PRESETS, variable=hotkey_var, width=240)
|
||||||
hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8)
|
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
|
row += 1
|
||||||
ctk.CTkLabel(parent, text="Язык:").grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
ctk.CTkLabel(parent, text="Язык:").grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
||||||
language_var = ctk.StringVar(value=config.language or "auto")
|
language_var = ctk.StringVar(value=config.language or "auto")
|
||||||
|
|
@ -365,7 +355,6 @@ class SettingsWindow:
|
||||||
updated = replace(
|
updated = replace(
|
||||||
current,
|
current,
|
||||||
hotkey=new_hotkey,
|
hotkey=new_hotkey,
|
||||||
model=model_var.get(),
|
|
||||||
language=None if language_choice == "auto" else language_choice,
|
language=None if language_choice == "auto" else language_choice,
|
||||||
notifications_enabled=notif_var.get(),
|
notifications_enabled=notif_var.get(),
|
||||||
show_cost_in_notification=cost_var.get(),
|
show_cost_in_notification=cost_var.get(),
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,8 @@ from __future__ import annotations
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from tests.fakes.fake_components import (
|
from tests.fakes.fake_components import (
|
||||||
FakeAutoPaste,
|
FakeAutoPaste,
|
||||||
FakeClipboard,
|
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 orchestrator.state == RecordingState.IDLE
|
||||||
assert not list(tmp_paths.sessions_dir.glob("*/source.wav"))
|
assert not list(tmp_paths.sessions_dir.glob("*/source.wav"))
|
||||||
orchestrator.shutdown()
|
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()
|
||||||
|
|
|
||||||
|
|
@ -60,3 +60,7 @@ def test_prices_immutable() -> None:
|
||||||
"""PRICES_PER_MINUTE нельзя изменить (MappingProxyType)."""
|
"""PRICES_PER_MINUTE нельзя изменить (MappingProxyType)."""
|
||||||
with pytest.raises(TypeError):
|
with pytest.raises(TypeError):
|
||||||
PriceCalculator.PRICES_PER_MINUTE["new-model"] = Decimal("1.0") # type: ignore[index]
|
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")
|
||||||
|
|
|
||||||
110
tests/unit/test_transcriber.py
Normal file
110
tests/unit/test_transcriber.py
Normal file
|
|
@ -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")
|
||||||
Loading…
Reference in a new issue