Datasets:
File size: 4,021 Bytes
551cc83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | #!/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()
|