File size: 5,901 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Showcase, job B step 3 (.venv_kraken): page CERs with linedet.det_eval.page_cers (imported, not copied), the line pairing
for the reading excerpts, and the reproduction check against the earlier page check (DATA/outputs/r5/b1_page_check).

Page CER: reading order = edit distance of the hypothesis lines joined by one space against the reference lines joined by one
space, over the reference characters; order free = lines matched one to one with the Hungarian method on the line edit
distances, unmatched lines counted in full (det_eval M28 / M29). Excerpt pairing: the same Hungarian assignment
(rapidfuzz cdist + scipy linear_sum_assignment, as inside page_cers); wrong characters from Levenshtein.opcodes(hyp, ref).
Typed pages also get the order-free edits split by the class of the matched reference line (print or handwriting).

usage: showcase_score.py --read read.jsonl --pages pages.json --b1pc DIR --out scores.json
"""
import argparse
import glob
import json
import os
import sys

sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
import numpy as np  # noqa: E402
from rapidfuzz import process  # noqa: E402
from rapidfuzz.distance import Levenshtein  # noqa: E402
from scipy.optimize import linear_sum_assignment  # noqa: E402

from linedet.det_eval import page_cers  # noqa: E402

ap = argparse.ArgumentParser()
ap.add_argument("--read", required=True)
ap.add_argument("--pages", required=True)
ap.add_argument("--b1pc", required=True)
ap.add_argument("--typed_report", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()

P = {p["id"]: p for p in json.load(open(a.pages, encoding="utf-8"))["pages"]}
recs = [json.loads(ln) for ln in open(a.read, encoding="utf-8")]
head = recs[0]
recs = [r for r in recs if not r.get("header")]
typed_info = {}
gr = json.load(open(a.typed_report, encoding="utf-8"))
for t in gr.get("typed", []):
    typed_info["pg_val_" + t.get("page_id", "")] = t

prev = {}
for fn in glob.glob(os.path.join(a.b1pc, "*_detB1_c*.jsonl")):
    for ln in open(fn, encoding="utf-8"):
        r = json.loads(ln)
        prev[r["id"]] = r
score_prev = {}
sj = json.load(open(os.path.join(a.b1pc, "score.json"), encoding="utf-8"))
for c in sj["cells"]:
    if c["prompt"] == "detB1":
        for row in c["per_page"]:
            score_prev[row["id"]] = row


def pairs(hyp, ref):
    if not hyp or not ref:
        return {}
    C = process.cdist(hyp, ref, scorer=Levenshtein.distance, dtype=np.int32)
    ri, ci = linear_sum_assignment(C)
    return {int(i): (int(j), int(C[i, j])) for i, j in zip(ri, ci)}


out = dict(header=head, note="validation pages only; timings on ZEN4 CPU cores (see header threads), not a GPU", pages=[])
for r in recs:
    pg = P[r["id"]]
    hyp, ref = r["hyp_lines"], r["ref_lines"]
    ro, of, nref = page_cers(hyp, ref)
    pr = pairs(hyp, ref)
    # excerpt: hypothesis lines in reading order (non-empty), each with its matched reference line and the edit operations
    ex = []
    for i, h in enumerate(hyp):
        j, d = pr.get(i, (None, None))
        rr = ref[j] if j is not None else None
        ops = [[o.tag, o.src_start, o.src_end, o.dest_start, o.dest_end] for o in Levenshtein.opcodes(h, rr)] if rr is not None else None
        ex.append(dict(hyp_index=i, hyp=h, ref_index=j, ref=rr, edits=d, opcodes=ops))
    row = dict(id=r["id"], set=r["set"], lang=r["lang"], kind=pg["kind"], strength=pg["strength"], image=pg["image"], width=pg["width"], height=pg["height"],
               scale=pg["scale"], reading_image_size=r["reading_image_size"], n_ref_lines=len(ref), ref_chars=nref, n_boxes=r["n_boxes"], n_crops=r["n_crops"],
               n_hyp_lines=len(hyp), boxes_used=pg["boxes_used"], det_tp_iou_0_5=pg["det_tp_iou_0_5"], n_gt_boxes=len(pg["gt_boxes"]),
               cpu_vs_stored=pg.get("cpu_vs_stored"), ro_edits=ro, of_edits=of, ro_cer=round(ro / max(nref, 1), 4), of_cer=round(of / max(nref, 1), 4),
               seconds=dict(detector_cpu=pg["det_seconds_cpu"], crop=r["seconds_crop"], read=r["seconds_read"],
                            total=round(pg["det_seconds_cpu"] + r["seconds_crop"] + r["seconds_read"], 2)),
               excerpt=ex, boxes=pg["boxes"], lines=r["lines"])
    ti = typed_info.get(r["id"])
    if ti is not None and ti.get("ref_line_classes"):
        cls = ti["ref_line_classes"]
        by = {}
        matched_ref = {j: (i, d) for i, (j, d) in pr.items()}
        for j, (t, c) in enumerate(zip(ref, cls)):
            e = matched_ref[j][1] if j in matched_ref else len(t)
            b = by.setdefault(c, dict(ref_chars=0, edits=0, lines=0))
            b["ref_chars"] += len(t)
            b["edits"] += e
            b["lines"] += 1
        un_h = sum(len(hyp[i]) for i in range(len(hyp)) if i not in pr)
        for c, b in by.items():
            b["cer"] = round(b["edits"] / max(b["ref_chars"], 1), 4)
        row["order_free_by_reference_class"] = dict(classes=by, unmatched_hypothesis_chars=un_h,
                                                    note="order-free edits of matched reference lines plus unmatched reference lines, split by the reference line's class; unmatched hypothesis characters are not attributed to a class")
    if r["id"] in prev:
        p0 = prev[r["id"]]
        same = sum(1 for x, y in zip(hyp, p0["hyp_lines"]) if x == y)
        row["reproduction"] = dict(previous_file="b1_page_check *_detB1_c*.jsonl", previous_n_lines=len(p0["hyp_lines"]), this_n_lines=len(hyp),
                                   identical_lines_same_position=same, all_identical=hyp == p0["hyp_lines"],
                                   previous_score_row=score_prev.get(r["id"]))
    out["pages"].append(row)
    print(r["id"], "ro %.4f of %.4f" % (row["ro_cer"], row["of_cer"]), "repro" if "reproduction" in row else "", flush=True)
json.dump(out, open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("done", flush=True)