"""Voice recordings for checking what was heard and said (voice_worker.spec.md, "Recordings"). Off unless the app sets JARVIS_RECORDINGS_DIR (setting `voice.record`). Each finished utterance and each spoken answer becomes a WAV file in a folder per local day, with one JSON line per file in that day's `index.jsonl` (time, who, text). Day folders older than KEEP_DAYS are removed when the worker starts. Writing happens on a thread of its own and a failure never stops the voice path. """ from __future__ import annotations import json import re import shutil import time import wave from concurrent.futures import ThreadPoolExecutor from datetime import date, timedelta from pathlib import Path import numpy as np from .log import debug_log RECORDINGS_ENV = "JARVIS_RECORDINGS_DIR" KEEP_DAYS = 7 _DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$") def _safe_id(value: str) -> str: return re.sub(r"[^0-9A-Za-z_-]", "_", value)[:40] or "x" class Recorder: def __init__(self, root: str | Path, keep_days: int = KEEP_DAYS, now: float | None = None): self.root = Path(root) self.keep_days = keep_days self.root.mkdir(parents=True, exist_ok=True) self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="recordings") self.purge(time.time() if now is None else now) def purge(self, now: float) -> int: """Remove day folders older than keep_days (by their name, the local day).""" oldest = date.fromtimestamp(now) - timedelta(days=self.keep_days - 1) removed = 0 for d in self.root.iterdir(): if d.is_dir() and _DAY.match(d.name) and date.fromisoformat(d.name) < oldest: shutil.rmtree(d, ignore_errors=True) removed += 1 if removed: debug_log(f"recordings: removed {removed} old day folders", "voice_worker") return removed def said(self, ts: float, speaker: str, name: str, channel: str | None, text: str, audio: np.ndarray, rate: int = 16000) -> None: """A finished utterance: float samples in -1..1 at `rate`, as it was cut for transcription.""" pcm = (np.clip(np.asarray(audio, dtype=np.float32), -1.0, 1.0) * 32767).astype(" None: """A spoken answer: int16 mono samples at `rate`, as far as it was made.""" self._submit(ts, "jarvis", np.asarray(pcm, dtype=" None: self._pool.shutdown(wait=True) def _submit(self, ts: float, tag: str, pcm: np.ndarray, rate: int, entry: dict) -> None: try: self._pool.submit(self._write, ts, tag, pcm.copy(), rate, entry) except RuntimeError: # closed pass def _write(self, ts: float, tag: str, pcm: np.ndarray, rate: int, entry: dict) -> None: try: lt = time.localtime(ts) day = self.root / time.strftime("%Y-%m-%d", lt) day.mkdir(parents=True, exist_ok=True) stem = f"{time.strftime('%H%M%S', lt)}-{int((ts % 1) * 1000):03d}-{tag}" path, n = day / f"{stem}.wav", 1 while path.exists(): n += 1 path = day / f"{stem}-{n}.wav" with wave.open(str(path), "wb") as w: w.setnchannels(1) w.setsampwidth(2) w.setframerate(rate) w.writeframes(pcm.tobytes()) line = {"file": path.name, "at": ts, "ms": len(pcm) * 1000 // rate, **entry} with open(day / "index.jsonl", "a", encoding="utf-8") as f: f.write(json.dumps(line, ensure_ascii=False) + "\n") except Exception as e: # noqa: BLE001 - a recording never stops the voice path debug_log(f"recordings: could not write ({type(e).__name__})", "voice_worker")