turkic-ocr-code / tests_r5eval /test_pages.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
6.87 kB
"""Hand-made tests of the page metrics (detection PRF, M28, M29, M30, M31, LWE) and of score_page_file. usage: python -I test_pages.py
No page prediction from any model exists yet; these cases only fix the definitions."""
import json
import os
import sys
import tempfile
import traceback
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "src"))
from r5eval import pages # noqa: E402
RESULTS = []
def test(fn):
try:
fn()
RESULTS.append((fn.__name__, True))
print("PASS", fn.__name__)
except Exception: # noqa: BLE001
RESULTS.append((fn.__name__, False))
print("FAIL", fn.__name__)
print(traceback.format_exc())
return fn
def L(text, box=None, score=None):
d = {"text": text}
if box:
d["box"] = box
if score is not None:
d["score"] = score
return d
@test
def t_box_iou_and_matching_thresholds():
assert pages.box_iou([0, 0, 10, 10], [0, 0, 10, 10]) == 1.0
assert abs(pages.box_iou([0, 0, 10, 10], [5, 0, 15, 10]) - 50 / 150) < 1e-12
assert pages.box_iou([0, 0, 1, 1], [5, 5, 6, 6]) == 0.0
refs = [L("a", [0, 0, 100, 20]), L("b", [0, 30, 100, 50])]
dets = [L("a", [0, 0, 100, 20], 0.9), L("b", [0, 30, 100, 40], 0.8), L("x", [0, 80, 100, 100], 0.7)] # second det: IoU 0.5 exactly
assert len(pages.match_detections(dets, refs, 0.5)) == 2
assert len(pages.match_detections(dets, refs, 0.75)) == 1
# one-to-one: two detections on the same reference line match once
dets2 = [L("a", [0, 0, 100, 20], 0.9), L("a2", [0, 1, 100, 21], 0.8)]
assert len(pages.match_detections(dets2, refs, 0.5)) == 1
# score order decides who gets the line
dets3 = [L("low", [0, 0, 100, 20], 0.1), L("high", [0, 2, 100, 22], 0.9)]
m = pages.match_detections(dets3, [L("a", [0, 0, 100, 20])], 0.5)
assert m == [(1, 0)]
@test
def t_page_scores_order_and_invention():
ref = [L("аб вг", [0, 0, 50, 10]), L("де жз", [0, 20, 50, 30])]
# same lines, reversed order: M29 zero, M28 not
out = [L("де жз", [0, 20, 50, 30]), L("аб вг", [0, 0, 50, 10])]
f = pages.page_scores(ref, out)
assert f["cost_orderfree"] == 0 and f["dist_ordered"] > 0
assert f["ard_sum"] == 1.0 # both lines are one place off: mean relative distance 1
assert f["tau_sum"] == -1.0
# an invented line is charged in full
out = [L("аб вг"), L("де жз"), L("қҰҚ")]
f = pages.page_scores(ref, out)
assert f["cost_orderfree"] == 3 and f["dist_ordered"] == 4 and f["ref_len_lines"] == 10 and f["ref_len_page"] == 11
# a missing line costs its length
f = pages.page_scores(ref, [L("аб вг")])
assert f["cost_orderfree"] == 5 and f["ard_sum"] == 1.0
# wrappers are stripped from VLM page output, empty lines dropped
f = pages.page_scores(ref, [L("<text>аб вг</text>"), L(" "), L("```\nде жз\n```")])
assert f["cost_orderfree"] == 0 and f["n_out_lines"] == 2
# merged lines
f = pages.page_scores([L("аб"), L("вг")], [L("абвг")])
assert f["cost_orderfree"] == 4
@test
def t_detection_counts_need_boxes_on_both_sides():
ref = [L("a", [0, 0, 100, 20])]
assert "tp_iou50" not in pages.page_scores(ref, [L("a")]) # a pipeline without boxes: text metrics only
f = pages.page_scores(ref, [L("a", [0, 0, 100, 20], 1.0)])
assert f["tp_iou50"] == 1 and f["det_iou50"] == 1 and f["gt_iou50"] == 1 and f["tp_iou75"] == 1
@test
def t_aggregate_pages_ratios():
per = []
for i in range(10):
ref = [L("аб вг", [0, 0, 50, 10]), L("де жз", [0, 20, 50, 30])]
out = [L("аб вг", [0, 0, 50, 10], 0.9), L("де жз", [0, 20, 50, 30], 0.8)] if i % 2 == 0 else [L("аб вг", [0, 0, 50, 10], 0.9)]
per.append(pages.page_scores(ref, out))
m = pages.aggregate_pages(per, B=200)
assert abs(m["page_cer_order_free"]["value"] - (5 * 5) / (10 * 10)) < 1e-12 # five pages miss a 5-character line
assert abs(m["det_precision_iou50"]["value"] - 1.0) < 1e-12 and abs(m["det_recall_iou50"]["value"] - 15 / 20) < 1e-12
assert abs(m["det_f1_iou50"]["value"] - 2 * 15 / (15 + 20)) < 1e-12
assert m["page_cer_order_free"]["lo"] <= m["page_cer_order_free"]["value"] <= m["page_cer_order_free"]["hi"]
assert abs(m["out_to_ref_char_ratio"]["value"] - 0.75) < 1e-12
@test
def t_lwe_amendment_3_1():
r = pages.lwe_page(["кітап", "оқу", "ас"], ["кітап", "оқұ", "xyz", "кітап"]) # "ас" is shorter than 3 characters: left out
assert r["ref_words"] == 2 and r["ref_chars"] == 8
assert r["cost"] == 1.0 and r["exact_words"] == 1 # кітап exact, оқу read as оқұ (one substitution); extra tokens cost nothing
r = pages.lwe_page(["кітап"], ["ж"]) # distance 5 is not smaller than the length 5: counts as unassigned, cost 5
assert r["cost"] == 5.0
r = pages.lwe_page(["кітап"], [])
assert r["cost"] == 5.0 and r["out_chars"] == 0
r = pages.lwe_page(["кітап"], ["кітап" * 10])
assert r["cost"] == 5.0
r = pages.lwe_page(["ас"], ["кітап"])
assert r["ref_words"] == 0 and r["cost"] == 0.0
@test
def t_score_page_file_roundtrip():
d = tempfile.mkdtemp(prefix="r5eval_pages_")
rows = []
preds = []
for i in range(6):
src = os.path.join(d, "pg%d.json" % i)
json.dump({"lines": [{"id": "l1", "text": "бір екі", "box": [0, 0, 80, 10], "polygon": [[0, 0], [80, 0], [80, 10], [0, 10]]},
{"id": "l2", "text": "үш төрт", "box": [0, 20, 80, 30]}]}, open(src, "w", encoding="utf-8"), ensure_ascii=False)
rows.append({"id": "pg%d" % i, "source": src, "unit": "page"})
if i < 5:
preds.append({"page_id": "pg%d" % i, "lines": [{"text": "бір екі", "box": [0, 0, 80, 10], "score": 0.9},
{"text": "үш төрт" if i else "үш төр", "box": [0, 20, 80, 30], "score": 0.8}]})
p = os.path.join(d, "x.jsonl")
with open(p, "w", encoding="utf-8") as f:
for r in preds:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
f.write("not json\n")
res = pages.score_page_file(p, rows, B=100)
assert res["coverage"]["scored_pages"] == 5 and res["coverage"]["missing_pages"] == 1 and res["coverage"]["complete"] is False
assert abs(res["metrics"]["page_cer_order_free"]["value"] - 1 / 70) < 1e-12 or res["metrics"]["page_cer_order_free"]["num"] == 1.0
assert res["metrics"]["det_recall_iou50"]["value"] == 1.0
if __name__ == "__main__":
bad = [r for r in RESULTS if not r[1]]
print("tests: %d passed, %d failed" % (len(RESULTS) - len(bad), len(bad)))
sys.exit(1 if bad else 0)