"""Persist a handful of user choices to ~/HVideoTool/settings.json. Slimmed down for the image-inspector tool: it remembers the detector, the model path, the overlay threshold, and the last opened folder. """ from __future__ import annotations import json from pathlib import Path from .config import AppConfig _PATH = Path.home() / "HVideoTool" / "settings.json" def _read() -> dict: try: return json.loads(_PATH.read_text(encoding="utf-8")) except (OSError, ValueError): return {} def _write(data: dict) -> None: _PATH.parent.mkdir(parents=True, exist_ok=True) _PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") def apply(config: AppConfig) -> None: """Overlay persisted settings onto ``config`` (mutates it in place).""" data = _read() if data.get("detector"): config.detector = data["detector"] if "model_path" in data: config.model_path = data["model_path"] if "threshold" in data: config.default_threshold = float(data["threshold"]) if data.get("restorer"): config.restorer = data["restorer"] for key in ("dm_dir", "dm_model", "dm_python", "dm_gpu"): if key in data: setattr(config, key, data[key]) def save(config: AppConfig) -> None: """Persist the configurable settings, preserving other keys (e.g. last_dir).""" data = _read() data.update( detector=config.detector, model_path=config.model_path, threshold=config.default_threshold, restorer=config.restorer, dm_dir=config.dm_dir, dm_model=config.dm_model, dm_python=config.dm_python, dm_gpu=config.dm_gpu, ) _write(data) def last_dir() -> str | None: return _read().get("last_dir") def set_last_dir(path: str) -> None: data = _read() data["last_dir"] = path _write(data)