"""启动前清空状态:SQLite、watch 旧 JSON、测量/行为运行时目录。 由 start_fresh.sh 在 uvicorn 之前调用,使 FishMeasure 与 FishAction 均在无缓存下重新推理。 可通过环境变量 KEEP_MEASURE_OUTPUT=1 保留测量输出目录以复用点云。 """ from __future__ import annotations import os from pathlib import Path from app.db import clear_runtime_compute_dirs, remove_sqlite_database_files from app.settings import get_settings def _rm_legacy_json(path: Path | None) -> None: if path is None: return try: if path.is_file(): path.unlink() print(f"[prestart-fresh] removed legacy JSON {path}", flush=True) except OSError as e: print(f"[prestart-fresh] skip {path}: {e}", flush=True) def run_prestart_fresh() -> None: s = get_settings() remove_sqlite_database_files(s) print( f"[prestart-fresh] removed SQLite at {s.sqlite_path} (and -wal/-shm if present).", flush=True, ) # 检查是否保留测量输出目录(用于复用点云) keep_measure_output = os.environ.get("KEEP_MEASURE_OUTPUT", "").strip() in ("1", "true", "yes") if keep_measure_output: # 只清理其他目录,保留 measure_output_root from app.db import _safe_rm_tree _safe_rm_tree(s.action_output_root) _safe_rm_tree(s.media_root) _safe_rm_tree(s.stream_tmp_dir) print( "[prestart-fresh] cleared compute dirs (kept measure_output for cloud reuse): " f"action_output={s.action_output_root}, " f"media={s.media_root}, stream_tmp={s.stream_tmp_dir}", flush=True, ) else: clear_runtime_compute_dirs(s) print( "[prestart-fresh] cleared compute dirs: " f"measure_output={s.measure_output_root}, " f"action_output={s.action_output_root}, " f"media={s.media_root}, stream_tmp={s.stream_tmp_dir}", flush=True, ) if s.measure_watch_use_state_file: if s.measure_watch_state_file is not None: _rm_legacy_json(s.measure_watch_state_file) elif s.measure_watch_dir is not None: _rm_legacy_json( s.measure_watch_dir / ".fishmeasure_watch_processed.json" ) if s.action_watch_use_state_file: if s.action_watch_state_file is not None: _rm_legacy_json(s.action_watch_state_file) elif s.action_watch_dir is not None: _rm_legacy_json( s.action_watch_dir / ".fishaction_watch_processed.json" ) print("[prestart-fresh] done.", flush=True) def main() -> None: run_prestart_fresh() if __name__ == "__main__": main()