VisSlideBench / eval /run_ocr.py
sabulin's picture
Release VisSlideBench (data, images, evaluation code)
2c76448 verified
Raw History Blame Contribute Delete
3.56 kB
"""Step 1 of Content Faithfulness: OCR every generated slide.
Uses PaddleOCR 3.x (paddleocr==3.3.2 in our runs) and merges detected boxes
into text lines. Output: one text file per case, one recognized line per row.
python eval/run_ocr.py --task t2i --pred_dir outputs/my_model --device gpu:0
"""
import argparse
import os
from pathlib import Path
import numpy as np
from common import bench_path, load_jsonl
def merge_ocr_lines(texts, polys, y_thresh_ratio=0.5, x_gap_ratio=1.2):
"""Group OCR boxes into lines (top to bottom), then join neighbours left to right.
A box joins the first line whose running vertical center is within
0.5 x the mean box height of that line. Inside a line, two neighbours are
joined when the horizontal gap is at most 1.2 x their mean height; a space
is inserted only between two ASCII characters.
"""
items = []
for text, poly in zip(texts, polys):
text = text.strip()
if not text:
continue
poly = np.asarray(poly)
left, right = poly[:, 0].min(), poly[:, 0].max()
top, bottom = poly[:, 1].min(), poly[:, 1].max()
items.append({"text": text, "left": left, "right": right, "height": bottom - top, "cy": (top + bottom) / 2})
items.sort(key=lambda x: x["cy"])
lines = []
for it in items:
for line in lines:
if abs(line["cy"] - it["cy"]) <= np.mean([i["height"] for i in line["items"]]) * y_thresh_ratio:
line["items"].append(it)
line["cy"] = np.mean([i["cy"] for i in line["items"]])
break
else:
lines.append({"cy": it["cy"], "items": [it]})
merged = []
for line in lines:
row = sorted(line["items"], key=lambda x: x["left"])
cur, prev = row[0]["text"], row[0]
for it in row[1:]:
if it["left"] - prev["right"] <= (prev["height"] + it["height"]) / 2 * x_gap_ratio:
cur += (" " if cur[-1].isascii() and it["text"][0].isascii() else "") + it["text"]
else:
merged.append(cur)
cur = it["text"]
prev = it
merged.append(cur)
return merged
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--task", required=True, choices=["t2i", "template", "multi_image"])
ap.add_argument("--pred_dir", required=True, help="Folder with <task>/<id>.png predictions.")
ap.add_argument("--out_dir", default=None, help="Defaults to <pred_dir>/ocr.")
ap.add_argument("--device", default="gpu:0", help="PaddleOCR device, e.g. gpu:0 or cpu.")
args = ap.parse_args()
from paddleocr import PaddleOCR
ocr = PaddleOCR(
device=args.device,
use_doc_orientation_classify=True,
use_doc_unwarping=False,
use_textline_orientation=True,
)
out_dir = Path(args.out_dir or os.path.join(args.pred_dir, "ocr")) / args.task
out_dir.mkdir(parents=True, exist_ok=True)
cases = load_jsonl(bench_path(f"data/{args.task}.jsonl"))
for case in cases:
img = Path(args.pred_dir) / args.task / f"{case['id']}.png"
dst = out_dir / f"{case['id']}.txt"
if not img.exists() or dst.exists():
continue
lines = []
for res in ocr.predict(input=str(img)):
lines += merge_ocr_lines(res.get("rec_texts") or [], res.get("rec_polys") or [])
dst.write_text("\n".join(l for l in lines if l) + "\n", encoding="utf-8")
print(f"OCR written to {out_dir}")
if __name__ == "__main__":
main()