#!/usr/bin/env python3 """Convert per-page prediction JSONs into evaluation CSVs for the benchmark. Each input JSON is a list of {"box": [x1, y1, x2, y2], "text": "..."} items. Each item becomes one CSV row with a unique group_row. Pass --unit-level to match what you will give the evaluator: line — each item is already a complete text line (Surya, most VLMs) word — each item is an individual word """ from __future__ import annotations import argparse import csv import json from pathlib import Path from typing import Any def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--predictions-dir", type=Path, required=True, help="Directory containing per-page prediction JSON files.", ) parser.add_argument( "--output-dir", type=Path, required=True, help="Directory where per-page evaluation CSV files will be written.", ) parser.add_argument( "--unit-level", choices=("line", "word"), default="word", help=( "Granularity of prediction items. Does not change the CSV structure " "(each item always gets its own group_row), but should match the " "--unit-level flag you pass to the evaluator." ), ) parser.add_argument( "--overwrite", action="store_true", help="Overwrite existing output files.", ) return parser.parse_args() def load_predictions(path: Path) -> list[Any]: with path.open("r", encoding="utf-8") as handle: data = json.load(handle) if not isinstance(data, list): raise ValueError(f"{path}: expected a top-level JSON array") return data def item_box(item: Any, *, path: Path, index: int) -> list[float]: if not isinstance(item, dict): raise ValueError(f"{path}: item {index} must be a JSON object") box = item.get("box") if not isinstance(box, (list, tuple)) or len(box) != 4: raise ValueError(f"{path}: item {index} is missing a valid 'box'") try: return [float(v) for v in box] except (TypeError, ValueError) as exc: raise ValueError(f"{path}: item {index} box coordinates must be numeric") from exc def item_text(item: Any) -> str: if isinstance(item, dict): return str(item.get("text", "")) return "" def to_csv_rows(predictions: list[Any], *, path: Path) -> list[dict[str, Any]]: rows = [] for index, item in enumerate(predictions): box = item_box(item, path=path, index=index) rows.append( { "x1": box[0], "y1": box[1], "x2": box[2], "y2": box[3], "group_row": str(index), "text": item_text(item), } ) return rows def write_csv(rows: list[dict[str, Any]], path: Path) -> None: fieldnames = ["x1", "y1", "x2", "y2", "group_row", "text"] with path.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) def main() -> None: args = parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) prediction_files = sorted(args.predictions_dir.glob("*.json")) if not prediction_files: raise FileNotFoundError(f"No JSON files found in {args.predictions_dir}") written = 0 skipped = 0 for pred_path in prediction_files: output_path = args.output_dir / pred_path.with_suffix(".csv").name if output_path.exists() and not args.overwrite: skipped += 1 continue predictions = load_predictions(pred_path) rows = to_csv_rows(predictions, path=pred_path) write_csv(rows, output_path) written += 1 print(f"Wrote {written} evaluation CSV files to {args.output_dir} ({skipped} skipped)") if __name__ == "__main__": main()