File size: 5,470 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
111
112
"""LOOPGUARD-1 prep: det_eval-style page files (1280-px page copies, reference line boxes and texts) for the held-out page sets,
built by the UNCHANGED functions of CODE/src/linedet/det_prep.py (imported, not copied or edited):
  school --split test : det_prep._work over annotations_test.json, the loop of det_prep.run_school for ONE split (run_school
                        itself hard-codes ('train', 'val')), page file <out>/pages_school_test.tsv
  gen    --split test : det_prep.run_gen('test', <out>), page file <out>/pages_gen_test.tsv
  valcheck            : rebuilds the VALIDATION page files of both kinds into a scratch folder with the same code path and
                        compares every column except 'image' (which holds the output folder) with the stored
                        DATA/data/processed/r5_linedet_det/{school2,gen}/pages_*_val.tsv; writes --report JSON.
Prints counts only, never text.

usage: lg_det_prep.py school|gen --split test --out DIR [--workers 16]
       lg_det_prep.py valcheck --out SCRATCH --report JSON [--workers 16]
"""
import argparse
import csv
import json
import multiprocessing as mp
import os
import sys
import zipfile

CODE = "/path/to/TURKIC_OCR_CODE"
sys.path.insert(0, CODE + "/src")
from linedet import det_prep as DP  # noqa: E402
from linedet.common import DATA, write_tsv  # noqa: E402

csv.field_size_limit(10 ** 9)
HEADER = ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"]


def run_school_split(split, out_root, workers):
    """det_prep.run_school's body for one split (same jobs, same _work, same rows, same columns)"""
    z = zipfile.ZipFile(DP.SCHOOL + "/images.zip")
    DP._NAMES_LOWER = {n.lower(): n for n in z.namelist() if not n.startswith("__MACOSX")}
    z.close()
    d = json.load(open("%s/annotations_%s.json" % (DP.SCHOOL, split), encoding="utf-8"))
    cats = {c["id"]: c["name"] for c in d["categories"]}
    traces, words = {}, {}
    for a in d["annotations"]:
        cn = cats[a["category_id"]]
        if cn == "text_line":
            traces.setdefault(a["image_id"], []).append(a["segmentation"])
        elif cn in ("pupil_text", "pupil_comment", "teacher_comment"):
            tr = (a.get("attributes") or {}).get("translation")
            if tr:
                words.setdefault(a["image_id"], []).append((DP._poly(a["segmentation"]).tolist(), tr))
    jobs = [(split, im, traces.get(im["id"], []), words.get(im["id"], []), out_root) for im in d["images"]]
    with mp.Pool(workers, initializer=DP._init_zip) as pool:
        res = pool.map(DP._work, jobs, chunksize=4)
    ok = [r for r in res if "error" not in r]
    err = [r for r in res if "error" in r]
    rows = [(r["id"], r["image"], r["width"], r["height"], "%.6f" % r["scale"], len(r["boxes"]), json.dumps(r["boxes"]), json.dumps(r["polys"]),
             json.dumps(r["baselines"]), json.dumps(r["ref_lines"], ensure_ascii=False), r["note"]) for r in ok]
    os.makedirs(out_root, exist_ok=True)
    write_tsv("%s/pages_school_%s.tsv" % (out_root, split), HEADER, rows)
    tot = {k: sum(r["stats"][k] for r in ok) for k in ("traces", "traces_without_words", "loose_word_lines", "loose_words")}
    summary = {"pages": len(ok), "errors": len(err), "size_mismatch_notes": sum(1 for r in ok if r["note"]),
               "lines_kept": sum(len(r["boxes"]) for r in ok), **tot}
    json.dump({split: summary}, open("%s/school_build_summary_%s.json" % (out_root, split), "w"), indent=1)
    print("school", split, summary, flush=True)
    return summary


def read(p):
    with open(p, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


def compare(mine, stored):
    A, B = read(mine), read(stored)
    out = {"rows_mine": len(A), "rows_stored": len(B), "ids_equal_in_order": [r["id"] for r in A] == [r["id"] for r in B]}
    diff = {}
    for ra, rb in zip(A, B):
        for k in HEADER:
            if k == "image":
                continue
            if ra.get(k) != rb.get(k):
                diff[k] = diff.get(k, 0) + 1
    out["differing_cells_by_column"] = diff
    out["equal_except_image_column"] = out["ids_equal_in_order"] and len(A) == len(B) and not diff
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("what", choices=["school", "gen", "valcheck"])
    ap.add_argument("--split", default="test")
    ap.add_argument("--out", required=True)
    ap.add_argument("--report", default="")
    ap.add_argument("--workers", type=int, default=16)
    a = ap.parse_args()
    if a.what == "school":
        s = run_school_split(a.split, a.out, a.workers)
        return 0 if s["errors"] == 0 else 2
    if a.what == "gen":
        DP.run_gen(a.split, a.out, a.workers)
        return 0
    stored = DATA + "/data/processed/r5_linedet_det"
    rep = {}
    run_school_split("val", a.out + "/school2", a.workers)
    rep["school_val"] = compare(a.out + "/school2/pages_school_val.tsv", stored + "/school2/pages_school_val.tsv")
    DP.run_gen("val", a.out + "/gen", a.workers)
    rep["gen_val"] = compare(a.out + "/gen/pages_gen_val.tsv", stored + "/gen/pages_gen_val.tsv")
    rep["passed"] = all(v["equal_except_image_column"] for v in rep.values())
    json.dump(rep, open(a.report, "w"), indent=1)
    print(json.dumps(rep), flush=True)
    return 0 if rep["passed"] else 2


if __name__ == "__main__":
    sys.exit(main())