from __future__ import annotations import json from pathlib import Path from typing import Iterable def read_json(path: str | Path): return json.loads(Path(path).read_text(encoding="utf-8")) def write_json(path: str | Path, value) -> None: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) target.write_text( json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) def read_jsonl(path: str | Path) -> list[dict]: rows = [] with Path(path).open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, 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 def write_jsonl(path: str | Path, rows: Iterable[dict]) -> None: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) temporary = target.with_suffix(target.suffix + ".tmp") with temporary.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") temporary.replace(target) def append_jsonl(path: str | Path, row: dict) -> None: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) with target.open("a", encoding="utf-8") as handle: handle.write(json.dumps(row, ensure_ascii=False) + "\n") def metadata_path(dataset_root: str | Path) -> Path: return Path(dataset_root) / "data" / "test" / "metadata.jsonl" def image_path(dataset_root: str | Path, row: dict) -> Path: return Path(dataset_root) / "data" / "test" / row["file_name"]