Add first-launch setup and profile-scoped API key entry
This commit is contained in:
parent
037ee8165a
commit
206f155c2c
9 changed files with 274 additions and 4 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -68,3 +68,7 @@ recordings/
|
||||||
|
|
||||||
# Also ignore an optional local environment symlink
|
# Also ignore an optional local environment symlink
|
||||||
.venv
|
.venv
|
||||||
|
|
||||||
|
# Private user credentials
|
||||||
|
credentials.json
|
||||||
|
.credentials-*
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.3.0b3"
|
__version__ = "0.3.0b4"
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,15 @@ def main() -> None:
|
||||||
transcribe_main(sys.argv[2:])
|
transcribe_main(sys.argv[2:])
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "setup":
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.ui.setup_wizard import run_setup
|
||||||
|
|
||||||
|
setup_paths = AppPaths.default().ensure_exists()
|
||||||
|
run_setup(setup_paths.root, ConfigStore(setup_paths.config_file))
|
||||||
|
return
|
||||||
|
|
||||||
if len(sys.argv) > 1 and sys.argv[1] == "settings":
|
if len(sys.argv) > 1 and sys.argv[1] == "settings":
|
||||||
from voice_dictation.ui.settings_cli import main as settings_main
|
from voice_dictation.ui.settings_cli import main as settings_main
|
||||||
|
|
||||||
|
|
@ -77,6 +86,14 @@ def main() -> None:
|
||||||
config.hotkey = "cmd+alt+shift+d"
|
config.hotkey = "cmd+alt+shift+d"
|
||||||
config.splash_enabled = False
|
config.splash_enabled = False
|
||||||
config_store.save(config)
|
config_store.save(config)
|
||||||
|
if not (paths.root / "setup-complete").exists():
|
||||||
|
from voice_dictation.ui.setup_wizard import run_setup
|
||||||
|
|
||||||
|
if not run_setup(paths.root, config_store):
|
||||||
|
lock.release()
|
||||||
|
return
|
||||||
|
config = config_store.load()
|
||||||
|
env = load_env()
|
||||||
logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model)
|
logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model)
|
||||||
|
|
||||||
if config.splash_enabled:
|
if config.splash_enabled:
|
||||||
|
|
|
||||||
|
|
@ -68,12 +68,14 @@ class RoutingTranscriber:
|
||||||
raise TranscriptionError(str(exc)) from exc
|
raise TranscriptionError(str(exc)) from exc
|
||||||
else:
|
else:
|
||||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
|
from voice_dictation.infrastructure.credentials import read_api_key
|
||||||
|
|
||||||
if not self._api_key:
|
api_key = read_api_key(self._models_dir.parent) or self._api_key
|
||||||
|
if not api_key:
|
||||||
raise TranscriptionError(
|
raise TranscriptionError(
|
||||||
"Для OpenAI укажите OPENAI_API_KEY или выберите локальный режим"
|
"Для OpenAI укажите OPENAI_API_KEY или выберите локальный режим"
|
||||||
)
|
)
|
||||||
engine = WhisperTranscriber(api_key=self._api_key, model=model)
|
engine = WhisperTranscriber(api_key=api_key, model=model)
|
||||||
try:
|
try:
|
||||||
return engine.transcribe(audio_path, prompt, language, model, duration_sec)
|
return engine.transcribe(audio_path, prompt, language, model, duration_sec)
|
||||||
finally:
|
finally:
|
||||||
|
|
|
||||||
34
src/voice_dictation/infrastructure/credentials.py
Normal file
34
src/voice_dictation/infrastructure/credentials.py
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
"""Profile-scoped API credentials, separate from exported preferences."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def read_api_key(root: Path) -> str:
|
||||||
|
"""Read a saved key without logging its contents."""
|
||||||
|
try:
|
||||||
|
data = json.loads((root / "credentials.json").read_text())
|
||||||
|
value = data.get("openai_api_key", "") if isinstance(data, dict) else ""
|
||||||
|
return value if isinstance(value, str) else ""
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def save_api_key(root: Path, key: str) -> None:
|
||||||
|
"""Atomically save a private credentials file (0600 on POSIX)."""
|
||||||
|
key = key.strip()
|
||||||
|
if not key or any(char.isspace() for char in key):
|
||||||
|
raise ValueError("Введите ключ без пробелов и переносов строк")
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, name = tempfile.mkstemp(prefix=".credentials-", dir=root)
|
||||||
|
temporary = Path(name)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w") as stream:
|
||||||
|
json.dump({"openai_api_key": key}, stream)
|
||||||
|
temporary.replace(root / "credentials.json")
|
||||||
|
finally:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
|
@ -54,7 +54,9 @@ def load_env() -> EnvConfig:
|
||||||
# .env не найден — используем существующие переменные окружения
|
# .env не найден — используем существующие переменные окружения
|
||||||
pass
|
pass
|
||||||
|
|
||||||
api_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
from voice_dictation.infrastructure.credentials import read_api_key
|
||||||
|
|
||||||
|
api_key = read_api_key(AppPaths.default().root) or os.environ.get("OPENAI_API_KEY", "").strip()
|
||||||
admin_key = os.environ.get("OPENAI_ADMIN_API_KEY", "").strip() or None
|
admin_key = os.environ.get("OPENAI_ADMIN_API_KEY", "").strip() or None
|
||||||
|
|
||||||
return EnvConfig(api_key=api_key, admin_api_key=admin_key)
|
return EnvConfig(api_key=api_key, admin_api_key=admin_key)
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,50 @@ def build_recognition_tab(
|
||||||
justify="left",
|
justify="left",
|
||||||
wraplength=620,
|
wraplength=620,
|
||||||
).pack(anchor="w", padx=12, pady=8)
|
).pack(anchor="w", padx=12, pady=8)
|
||||||
|
from voice_dictation.infrastructure.credentials import read_api_key, save_api_key
|
||||||
|
|
||||||
|
key_entry = ctk.CTkEntry(cloud_frame, show="•", width=460, placeholder_text="OpenAI API-ключ")
|
||||||
|
key_entry.pack(anchor="w", padx=12, pady=4)
|
||||||
|
key_status = ctk.CTkLabel(
|
||||||
|
cloud_frame,
|
||||||
|
text="Ключ сохранён"
|
||||||
|
if read_api_key(paths.root)
|
||||||
|
else "Ключ можно вставить здесь (или использовать прежний .env).",
|
||||||
|
)
|
||||||
|
key_status.pack(anchor="w", padx=12)
|
||||||
|
|
||||||
|
def save_key() -> None:
|
||||||
|
try:
|
||||||
|
save_api_key(paths.root, key_entry.get())
|
||||||
|
except (ValueError, OSError):
|
||||||
|
key_status.configure(
|
||||||
|
text="Не удалось сохранить ключ. Проверьте ввод и доступ к профилю."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
key_entry.delete(0, "end")
|
||||||
|
key_status.configure(
|
||||||
|
text="Ключ сохранён. Распознавание использует его со следующей записи."
|
||||||
|
)
|
||||||
|
|
||||||
|
ctk.CTkButton(cloud_frame, text="Сохранить API-ключ", command=save_key).pack(
|
||||||
|
anchor="w", padx=12, pady=4
|
||||||
|
)
|
||||||
|
|
||||||
|
def open_setup() -> None:
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
args = (
|
||||||
|
[sys.executable, "setup"]
|
||||||
|
if getattr(sys, "frozen", False)
|
||||||
|
else [sys.executable, "-m", "voice_dictation", "setup"]
|
||||||
|
)
|
||||||
|
subprocess.Popen(args, start_new_session=True)
|
||||||
|
toast("После изменения хоткея в мастере перезапустите приложение.")
|
||||||
|
|
||||||
|
ctk.CTkButton(parent, text="Мастер настройки", command=open_setup).pack(
|
||||||
|
anchor="w", padx=12, pady=4
|
||||||
|
)
|
||||||
local_frame = ctk.CTkFrame(engine_area, fg_color="transparent")
|
local_frame = ctk.CTkFrame(engine_area, fg_color="transparent")
|
||||||
|
|
||||||
def show_backend() -> None:
|
def show_backend() -> None:
|
||||||
|
|
|
||||||
133
src/voice_dictation/ui/setup_wizard.py
Normal file
133
src/voice_dictation/ui/setup_wizard.py
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
"""Interactive first-launch setup; never sends audio or validates keys online."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
from voice_dictation.infrastructure.credentials import read_api_key, save_api_key
|
||||||
|
|
||||||
|
|
||||||
|
def run_setup(root: Path, store: ConfigStore) -> bool:
|
||||||
|
"""Show setup before tray startup; return whether the user finished it."""
|
||||||
|
window = ctk.CTk()
|
||||||
|
window.title("Voice Dictation — первый запуск")
|
||||||
|
window.geometry("720x650")
|
||||||
|
from voice_dictation.ui.settings_window import _activate_app
|
||||||
|
|
||||||
|
_activate_app()
|
||||||
|
content = ctk.CTkScrollableFrame(window)
|
||||||
|
content.pack(fill="both", expand=True)
|
||||||
|
completed = False
|
||||||
|
config = store.load()
|
||||||
|
ctk.CTkLabel(content, text="Настроим диктовку", font=("Arial", 23)).pack(pady=12)
|
||||||
|
ctk.CTkLabel(content, text="1. Где распознавать запись?").pack()
|
||||||
|
backend = ctk.StringVar(
|
||||||
|
value="Локально" if config.transcription_backend == "local" else "OpenAI API"
|
||||||
|
)
|
||||||
|
ctk.CTkOptionMenu(content, values=["Локально", "OpenAI API"], variable=backend).pack(pady=6)
|
||||||
|
ctk.CTkLabel(content, text="OpenAI API-ключ (для локального режима не нужен):").pack()
|
||||||
|
key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь")
|
||||||
|
key.pack(pady=6)
|
||||||
|
ctk.CTkLabel(
|
||||||
|
content,
|
||||||
|
text="Ключ сохраняется отдельно в вашем профиле с правами 0600.\n"
|
||||||
|
"Пустое поле оставляет прежний ключ. Проверки через интернет здесь нет.",
|
||||||
|
).pack()
|
||||||
|
ctk.CTkLabel(content, text="2. Разрешения macOS: микрофон и Универсальный доступ").pack(
|
||||||
|
pady=(16, 4)
|
||||||
|
)
|
||||||
|
status = ctk.CTkLabel(content, text="")
|
||||||
|
status.pack()
|
||||||
|
|
||||||
|
def refresh() -> None:
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
from ApplicationServices import AXIsProcessTrusted
|
||||||
|
|
||||||
|
access = "разрешено" if AXIsProcessTrusted() else "нет доступа"
|
||||||
|
status.configure(
|
||||||
|
text=f"Управление клавиатурой: {access}\n"
|
||||||
|
"Микрофон проверяется отдельной кнопкой ниже."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
status.configure(text="Разрешите микрофон в настройках конфиденциальности Windows.")
|
||||||
|
|
||||||
|
def permissions(section: str) -> None:
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
subprocess.Popen(
|
||||||
|
[
|
||||||
|
"/usr/bin/open",
|
||||||
|
f"x-apple.systempreferences:com.apple.preference.security?Privacy_{section}",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
elif sys.platform == "win32":
|
||||||
|
subprocess.Popen(["explorer.exe", "ms-settings:privacy-microphone"])
|
||||||
|
|
||||||
|
def test_microphone() -> None:
|
||||||
|
import sounddevice as sd
|
||||||
|
|
||||||
|
try:
|
||||||
|
with sd.InputStream(samplerate=16000, channels=1) as stream:
|
||||||
|
stream.read(1600)
|
||||||
|
status.configure(text="Микрофон: запись доступна. Аудио не сохранено и не отправлено.")
|
||||||
|
except Exception:
|
||||||
|
status.configure(
|
||||||
|
text="Нет доступа к микрофону или устройство недоступно. Проверьте разрешения."
|
||||||
|
)
|
||||||
|
|
||||||
|
ctk.CTkButton(content, text="Проверить микрофон", command=test_microphone).pack(pady=4)
|
||||||
|
ctk.CTkButton(
|
||||||
|
content, text="Открыть Универсальный доступ", command=lambda: permissions("Accessibility")
|
||||||
|
).pack(pady=4)
|
||||||
|
ctk.CTkButton(
|
||||||
|
content, text="Открыть настройки микрофона", command=lambda: permissions("Microphone")
|
||||||
|
).pack(pady=4)
|
||||||
|
ctk.CTkButton(content, text="Проверить разрешения снова", command=refresh).pack(pady=4)
|
||||||
|
ctk.CTkLabel(content, text="3. Хоткей (⌘Space часто занят Spotlight)").pack(pady=(12, 4))
|
||||||
|
hotkey = ctk.CTkEntry(content, width=400)
|
||||||
|
hotkey.insert(0, config.hotkey)
|
||||||
|
hotkey.pack()
|
||||||
|
message = ctk.CTkLabel(
|
||||||
|
content,
|
||||||
|
text="После запуска: хоткей → фраза → хоткей → проверьте вставку.\n"
|
||||||
|
"Локальную модель можно скачать в Настройки → Распознавание.",
|
||||||
|
wraplength=650,
|
||||||
|
)
|
||||||
|
message.pack(pady=10)
|
||||||
|
|
||||||
|
def finish() -> None:
|
||||||
|
nonlocal completed
|
||||||
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
|
||||||
|
try:
|
||||||
|
from pynput.keyboard import HotKey
|
||||||
|
|
||||||
|
combination = hotkey.get().strip().lower()
|
||||||
|
HotKey.parse(
|
||||||
|
"+".join(f"<{part}>" if len(part) > 1 else part for part in combination.split("+"))
|
||||||
|
)
|
||||||
|
if "+" not in combination:
|
||||||
|
raise ValueError("Укажите сочетание клавиш, например cmd+alt+d")
|
||||||
|
if key.get().strip():
|
||||||
|
save_api_key(root, key.get())
|
||||||
|
if backend.get() == "OpenAI API" and not (read_api_key(root) or load_env().api_key):
|
||||||
|
raise ValueError("Введите OpenAI API-ключ или выберите локальный режим")
|
||||||
|
updated = store.load()
|
||||||
|
updated.transcription_backend = "local" if backend.get() == "Локально" else "openai"
|
||||||
|
updated.hotkey = hotkey.get().strip()
|
||||||
|
store.save(updated)
|
||||||
|
(root / "setup-complete").touch(mode=0o600)
|
||||||
|
except (ValueError, OSError):
|
||||||
|
message.configure(text="Проверьте ключ, сочетание клавиш и доступ к папке профиля.")
|
||||||
|
return
|
||||||
|
completed = True
|
||||||
|
window.destroy()
|
||||||
|
|
||||||
|
ctk.CTkButton(content, text="Сохранить и запустить диктовку", command=finish).pack(pady=8)
|
||||||
|
refresh()
|
||||||
|
window.mainloop()
|
||||||
|
return completed
|
||||||
34
tests/unit/test_credentials.py
Normal file
34
tests/unit/test_credentials.py
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
"""Private profile credentials must not leak into preferences or other profiles."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.credentials import read_api_key, save_api_key
|
||||||
|
|
||||||
|
|
||||||
|
def test_key_roundtrip_private_and_isolated(tmp_path: Path) -> None:
|
||||||
|
beta = tmp_path / "beta"
|
||||||
|
save_api_key(beta, "test-key-not-real")
|
||||||
|
assert read_api_key(beta) == "test-key-not-real"
|
||||||
|
assert read_api_key(tmp_path / "main") == ""
|
||||||
|
if os.name == "posix":
|
||||||
|
assert (beta / "credentials.json").stat().st_mode & 0o777 == 0o600
|
||||||
|
save_api_key(beta, "replacement-not-real")
|
||||||
|
assert read_api_key(beta) == "replacement-not-real"
|
||||||
|
assert not list(beta.glob(".credentials-*"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_key_preserves_previous(tmp_path: Path) -> None:
|
||||||
|
save_api_key(tmp_path, "test-key-not-real")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
save_api_key(tmp_path, "bad key")
|
||||||
|
assert read_api_key(tmp_path) == "test-key-not-real"
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_file_does_not_crash(tmp_path: Path) -> None:
|
||||||
|
(tmp_path / "credentials.json").write_text("[]")
|
||||||
|
assert read_api_key(tmp_path) == ""
|
||||||
Loading…
Reference in a new issue