from __future__ import annotations import hashlib import json from datetime import datetime from pathlib import Path from zoneinfo import ZoneInfo def canonical(value) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False) def digest(value) -> str: return hashlib.sha256(canonical(value).encode()).hexdigest() def file_hash(path) -> str: h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def now() -> str: return datetime.now(ZoneInfo("Asia/Taipei")).isoformat() def read_json(path): return json.loads(Path(path).read_text(encoding="utf-8")) def save_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8") temporary.replace(path) def append_jsonl(path, value): with Path(path).open("a", encoding="utf-8") as f: f.write(canonical(value) + "\n") f.flush()