| 1 | from __future__ import annotations |
| 2 | |
| 3 | import json |
| 4 | from typing import Any |
| 5 | |
| 6 | from helpers import files, plugins |
| 7 | |
| 8 | |
| 9 | PLUGIN_NAME = "_whisper_stt" |
| 10 | LEGACY_SETTINGS_FILE = files.get_abs_path("usr/settings.json") |
| 11 | DEFAULT_CONFIG = { |
| 12 | "model_size": "base", |
| 13 | "language": "en", |
| 14 | "message_mode": "send", |
| 15 | "silence_threshold": 0.3, |
| 16 | "silence_duration": 1000, |
| 17 | "waiting_timeout": 2000, |
| 18 | } |
| 19 | |
| 20 | |
| 21 | def ensure_config_seeded() -> bool: |
| 22 | config_path = get_config_path() |
| 23 | if files.exists(config_path): |
| 24 | return False |
| 25 | |
| 26 | config = build_seed_config(_read_legacy_settings()) |
| 27 | files.write_file(config_path, json.dumps(config, indent=2)) |
| 28 | return True |
| 29 | |
| 30 | |
| 31 | def get_config_path() -> str: |
| 32 | return plugins.determine_plugin_asset_path( |
| 33 | PLUGIN_NAME, "", "", plugins.CONFIG_FILE_NAME |
| 34 | ) |
| 35 | |
| 36 | |
| 37 | def read_saved_config() -> dict[str, Any]: |
| 38 | config_path = get_config_path() |
| 39 | if not files.exists(config_path): |
| 40 | return {} |
| 41 | |
| 42 | try: |
| 43 | return json.loads(files.read_file(config_path)) |
| 44 | except Exception: |
| 45 | return {} |
| 46 | |
| 47 | |
| 48 | def build_seed_config(legacy_settings: dict[str, Any]) -> dict[str, Any]: |
| 49 | seeded = dict(DEFAULT_CONFIG) |
| 50 | |
| 51 | model_size = str( |
| 52 | legacy_settings.get("stt_model_size", seeded["model_size"]) or "" |
| 53 | ).strip() |
| 54 | if model_size: |
| 55 | seeded["model_size"] = model_size |
| 56 | |
| 57 | language = str(legacy_settings.get("stt_language", seeded["language"]) or "").strip() |
| 58 | if language: |
| 59 | seeded["language"] = language |
| 60 | |
| 61 | seeded["silence_threshold"] = _coerce_float( |
| 62 | legacy_settings.get("stt_silence_threshold"), |
| 63 | seeded["silence_threshold"], |
| 64 | ) |
| 65 | seeded["silence_duration"] = _coerce_int( |
| 66 | legacy_settings.get("stt_silence_duration"), |
| 67 | seeded["silence_duration"], |
| 68 | ) |
| 69 | seeded["waiting_timeout"] = _coerce_int( |
| 70 | legacy_settings.get("stt_waiting_timeout"), |
| 71 | seeded["waiting_timeout"], |
| 72 | ) |
| 73 | |
| 74 | return seeded |
| 75 | |
| 76 | |
| 77 | def _read_legacy_settings() -> dict[str, Any]: |
| 78 | if not files.exists(LEGACY_SETTINGS_FILE): |
| 79 | return {} |
| 80 | |
| 81 | try: |
| 82 | return json.loads(files.read_file(LEGACY_SETTINGS_FILE)) |
| 83 | except Exception: |
| 84 | return {} |
| 85 | |
| 86 | |
| 87 | def _coerce_float(value: Any, default: float) -> float: |
| 88 | try: |
| 89 | return float(value) |
| 90 | except (TypeError, ValueError): |
| 91 | return default |
| 92 | |
| 93 | |
| 94 | def _coerce_int(value: Any, default: int) -> int: |
| 95 | try: |
| 96 | return int(value) |
| 97 | except (TypeError, ValueError): |
| 98 | return default |