#!/usr/bin/env python3 """Reference Exact-lines / Exact CLS / CER scoring. Matches SimdPaddleOCR BenchSummary: https://github.com/sdcb/SimdPaddleOCR/blob/master/test/Sdcb.SimdPaddleOCR.Tests/BenchSummary.cs Predictions file: either { "img-001.jpg": ["line a", "line b"], ... } { "img-001.jpg": { "texts": [...], "rotations": [...], "boxes": [...] }, ... } or a SimdPaddleOCR bench JSON with rows[].file / rows[].texts / rows[].rotations / rows[].warmup. """ from __future__ import annotations import argparse import json from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True) class GtLine: text: str cls_degrees: int bbox: list[int] @dataclass class PredLine: text: str rotation: int | None box: list[float] | None def levenshtein(a: str, b: str) -> int: if a == b: return 0 if not a: return len(b) if not b: return len(a) previous = list(range(len(b) + 1)) current = [0] * (len(b) + 1) for i, ca in enumerate(a, start=1): current[0] = i for j, cb in enumerate(b, start=1): substitute = previous[j - 1] + (0 if ca == cb else 1) current[j] = min(previous[j] + 1, current[j - 1] + 1, substitute) previous, current = current, previous return previous[len(b)] def aabb_iou(ax0: float, ay0: float, ax1: float, ay1: float, bx0: float, by0: float, bx1: float, by1: float) -> float: ix0, iy0 = max(ax0, bx0), max(ay0, by0) ix1, iy1 = min(ax1, bx1), min(ay1, by1) iw, ih = ix1 - ix0, iy1 - iy0 if iw <= 0 or ih <= 0: return 0.0 inter = iw * ih area_a = max(0.0, ax1 - ax0) * max(0.0, ay1 - ay0) area_b = max(0.0, bx1 - bx0) * max(0.0, by1 - by0) union = area_a + area_b - inter return inter / union if union > 0 else 0.0 def load_ground_truth(metadata_path: Path) -> dict[str, list[GtLine]]: meta = json.loads(metadata_path.read_text(encoding="utf-8")) out: dict[str, list[GtLine]] = {} for image in meta["images"]: lines: list[GtLine] = [] for line in image["lines"]: cls = int(line["cls_degrees"]) if cls not in (0, 180): raise ValueError(f"{image['file']} cls_degrees must be 0 or 180, got {cls}") bbox = [int(v) for v in line["bbox"]] if len(bbox) < 4: raise ValueError(f"{image['file']} bbox must have 4 values") lines.append(GtLine(line["text"], cls, bbox)) out[image["file"]] = lines return out def _as_int_list(value, expected: int) -> list[int | None]: if value is None: return [None] * expected items = list(value) if len(items) != expected: raise ValueError(f"expected {expected} rotations, got {len(items)}") return [None if v is None else int(v) for v in items] def _as_box_list(value, expected: int) -> list[list[float] | None]: if value is None: return [None] * expected items = list(value) if len(items) != expected: raise ValueError(f"expected {expected} boxes, got {len(items)}") boxes: list[list[float] | None] = [] for item in items: if item is None: boxes.append(None) continue box = [float(v) for v in item] boxes.append(box if len(box) >= 4 else None) return boxes def _pred_lines_from_value(value) -> list[PredLine]: if isinstance(value, dict): texts = list(value.get("texts") or []) rotations = _as_int_list(value.get("rotations"), len(texts)) boxes = _as_box_list(value.get("boxes"), len(texts)) return [PredLine(texts[i], rotations[i], boxes[i]) for i in range(len(texts))] texts = list(value) return [PredLine(text, None, None) for text in texts] def load_predictions(path: Path) -> dict[str, list[PredLine]]: payload = json.loads(path.read_text(encoding="utf-8")) if isinstance(payload, dict) and "rows" in payload: predicted: dict[str, list[PredLine]] = {} for row in payload["rows"]: if row.get("warmup"): continue file = row.get("file") if not file: continue texts = list(row.get("texts") or []) rotations = _as_int_list(row.get("rotations"), len(texts)) boxes = _as_box_list(row.get("boxes"), len(texts)) predicted[file] = [PredLine(texts[i], rotations[i], boxes[i]) for i in range(len(texts))] return predicted if not isinstance(payload, dict): raise ValueError("predictions must be an object or a bench JSON with rows") return {key: _pred_lines_from_value(value) for key, value in payload.items()} def score_text(gt_lines: list[GtLine], pred_lines: list[PredLine]) -> tuple[int, int, int, bool]: remaining = [p.text for p in pred_lines] exact = errors = 0 image_exact = True for expected in gt_lines: if expected.text in remaining: remaining.remove(expected.text) exact += 1 continue image_exact = False best = len(expected.text) for actual in remaining: best = min(best, levenshtein(expected.text, actual)) errors += best return exact, errors, sum(len(g.text) for g in gt_lines), image_exact def score_cls(gt_lines: list[GtLine], pred_lines: list[PredLine]) -> tuple[int, int]: if not gt_lines or not pred_lines: return 0, 0 if all(p.rotation is None for p in pred_lines): return 0, 0 use_boxes = any(p.box is not None and len(p.box) >= 4 for p in pred_lines) and any( g.bbox[2] > g.bbox[0] and g.bbox[3] > g.bbox[1] for g in gt_lines ) if use_boxes: pairs: list[tuple[int, int, float]] = [] for gi, g in enumerate(gt_lines): for pi, p in enumerate(pred_lines): if p.box is None or len(p.box) < 4: continue iou = aabb_iou(g.bbox[0], g.bbox[1], g.bbox[2], g.bbox[3], p.box[0], p.box[1], p.box[2], p.box[3]) if iou >= 0.3: pairs.append((gi, pi, iou)) pairs.sort(key=lambda item: item[2], reverse=True) gt_used = [False] * len(gt_lines) pred_used = [False] * len(pred_lines) correct = total = 0 for gi, pi, _ in pairs: if gt_used[gi] or pred_used[pi]: continue gt_used[gi] = pred_used[pi] = True total += 1 if pred_lines[pi].rotation == gt_lines[gi].cls_degrees: correct += 1 return correct, total remaining = list(pred_lines) correct = total = 0 for gt in gt_lines: index = next((i for i, p in enumerate(remaining) if p.text == gt.text), -1) if index < 0: continue total += 1 if remaining[index].rotation == gt.cls_degrees: correct += 1 remaining.pop(index) return correct, total def score(ground_truth: dict[str, list[GtLine]], predicted: dict[str, list[PredLine]]) -> dict: exact_lines = 0 total_lines = 0 exact_images = 0 images = 0 errors = 0 total_chars = 0 exact_cls = 0 cls_total = 0 for file, gt_lines in ground_truth.items(): if file not in predicted: continue pred_lines = predicted[file] images += 1 exact, image_errors, chars, image_exact = score_text(gt_lines, pred_lines) exact_lines += exact total_lines += len(gt_lines) errors += image_errors total_chars += chars if image_exact: exact_images += 1 correct, total = score_cls(gt_lines, pred_lines) exact_cls += correct cls_total += total cer = (errors / total_chars) if total_chars else 0.0 return { "exact_lines": exact_lines, "total_lines": total_lines, "exact_line_rate": exact_lines / total_lines if total_lines else 0.0, "exact_cls": exact_cls, "cls_total": cls_total, "exact_cls_rate": exact_cls / cls_total if cls_total else 0.0, "cer": cer, "char_acc": 1.0 - cer, "exact_img": exact_images, "images": images, "errors": errors, "total_chars": total_chars, } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("predictions", type=Path, help="JSON map or bench JSON") parser.add_argument( "--metadata", type=Path, default=Path(__file__).resolve().parents[1] / "dataset" / "metadata.json", ) args = parser.parse_args() result = score(load_ground_truth(args.metadata), load_predictions(args.predictions)) cls = ( f"exact_cls={result['exact_cls']}/{result['cls_total']} " f"({result['exact_cls_rate'] * 100:.2f}%) " if result["cls_total"] else "exact_cls=n/a (no rotations) " ) print( f"exact_lines={result['exact_lines']}/{result['total_lines']} " f"({result['exact_line_rate'] * 100:.2f}%) " f"{cls}" f"CER={result['cer'] * 100:.2f}% " f"char_acc={result['char_acc'] * 100:.2f}% " f"exact_img={result['exact_img']}/{result['images']}" ) return 0 if __name__ == "__main__": raise SystemExit(main())