File size: 5,599 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
# Check 1 from review: are NUMBERED train crops duplicated in validation/test (same ink under two form ids)? Images only, no label file.
# All valid numbered train crops (80,512) against validation+test (34,853), reuse of cached features and the helpers of kohtd_leak_scan.py.
# usage: python -I kohtd_leak_numbered.py <out_dir> <workers>
import collections
import importlib.util
import json
import os
import re
import sys
import time

import numpy as np

t0 = time.time()
spec = importlib.util.spec_from_file_location("leak", "/path/to/TURKIC_OCR_CODE/scripts/kohtd_leak_scan.py")
leak = importlib.util.module_from_spec(spec)
sys.modules["leak"] = leak
spec.loader.exec_module(leak)
OUT, WORKERS = sys.argv[1], int(sys.argv[2])
NAMES = sorted(n for n in os.listdir(leak.IMG) if n.endswith(".jpg"))
leak.NAMES = NAMES
num = re.compile(r"^(\d+)_(\d+)_(\d+)\.jpg$")
grp = np.full(len(NAMES), -1)
form = np.full(len(NAMES), -1)
for i, n in enumerate(NAMES):
    m = num.match(n)
    if m:
        form[i] = int(m.group(1))
        grp[i] = leak.split_of_form(form[i])
    else:
        grp[i] = leak.G_S
z = np.load(os.path.join(OUT, "features.npz"), allow_pickle=True)
W, H, STD, DH, PH, BAD = [z[k] for k in ("W", "H", "STD", "DH", "PH", "BAD")]
AR = (W / np.maximum(H, 1)).astype(np.float32)
valid = (~BAD) & (STD > leak.STD_MIN)
iN = np.where((grp == leak.G_N) & valid)[0]
iV = np.where((grp == leak.G_V) & valid)[0]
iT = np.where((grp == leak.G_T) & valid)[0]
DBi = np.concatenate([iV, iT])
segs = [(0, len(iV)), (len(iV), len(DBi))]
bd, bi, _ = leak.nn(DH[iN], PH[iN], AR[iN], DH[DBi], PH[DBi], AR[DBi], segs)
best_seg = np.where(bd[:, 0] <= bd[:, 1], 0, 1)
d = bd.min(1)
dbk = np.where(best_seg == 0, bi[:, 0], bi[:, 1])
print("matching done", round(time.time() - t0), flush=True)
TE, TH = 0.2091, 0.3751
cand = np.where(d <= TH)[0]
pairs = [(NAMES[DBi[dbk[q]]], NAMES[iN[q]]) for q in cand]
from multiprocessing import Pool
with Pool(WORKERS) as pool:
    ncc = np.array(pool.map(leak.ncc_paths, pairs, chunksize=64))
print("ncc done", len(cand), round(time.time() - t0), flush=True)
res = {"queries_numbered_train_crops": len(iN), "database_val_plus_test": len(DBi), "pairs_hash_le_tau_hard": int(len(cand)), "pairs_hash_le_tau_easy": int((d <= TE).sum()),
       "pairs_hash_le_tau_hard_and_ncc_ge_0.9": int((ncc >= 0.9).sum()), "pairs_hash_le_tau_hard_and_ncc_ge_0.85": int((ncc >= 0.85).sum()), "pairs_hash_le_tau_hard_and_ncc_ge_0.8": int((ncc >= 0.8).sum())}
sel = [k for k in range(len(cand)) if d[cand[k]] <= TE or ncc[k] >= 0.9]
rows = []
for k in sel:
    q = cand[k]
    a, b = NAMES[iN[q]], NAMES[DBi[dbk[q]]]
    rows.append({"train_crop": a, "train_form": int(form[iN[q]]), "train_wxh": [int(W[iN[q]]), int(H[iN[q]])], "vt_crop": b, "vt_form": int(form[DBi[dbk[q]]]), "vt_split": "validation" if best_seg[q] == 0 else "test",
                 "vt_wxh": [int(W[DBi[dbk[q]]]), int(H[DBi[dbk[q]]])], "hash_distance": round(float(d[q]), 4), "ncc": round(float(ncc[k]), 4)})
res["pairs_listed_hash_le_easy_or_ncc_ge_0.9"] = len(rows)
res["of_those_hash_le_easy_and_ncc_ge_0.9"] = int(sum(1 for r in rows if r["hash_distance"] <= TE and r["ncc"] >= 0.9))
gp = collections.Counter((r["train_form"], r["vt_form"]) for r in rows)
res["form_pairs_with_pairs"] = len(gp)
res["max_pairs_on_one_form_pair"] = max(gp.values()) if gp else 0
res["form_pairs_top10"] = [{"train_form": a, "vt_form": b, "n": c} for (a, b), c in gp.most_common(10)]
tf = collections.Counter(r["train_form"] for r in rows)
vf = collections.Counter(r["vt_form"] for r in rows)
res["max_pairs_per_train_form"] = max(tf.values()) if tf else 0
res["max_pairs_per_vt_form"] = max(vf.values()) if vf else 0
res["distinct_train_forms"] = len(tf)
res["distinct_vt_forms"] = len(vf)
ar = np.array([r["train_wxh"][0] * r["train_wxh"][1] for r in rows]) if rows else np.array([0])
res["median_area_px_of_listed_train_crops"] = float(np.median(ar))
res["median_area_px_all_train_crops"] = float(np.median((W[iN] * H[iN]).astype(np.float64)))
rows.sort(key=lambda r: (-(r["ncc"] >= 0.9), r["hash_distance"]))
res["pairs_listed"] = rows
# side by side images, 20 pairs in two panels
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.truetype(leak.FONT, 13)
sh = rows[:20]
for pi in range(2):
    chunk = sh[pi * 10:(pi + 1) * 10]
    if not chunk:
        continue
    panels = []
    for r in chunk:
        _, ga = leak.load(os.path.join(leak.IMG, r["train_crop"]))
        _, gb = leak.load(os.path.join(leak.IMG, r["vt_crop"]))
        hh = 70
        A = Image.fromarray(ga).resize((max(1, int(ga.shape[1] * hh / ga.shape[0])), hh))
        B = Image.fromarray(gb).resize((max(1, int(gb.shape[1] * hh / gb.shape[0])), hh))
        c = Image.new("L", (A.width + B.width + 50, hh + 22), 255)
        c.paste(A, (5, 20))
        c.paste(B, (A.width + 40, 20))
        ImageDraw.Draw(c).text((5, 2), "train %s | %s %s | d %.3f ncc %.3f" % (r["train_crop"], r["vt_split"], r["vt_crop"], r["hash_distance"], r["ncc"]), font=font, fill=0)
        panels.append(c)
    Wp = max(p.width for p in panels)
    img = Image.new("L", (Wp, sum(p.height + 6 for p in panels)), 255)
    y = 0
    for p in panels:
        img.paste(p, (0, y))
        y += p.height + 6
    img.save(os.path.join(OUT, "numbered_pairs_panel_%d.png" % (pi + 1)))
res["job_id"] = os.environ.get("SLURM_JOB_ID", "none")
res["runtime_seconds"] = round(time.time() - t0)
with open(os.path.join(OUT, "result_numbered.json"), "w", encoding="utf-8") as f:
    json.dump(res, f, ensure_ascii=False, indent=1)
print("DONE", round(time.time() - t0), flush=True)