from __future__ import annotations import hashlib import json from pathlib import Path from typing import Any, Iterable def canonical_json(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def sha256_json(value: Any) -> str: return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest() def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def read_json(path: Path) -> Any: with path.open(encoding="utf-8") as stream: return json.load(stream) def write_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as stream: json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True) stream.write("\n") def append_jsonl(path: Path, values: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as stream: for value in values: stream.write(canonical_json(value) + "\n") def write_jsonl(path: Path, values: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as stream: for value in values: stream.write(canonical_json(value) + "\n") def read_jsonl(path: Path) -> list[dict[str, Any]]: if not path.exists(): return [] rows = [] with path.open(encoding="utf-8") as stream: for line_number, line in enumerate(stream, start=1): if not line.strip(): continue try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f"Invalid JSONL at {path}:{line_number}: {exc}") from exc return rows