"""Per-connection STT settings, validated as a whole before any of them change.""" from __future__ import annotations from dataclasses import asdict, dataclass, fields @dataclass class SttSettings: partials: bool = True partial_interval_ms: int = 400 end_silence_ms: int = 300 final_beam: int = 2 language: str | None = "ko" hotwords: tuple[str, ...] = () def update(self, changes: dict) -> None: """Apply ``changes``; raises ValueError and changes nothing if any value is bad.""" names = {f.name for f in fields(self)} staged = asdict(self) for key, value in changes.items(): if key not in names: raise ValueError(f"unknown STT setting: {key}") staged[key] = _check(key, value) for key, value in staged.items(): setattr(self, key, value) def as_dict(self) -> dict: d = asdict(self) d["hotwords"] = list(self.hotwords) return d def _int_in(key: str, value, lo: int, hi: int) -> int: if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi: raise ValueError(f"{key} must be an integer in {lo}-{hi}") return value def _check(key: str, value): if key == "partials": if not isinstance(value, bool): raise ValueError("partials must be true or false") return value if key == "partial_interval_ms": return _int_in(key, value, 100, 5000) if key == "end_silence_ms": return _int_in(key, value, 100, 2000) if key == "final_beam": return _int_in(key, value, 1, 5) if key == "language": if value is not None and (not isinstance(value, str) or not 2 <= len(value) <= 8): raise ValueError("language must be a language code or null") return value if key == "hotwords": if (not isinstance(value, (list, tuple)) or len(value) > 50 or not all(isinstance(w, str) and 0 < len(w) <= 64 for w in value)): raise ValueError("hotwords must be a list of up to 50 short strings") return tuple(value) raise ValueError(f"unknown STT setting: {key}") # pragma: no cover