turkic-ocr-code / scripts /kohtd_leak_scan.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
27.3 kB
# Leakage check: do the 24,989 scan-named KOHTD training crops come from forms in the validation or test split?
# IMAGES ONLY. No label file is read. Split membership is rebuilt from the crop file names with the pre-registered hash rule
# (DATA/data/processed/kohtd_split_v1/split_spec_v1.txt, rule (b)) and checked against the published counts.
# usage: python -I kohtd_leak_scan.py <out_dir> <workers>
import collections
import hashlib
import json
import math
import os
import random
import re
import sys
import time
import cv2
import numpy as np
cv2.setNumThreads(1)
IMG = "/path/to/TURKIC_OCR_DATA/data/processed/kohtd_words_raw/KOHTD_dataset/HK_dataset/img"
OUT = sys.argv[1]
WORKERS = int(sys.argv[2])
SEED = 20261125
PREFIX = "KOHTD-split-v1-2026-11-20:"
STD_MIN = 5.0 # near-blank filter, as in K1
ASPECT_LOG = math.log(1.15) # aspect-ratio gate: within 15 percent
EXPECT = {"train_numbered": 80513, "validation": 16238, "test": 18615, "scan": 24989}
FONT = "/path/to/TURKIC_OCR_CODE/.venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf"
NAMES = []
G_S, G_N, G_V, G_T = 0, 1, 2, 3 # groups: scan-named, numbered train, numbered validation, numbered test
def split_of_form(fid):
v = int(hashlib.sha256((PREFIX + str(fid)).encode("utf-8")).hexdigest()[:8], 16) % 100
return G_N if v < 70 else (G_V if v < 85 else G_T)
def ink_map(g):
bg = float(np.percentile(g, 70))
ink = np.clip(bg - g.astype(np.float32), 0, None)
ink[ink < 25] = 0
return ink / 255.0
def hashes(g):
ink = ink_map(g)
t = cv2.resize(ink, (17, 16), interpolation=cv2.INTER_AREA)
a, b = t[:, 1:], t[:, :-1]
bits = np.concatenate([(a > b + 0.01).ravel(), (a < b - 0.01).ravel()]).astype(np.uint8) # 512 bits: rise, fall
dh = np.packbits(bits).view(np.uint64)
t32 = cv2.resize(ink, (32, 32), interpolation=cv2.INTER_AREA).astype(np.float32)
d = cv2.dct(t32)[:8, :8].ravel()
ph = np.packbits((d > np.median(d[1:])).astype(np.uint8)).view(np.uint64) # 64 bits
return dh, ph
def load(path):
with open(path, "rb") as f:
b = f.read()
return b, cv2.imdecode(np.frombuffer(b, np.uint8), cv2.IMREAD_GRAYSCALE)
def work(i):
try:
b, g = load(os.path.join(IMG, NAMES[i]))
except Exception:
return i, None
if g is None:
return i, None
h, w = g.shape
dh, ph = hashes(g)
return i, (hashlib.sha256(b).hexdigest(), hashlib.sha256(g.tobytes() + str(g.shape).encode()).hexdigest(), w, h, float(g.std()), dh, ph)
def ncc_arrays(a, b):
"""a: DB crop (gray), b: scan crop (gray). Resize b to a's size, blur, shift +-4 px, return max TM_CCOEFF_NORMED."""
ia, ib = ink_map(a), ink_map(b)
h, w = ia.shape
ib = cv2.resize(ib, (w, h), interpolation=cv2.INTER_AREA)
if ia.std() < 1e-6 or ib.std() < 1e-6:
return -1.0
ia = cv2.GaussianBlur(ia, (0, 0), 1.0)
ib = cv2.GaussianBlur(ib, (0, 0), 1.0)
ia = cv2.copyMakeBorder(ia, 4, 4, 4, 4, cv2.BORDER_CONSTANT, value=0)
r = cv2.matchTemplate(ia, ib, cv2.TM_CCOEFF_NORMED)
return float(np.nanmax(r))
def ncc_paths(pair):
try:
_, a = load(os.path.join(IMG, pair[0]))
_, b = load(os.path.join(IMG, pair[1]))
return ncc_arrays(a, b)
except Exception:
return -2.0
def pack_feats(gs):
dh = np.zeros((len(gs), 8), np.uint64)
ph = np.zeros((len(gs), 1), np.uint64)
ar = np.zeros(len(gs), np.float32)
for k, g in enumerate(gs):
dh[k], ph[k] = hashes(g)
ar[k] = g.shape[1] / g.shape[0]
return dh, ph, ar
def nn(Qdh, Qph, Qar, Ddh, Dph, Dar, segs, exclude=None, chunk=64):
"""Nearest neighbour by combined distance d = dHash512/512 + pHash64/64 (0..2), aspect-gated.
segs: list of (lo, hi) in the DB; returns best dist and global index per segment (nq, nseg), plus best-other dist if exclude given."""
DT = np.ascontiguousarray(Ddh.T)
PT = np.ascontiguousarray(Dph.T)
nq, n = len(Qdh), len(Ddh)
bd = np.full((nq, len(segs)), 9.0, np.float32)
bi = np.full((nq, len(segs)), -1, np.int64)
other = np.full(nq, 9.0, np.float32)
lar = np.log(Dar)[None, :]
for s in range(0, nq, chunk):
e = min(nq, s + chunk)
dh = np.zeros((e - s, n), np.uint16)
for k in range(8):
dh += np.bitwise_count(Qdh[s:e, k, None] ^ DT[k][None, :])
ph = np.bitwise_count(Qph[s:e, 0, None] ^ PT[0][None, :]).astype(np.uint16)
dist = dh.astype(np.float32) / 512.0 + ph.astype(np.float32) / 64.0
dist[np.abs(np.log(Qar[s:e])[:, None] - lar) > ASPECT_LOG] = 9.0
if exclude is not None:
ex = exclude[s:e]
sel = ex >= 0
tmp = dist[np.arange(e - s)[sel], ex[sel]].copy()
dist[np.arange(e - s)[sel], ex[sel]] = 9.0
other[s:e] = dist.min(1)
dist[np.arange(e - s)[sel], ex[sel]] = tmp
for j, (lo, hi) in enumerate(segs):
k = dist[:, lo:hi].argmin(1)
bi[s:e, j] = lo + k
bd[s:e, j] = dist[np.arange(e - s), lo + k]
return bd, bi, other
def degrade(g, rng, hard, f=1.78):
h, w = g.shape
up = cv2.resize(g, None, fx=f, fy=f, interpolation=cv2.INTER_LINEAR if f >= 1 else cv2.INTER_AREA)
hh, ww = up.shape
m = (0.02, 0.04) if hard else (0.01, 0.02)
t, bt, l, r = [int(round(rng.uniform(*m) * (hh if k < 2 else ww))) for k in range(4)]
up = up[t:hh - bt, l:ww - r]
x = up.astype(np.float32)
if hard:
ang = rng.uniform(-1.0, 1.0)
H, W = x.shape
M = cv2.getRotationMatrix2D((W / 2, H / 2), ang, 1.0)
x = cv2.warpAffine(x, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=255)
x = x * 0.88 + 8.0
x = x + np.random.RandomState(rng.randint(0, 2 ** 31 - 1)).normal(0, 4.0, x.shape)
x = np.clip(x, 0, 255).astype(np.uint8)
ok, buf = cv2.imencode(".jpg", x, [cv2.IMWRITE_JPEG_QUALITY, 75 if hard else 85])
return cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
def qs(a, ps=(0, 0.1, 1, 5, 25, 50, 75, 95, 99, 100)):
a = np.asarray(a, dtype=np.float64)
return {str(p): round(float(np.percentile(a, p)), 4) for p in ps} if len(a) else {}
def main():
global NAMES
t0 = time.time()
os.makedirs(OUT, exist_ok=True)
job = os.environ.get("SLURM_JOB_ID", "none")
res = {"job_id": job, "seed": SEED}
NAMES = sorted(n for n in os.listdir(IMG) if n.endswith(".jpg"))
num = re.compile(r"^(\d+)_(\d+)_(\d+)\.jpg$")
scan = re.compile(r"^word_croped_(.+)_(-?\d+)_(\d+)\.jpg$")
grp, form, sname, srow = [], [], [], []
other = []
for n in NAMES:
m = num.match(n)
if m:
fid = int(m.group(1))
grp.append(split_of_form(fid))
form.append(fid)
sname.append("")
srow.append(0)
continue
m = scan.match(n)
if m:
grp.append(G_S)
form.append(-1)
sname.append(m.group(1))
srow.append(int(m.group(2)))
else:
other.append(n)
grp.append(-1)
form.append(-1)
sname.append("")
srow.append(0)
grp, form, srow = np.array(grp), np.array(form), np.array(srow)
counts = {"files": len(NAMES), "unparsed": len(other), "scan": int((grp == G_S).sum()), "train_numbered": int((grp == G_N).sum()),
"validation": int((grp == G_V).sum()), "test": int((grp == G_T).sum())}
counts["matches_published_split_stats"] = all(counts[k] == v for k, v in EXPECT.items())
res["membership_rebuilt_from_file_names"] = counts
print("counts", counts, flush=True)
# ---- features for all crops (cached) ----
cache = os.path.join(OUT, "features.npz")
if os.path.exists(cache):
z = np.load(cache, allow_pickle=True)
sha, pix, W, H, STD, DH, PH, BAD = [z[k] for k in ("sha", "pix", "W", "H", "STD", "DH", "PH", "BAD")]
else:
from multiprocessing import Pool
n = len(NAMES)
sha, pix = np.empty(n, dtype=object), np.empty(n, dtype=object)
W, H, STD = np.zeros(n, np.int32), np.zeros(n, np.int32), np.zeros(n, np.float32)
DH, PH, BAD = np.zeros((n, 8), np.uint64), np.zeros((n, 1), np.uint64), np.zeros(n, bool)
with Pool(WORKERS) as pool:
for k, (i, r) in enumerate(pool.imap_unordered(work, range(n), chunksize=256)):
if r is None:
BAD[i] = True
continue
sha[i], pix[i], W[i], H[i], STD[i], DH[i], PH[i] = r
if k % 20000 == 0:
print("features", k, round(time.time() - t0), "s", flush=True)
np.savez(cache, sha=sha, pix=pix, W=W, H=H, STD=STD, DH=DH, PH=PH, BAD=BAD)
print("features done", round(time.time() - t0), "s", flush=True)
res["unreadable_files"] = int(BAD.sum())
valid = (~BAD) & (STD > STD_MIN)
res["near_blank_dropped_std_le_5"] = {g: int(((grp == c) & ~BAD & (STD <= STD_MIN)).sum()) for g, c in (("scan", G_S), ("train_numbered", G_N), ("validation", G_V), ("test", G_T))}
AR = (W / np.maximum(H, 1)).astype(np.float32)
# ---- exact duplicates ----
def dup_report(key, label):
by = collections.defaultdict(list)
for i in range(len(NAMES)):
if not BAD[i]:
by[key[i]].append(i)
groups = [v for v in by.values() if len(v) > 1]
cross = {"scan_with_validation": 0, "scan_with_test": 0, "scan_with_train_numbered": 0, "scan_with_scan": 0}
for v in groups:
gs = set(int(grp[i]) for i in v)
if G_S in gs and G_V in gs:
cross["scan_with_validation"] += 1
if G_S in gs and G_T in gs:
cross["scan_with_test"] += 1
if G_S in gs and G_N in gs:
cross["scan_with_train_numbered"] += 1
if sum(1 for i in v if grp[i] == G_S) > 1:
cross["scan_with_scan"] += 1
return {"duplicate_groups": len(groups), "files_in_groups": sum(len(v) for v in groups), "groups_by_kind": cross, "label": label}
res["exact_duplicates_file_sha256"] = dup_report(sha, "sha256 of the file bytes")
res["exact_duplicates_decoded_pixels"] = dup_report(pix, "sha256 of the decoded grayscale pixels")
print("exact dup", res["exact_duplicates_file_sha256"], res["exact_duplicates_decoded_pixels"], flush=True)
# ---- sets ----
iS = np.where((grp == G_S) & valid)[0]
iN = np.where((grp == G_N) & valid)[0]
iV = np.where((grp == G_V) & valid)[0]
iT = np.where((grp == G_T) & valid)[0]
DBi = np.concatenate([iV, iT, iN]) # DB order: V, T, N
segs = [(0, len(iV)), (len(iV), len(iV) + len(iT)), (len(iV) + len(iT), len(DBi))]
Ddh, Dph, Dar = DH[DBi], PH[DBi], AR[DBi]
res["valid_crops_used"] = {"scan": len(iS), "train_numbered": len(iN), "validation": len(iV), "test": len(iT)}
# ---- positive controls ----
rng = random.Random(SEED)
ctrl_src = rng.sample(list(iN), 600)
pos_in_db = {int(d): k for k, d in enumerate(DBi)}
ctrl = {}
dbidx = np.array([pos_in_db[int(i)] for i in ctrl_src])
for hard in (False, True):
gs, orig = [], []
for i in ctrl_src:
_, g = load(os.path.join(IMG, NAMES[i]))
gs.append((g, degrade(g, rng, hard)))
dh, ph, ar = pack_feats([x[1] for x in gs])
bd, bi, oth = nn(dh, ph, ar, Ddh, Dph, Dar, [(0, len(DBi))], exclude=dbidx)
top1_ok = (bi[:, 0] == dbidx)
# true-pair distance: recompute through nn with exclude trick: distance to original = need explicit
true_d = []
for k in range(len(gs)):
a = np.bitwise_count(dh[k] ^ Ddh[dbidx[k]]).sum() / 512.0 + np.bitwise_count(ph[k] ^ Dph[dbidx[k]]).sum() / 64.0
true_d.append(float(a))
nccs = [ncc_arrays(gs[k][0], gs[k][1]) for k in range(len(gs))]
name = "hard" if hard else "easy"
ctrl[name] = {"n": len(gs), "top1_recall_all_numbered_db": float(top1_ok.mean()), "true_pair_dist": qs(true_d), "best_other_dist": qs(oth),
"true_pair_ncc": qs(nccs), "description": ("scale x1.78 + JPEG q75 + crop margins 2-4% + rotation +-1 deg + contrast 0.88x+8 + gaussian noise sd 4" if hard else "scale x1.78 + JPEG q85 + crop margins 1-2%")}
ctrl[name]["true_pair_ncc_fraction_ge"] = {str(t): round(float(np.mean(np.array(nccs) >= t)), 3) for t in (0.6, 0.7, 0.8, 0.85, 0.9)}
ctrl[name]["_p95_true"] = float(np.percentile(true_d, 95))
ctrl[name]["_ncc_p5"] = float(np.percentile(nccs, 5))
tau_easy, tau_hard = ctrl["easy"].pop("_p95_true"), ctrl["hard"].pop("_p95_true")
ctrl["easy"].pop("_ncc_p5"), ctrl["hard"].pop("_ncc_p5")
res["positive_controls"] = ctrl
# reverse control in the scan domain: 600 scan crops shrunk by 1/1.78 (numbered-crop size) and matched against the scan crops themselves
rev = {}
rs = random.Random(SEED + 5)
src = rs.sample(list(iS), 600)
pos_s = {int(d): k for k, d in enumerate(iS)}
exs = np.array([pos_s[int(i)] for i in src])
for hard in (False, True):
gs = []
for i in src:
_, g = load(os.path.join(IMG, NAMES[i]))
gs.append((g, degrade(g, rs, hard, f=1 / 1.78)))
dh, ph, ar = pack_feats([x[1] for x in gs])
bd2, bi2, oth2 = nn(dh, ph, ar, DH[iS], PH[iS], AR[iS], [(0, len(iS))], exclude=exs)
td = [float(np.bitwise_count(dh[k] ^ DH[iS][exs[k]]).sum() / 512.0 + np.bitwise_count(ph[k] ^ PH[iS][exs[k]]).sum() / 64.0) for k in range(len(gs))]
nc2 = [ncc_arrays(gs[k][0], gs[k][1]) for k in range(len(gs))]
rev["hard" if hard else "easy"] = {"n": len(gs), "top1_recall_among_scan_crops": float((bi2[:, 0] == exs).mean()), "true_pair_dist": qs(td), "best_other_dist": qs(oth2), "true_pair_ncc": qs(nc2),
"fraction_true_pairs_within_tau_hard_0.3751": round(float(np.mean(np.array(td) <= 0.3751)), 3),
"description": "scan-named crop shrunk to 1/1.78 (numbered-crop size), same distortions as the forward control"}
res["reverse_controls_scan_domain"] = rev
res["thresholds"] = {"hash_distance": "d = dHash512/512 + pHash64/64 on the ink map (0 = identical, 2 = opposite); aspect-ratio gate within 15 percent",
"tau_easy_p95_of_true_pairs": round(tau_easy, 4), "tau_hard_p95_of_true_pairs": round(tau_hard, 4)}
print("controls", json.dumps(ctrl)[:1500], flush=True)
# ---- real query: scan-named crops against V, T, N ----
bdS, biS, _ = nn(DH[iS], PH[iS], AR[iS], Ddh, Dph, Dar, segs)
# ---- null query: a random sample of numbered TRAIN crops, same size, against V and T only (form-disjoint by construction) ----
nrng = np.random.RandomState(SEED)
sampN = nrng.choice(iN, len(iS), replace=False)
VT = (0, len(iV) + len(iT))
DdhVT, DphVT, DarVT = Ddh[:VT[1]], Dph[:VT[1]], Dar[:VT[1]]
bdN, biN, _ = nn(DH[sampN], PH[sampN], AR[sampN], DdhVT, DphVT, DarVT, [(0, len(iV)), (len(iV), VT[1])])
print("matching done", round(time.time() - t0), "s", flush=True)
realVT = np.minimum(bdS[:, 0], bdS[:, 1])
nullVT = np.minimum(bdN[:, 0], bdN[:, 1])
ladder = [round(tau_easy, 4), round(tau_hard, 4), 0.10, 0.20, 0.30, 0.40, 0.50, 0.60]
lad = {}
for t in ladder:
lad[str(t)] = {"scan_to_validation": int((bdS[:, 0] <= t).sum()), "scan_to_test": int((bdS[:, 1] <= t).sum()), "scan_to_train_numbered": int((bdS[:, 2] <= t).sum()),
"scan_to_val_or_test": int((realVT <= t).sum()), "NULL_trainnumbered_sample_to_val_or_test": int((nullVT <= t).sum())}
res["hash_counts_by_threshold_crops"] = lad
res["nearest_distance_quantiles"] = {"scan_to_val_or_test": qs(realVT), "NULL_trainnumbered_to_val_or_test": qs(nullVT), "scan_to_train_numbered": qs(bdS[:, 2]), "scan_to_all_numbered": qs(bdS.min(1))}
res["nearest_distance_note"] = "NULL = 24,989 random numbered TRAIN crops matched against validation+test crops; train forms differ from val/test forms by construction (checked by the hash rule), so every NULL neighbour is a different page."
# ---- NCC second check on the closest pairs ----
from multiprocessing import Pool
best_seg = np.where(bdS[:, 0] <= bdS[:, 1], 0, 1)
real_idx = np.where(best_seg == 0, biS[:, 0], biS[:, 1]) # DB index
null_best_seg = np.where(bdN[:, 0] <= bdN[:, 1], 0, 1)
null_idx = np.where(null_best_seg == 0, biN[:, 0], biN[:, 1])
K = int(max(300, min(3000, (realVT <= tau_hard).sum())))
ordR = np.argsort(realVT)[:K]
ordN = np.argsort(nullVT)[:K]
pairsR = [(NAMES[DBi[real_idx[q]]], NAMES[iS[q]]) for q in ordR]
pairsN = [(NAMES[DBi[null_idx[q]]], NAMES[sampN[q]]) for q in ordN]
rand_q = nrng.choice(len(iS), 2000, replace=False)
pairsN_rand = [(NAMES[DBi[null_idx[q]]], NAMES[sampN[q]]) for q in rand_q]
with Pool(WORKERS) as pool:
nccR = np.array(pool.map(ncc_paths, pairsR, chunksize=32))
nccN = np.array(pool.map(ncc_paths, pairsN, chunksize=32))
nccNr = np.array(pool.map(ncc_paths, pairsN_rand, chunksize=32))
thr_ncc = 0.85 # fixed in advance (reviewer advice before the first result was seen)
res["ncc_second_check"] = {"K_closest_pairs_checked": K, "method": "scan crop resized to the val/test crop size, ink map, gaussian blur 1 px, max TM_CCOEFF_NORMED over +-4 px shifts",
"real_closest_K_ncc": qs(nccR), "NULL_closest_K_ncc": qs(nccN), "NULL_random_top1_ncc": qs(nccNr), "threshold_ncc_fixed_in_advance": thr_ncc, "ncc_ladder_real_closest_K_count_ge": {str(t): int((nccR >= t).sum()) for t in (0.6, 0.7, 0.8, 0.85, 0.9)}, "ncc_ladder_NULL_closest_K_count_ge": {str(t): int((nccN >= t).sum()) for t in (0.6, 0.7, 0.8, 0.85, 0.9)},
"hard_control_ncc_p5": ctrl["hard"]["true_pair_ncc"].get("5"), "easy_control_ncc_p5": ctrl["easy"]["true_pair_ncc"].get("5")}
conf_mask = (realVT[ordR] <= tau_hard) & (nccR >= thr_ncc)
conf_null = (nullVT[ordN] <= tau_hard) & (nccN >= thr_ncc)
conf_q = ordR[conf_mask]
res["confirmed_near_duplicates"] = {"rule": "hash distance <= tau_hard AND NCC >= threshold_ncc", "crops": int(conf_mask.sum()), "NULL_expected_false_positives_same_rule": int(conf_null.sum()),
"in_validation": int((best_seg[conf_q] == 0).sum()), "in_test": int((best_seg[conf_q] == 1).sum())}
# ---- vote per scan name ----
snames = np.array([re.match(scan, NAMES[i]).group(1) for i in iS])
allbest = bdS.argmin(1)
best_dist = bdS.min(1)
best_db = biS[np.arange(len(iS)), allbest]
best_form = form[DBi[best_db]]
best_grp = grp[DBi[best_db]]
by_name = collections.defaultdict(list)
for q in range(len(iS)):
by_name[snames[q]].append(q)
names3 = [k for k, v in by_name.items() if len(v) >= 3]
def maxvotes(forms_arr):
out = {}
for k in names3:
c = collections.Counter(int(forms_arr[q]) for q in by_name[k] if forms_arr[q] >= 0)
out[k] = c.most_common(1)[0] if c else (-1, 0)
return out
def vote_summary(forms_arr, label):
real = maxvotes(forms_arr)
rv = np.array([v[1] for v in real.values()])
prng = np.random.RandomState(SEED + 1)
perm_counts = {k: [] for k in (2, 3, 4, 5)}
for _ in range(200):
fa = prng.permutation(forms_arr)
pv = np.array([v[1] for v in maxvotes(fa).values()])
for k in perm_counts:
perm_counts[k].append(int((pv >= k).sum()))
return {"label": label, "scan_names_with_3plus_valid_crops": len(names3),
"names_with_max_votes_ge": {str(k): int((rv >= k).sum()) for k in perm_counts},
"PERMUTATION_NULL_mean_names_ge": {str(k): round(float(np.mean(v)), 2) for k, v in perm_counts.items()},
"PERMUTATION_NULL_max_names_ge": {str(k): int(np.max(v)) for k, v in perm_counts.items()}}, real
allforms = best_form.copy()
s_all, real_all = vote_summary(allforms, "every crop votes for the form of its nearest numbered crop (aspect-gated), no distance limit")
close_forms = np.where(best_dist <= tau_hard, best_form, -1)
s_close, real_close = vote_summary(close_forms, "only crops whose nearest numbered crop is within tau_hard vote")
res["vote_per_scan_name"] = {"all_crops": s_all, "close_crops_only": s_close,
"crops_whose_nearest_numbered_crop_is_within_tau_hard": int((best_dist <= tau_hard).sum()),
"their_split": {"validation": int(((best_dist <= tau_hard) & (best_grp == G_V)).sum()), "test": int(((best_dist <= tau_hard) & (best_grp == G_T)).sum()),
"train_numbered": int(((best_dist <= tau_hard) & (best_grp == G_N)).sum())}}
# NCC of voting pairs in names that pile up on a val/test form
vp = []
for k, (fid, c) in real_all.items():
if c >= 3 and fid >= 0 and split_of_form(fid) in (G_V, G_T):
for q in by_name[k]:
if best_form[q] == fid:
vp.append((NAMES[DBi[best_db[q]]], NAMES[iS[q]], k, fid, float(best_dist[q])))
vp = vp[:1500]
with Pool(WORKERS) as pool:
nv = np.array(pool.map(ncc_paths, [(a, b) for a, b, _, _, _ in vp], chunksize=32)) if vp else np.array([])
res["vote_per_scan_name"]["names_piling_on_a_val_or_test_form_3plus"] = len(set(v[2] for v in vp))
res["vote_per_scan_name"]["their_voting_pairs_ncc"] = qs(nv)
res["vote_per_scan_name"]["their_voting_pairs_ncc_ge_threshold"] = int((nv >= thr_ncc).sum()) if len(nv) else 0
res["vote_per_scan_name"]["linked_names_vote3_and_ncc_ge_threshold"] = None
linked = collections.defaultdict(int)
for (a, b, k, fid, d), v in zip(vp, nv):
if v >= thr_ncc:
linked[(k, fid)] += 1
ln = [(k, fid, c) for (k, fid), c in linked.items() if c >= 3]
res["vote_per_scan_name"]["linked_names_vote3_and_ncc_ge_threshold"] = {"count": len(ln), "details": [{"scan_name": k, "form": fid, "split": ["train", "validation", "test"][split_of_form(fid) - 1], "crops_voting_and_confirmed": c} for k, fid, c in ln[:20]],
"crops_of_linked_names": int(sum(len(by_name[k]) for k, _, _ in ln))}
# ---- examples: five closest scan-to-val/test pairs by NCC among the K closest by hash ----
order_ex = np.argsort(-nccR)[:5]
ex = []
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.truetype(FONT, 14)
panels = []
for r, o in enumerate(order_ex):
q = ordR[o]
sa, db = NAMES[iS[q]], NAMES[DBi[real_idx[q]]]
d = float(realVT[q])
nc = float(nccR[o])
confirmed = bool(d <= tau_hard and nc >= thr_ncc)
fid = int(form[DBi[real_idx[q]]])
spl = "validation" if best_seg[q] == 0 else "test"
ex.append({"rank": r + 1, "scan_named_crop": sa, "val_or_test_crop": db, "form_id": fid, "split": spl, "hash_distance": round(d, 4), "ncc": round(nc, 4), "confirmed_duplicate": confirmed})
_, ga = load(os.path.join(IMG, sa))
_, gb = load(os.path.join(IMG, db))
hh = 130
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))
canvas = Image.new("L", (A.width + B.width + 60, hh + 50), 255)
canvas.paste(A, (10, 40))
canvas.paste(B, (A.width + 50, 40))
dr = ImageDraw.Draw(canvas)
dr.text((10, 4), "%d scan-named: %s" % (r + 1, sa[:60]), font=font, fill=0)
dr.text((10, 22), "%s form %d (%s) hash dist %.3f NCC %.3f %s" % (db, fid, spl, d, nc, "CONFIRMED" if confirmed else "closest, not a confirmed duplicate"), font=font, fill=0)
canvas.save(os.path.join(OUT, "pair_%d.png" % (r + 1)))
panels.append(canvas)
Wp = max(p.width for p in panels)
panel = Image.new("L", (Wp, sum(p.height + 10 for p in panels)), 255)
y = 0
for p in panels:
panel.paste(p, (0, y))
y += p.height + 10
panel.save(os.path.join(OUT, "examples_panel.png"))
res["examples_five_closest_scan_to_val_or_test"] = ex
# ---- step 4: name structure and image traits ----
snm = re.compile(r"^Скан_(\d{8})(?:_(\d+))?(?: \((\d+)\))?$")
names_all = sorted(set(sname[i] for i in range(len(NAMES)) if grp[i] == G_S))
per_date = collections.defaultdict(lambda: {"names": 0, "crops": 0, "n_values": set(), "heights": []})
unparsed = 0
name_date = {}
for s in names_all:
m = snm.match(s)
if not m:
unparsed += 1
continue
name_date[s] = m.group(1)
per_date[m.group(1)]["names"] += 1
if m.group(2):
per_date[m.group(1)]["n_values"].add(int(m.group(2)))
for i in range(len(NAMES)):
if grp[i] == G_S and not BAD[i] and sname[i] in name_date:
per_date[name_date[sname[i]]]["crops"] += 1
per_date[name_date[sname[i]]]["heights"].append(int(H[i]))
res["scan_name_structure"] = {"names": len(names_all), "unparsed": unparsed, "crops_with_row_minus1": int(((grp == G_S) & (srow == -1)).sum()),
"pattern": "Скан_YYYYMMDD[_n][ (k)] = scanner export file name (date, batch number n, copy number k); the meaning of n and k is NOT documented (unknown)",
"per_date": {d: {"names": v["names"], "crops": v["crops"], "n_range": [min(v["n_values"]), max(v["n_values"])] if v["n_values"] else None, "median_crop_height": float(np.median(v["heights"])) if v["heights"] else None} for d, v in sorted(per_date.items())},
"note": "The sheet archive folder is named 20200929_Examination_sheets_cleaned; 500 scan names carry the date 20200929. Flagged as a coincidence, not evidence of a link."}
ms, mn = (np.median(W[iS]), np.median(H[iS])), (np.median(W[iN]), np.median(H[iN]))
res["crop_size_median_wxh"] = {"scan": [float(ms[0]), float(ms[1])], "train_numbered": [float(mn[0]), float(mn[1])], "ratio_h": round(float(ms[1] / mn[1]), 3)}
from PIL import Image as PI
meta = {}
srng = random.Random(SEED + 2)
for lab, pool_i in (("scan", iS), ("numbered", iN)):
fp = collections.Counter()
dpis = collections.Counter()
for i in srng.sample(list(pool_i), 300):
with PI.open(os.path.join(IMG, NAMES[i])) as im:
q = getattr(im, "quantization", None)
fp[hashlib.md5(repr(q).encode()).hexdigest()[:8]] += 1
dpis[str(im.info.get("dpi"))] += 1
meta[lab] = {"jpeg_quant_table_fingerprints_in_300": dict(fp), "dpi_values_in_300": dict(dpis)}
res["jpeg_metadata_sample"] = meta
res["runtime_seconds"] = round(time.time() - t0)
with open(os.path.join(OUT, "result.json"), "w", encoding="utf-8") as f:
json.dump(res, f, ensure_ascii=False, indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o))
print("DONE", round(time.time() - t0), "s", flush=True)
if __name__ == "__main__":
main()