turkic-ocr-code / scripts /release2 /rel2_d5_check.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
19.2 kB
"""RELEASE2 D5 finish, check job (ZEN4 CPU, see rel2_d5_check.sbatch). Run with CODE/.venv_kraken/bin/python -B -I.
Facts about the retrained stage-2 line detector (yolo_s2_d5, jobs 55687 + 55706) and the end-to-end check of the page pipeline with it,
BEFORE the weights go into the package. The release folders are only read. Validation data only; nothing is uploaded.
1 sha256 of the new best.pt, of the package best.pt (rc1, yolo_s2) and of the detector package's infer.py;
2 checkpoint metadata and parameter count of both weights with rc1_prep_det.py (the method of job 55119);
3 results.csv of yolo_s2_d5 and yolo_s2: rows, last epoch, the row whose metrics equal the train_metrics stored in best.pt, the row
with the highest mAP50-95;
4 generated training page lists (gen_d5 and gen): pages, lines, by layout and language; overlap with the 83 excluded pages; files on disk;
5 a temporary detector folder (the package's infer.py + the new best.pt) and the page pipeline of the package (page-pipeline/infer.py,
reader turkic-ocr-paddleocr-vl-1.6) on the 5 validation pages of rc1_check.py step 6 with the same arguments; compared with the
rc1 run of job 55230 (old detector, DATA/tmp/rc1_check/page_*.tsv): boxes, lines, page CER (reading order and order free, the
page_cers function of rc1_check.py unchanged).
"""
import csv
import difflib
import hashlib
import json
import os
import shutil
import subprocess
import time
from datetime import datetime, timezone
import numpy as np
from rapidfuzz import process
from rapidfuzz.distance import Levenshtein
from scipy.optimize import linear_sum_assignment
csv.field_size_limit(10 ** 9)
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
R = DATA + "/release/rc1"
W = DATA + "/tmp/release2/d5_finish"
OLD = DATA + "/tmp/rc1_check"
PY_VLM = CODE + "/.venv_vlm/bin/python"
PY_KR = CODE + "/.venv_kraken/bin/python"
DET_PKG = R + "/turkic-line-detector-yolo11s"
PAGE_PKG = R + "/page-pipeline"
NEW_W = DATA + "/checkpoints/r5/linedet/detectors/yolo_s2_d5/weights/best.pt"
NEW_RUN = DATA + "/checkpoints/r5/linedet/detectors/yolo_s2_d5"
OLD_RUN = DATA + "/checkpoints/r5/linedet/detectors/yolo_s2"
PG = DATA + "/data/processed/r5_linedet_det"
EXPECT_NEW = "55633d707319b0c9e0c1a2c1f116357493992e58efc192c679401d31ea14acc4"
EXPECT_OLD = "2ef12b4a1d4b4f28b3285251a35ea30032fc2c7b53f03aa5db5f0510ae8ffc00"
EXPECT_DET_INFER = "49e15fbbd052515f508ec276297dd6e86da35134d4e4a46183b7fbb72b4b673b"
GEN_IDS = ["pg_val_diagram_az_l_000008", "pg_val_diagram_kk_h_000029", "pg_val_map_tt_l_000022"]
SCH_IDS = ["school_val_0", "school_val_45"]
RES = {}
def utc():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def say(*a):
print("[d5check %s]" % utc(), *a, flush=True)
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
return h.hexdigest()
def read_tsv(path):
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
def env():
e = dict(os.environ)
for k in list(e):
if k.startswith("PYTHON"):
e.pop(k)
e.update({"PYTHONDONTWRITEBYTECODE": "1", "HF_HOME": W + "/hf_home", "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1",
"YOLO_OFFLINE": "1", "YOLO_CONFIG_DIR": W + "/yolo_cfg", "OMP_NUM_THREADS": "16", "MKL_NUM_THREADS": "16",
"TOKENIZERS_PARALLELISM": "false"})
for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
e.pop(k, None)
return e
def run(cmd, name, cwd):
t0 = time.time()
r = subprocess.run(cmd, cwd=cwd, env=env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
with open("%s/log_%s.txt" % (W, name), "w", encoding="utf-8") as f:
f.write("CMD: " + " ".join(cmd) + "\n--- stdout\n" + r.stdout + "\n--- stderr\n" + r.stderr)
say(name, "exit", r.returncode, "%.1f s" % (time.time() - t0))
return {"exit": r.returncode, "seconds": round(time.time() - t0, 1), "stdout_tail": r.stdout[-400:], "stderr_tail": r.stderr[-400:]}
# ----------------------------------------------------------------------------------------------- 1
def step1():
out = {"new_best_pt": NEW_W, "new_sha256": sha256(NEW_W), "new_bytes": os.path.getsize(NEW_W),
"package_best_pt_sha256": sha256(DET_PKG + "/best.pt"), "package_best_pt_bytes": os.path.getsize(DET_PKG + "/best.pt"),
"package_infer_py_sha256": sha256(DET_PKG + "/infer.py"),
"new_last_pt_sha256": sha256(NEW_RUN + "/weights/last.pt")}
out["new_equals_expected"] = out["new_sha256"] == EXPECT_NEW
out["package_best_equals_expected_old"] = out["package_best_pt_sha256"] == EXPECT_OLD
out["package_infer_equals_rc1"] = out["package_infer_py_sha256"] == EXPECT_DET_INFER
return out
# ----------------------------------------------------------------------------------------------- 2
def step2():
out = {}
for name, w in (("new", NEW_W), ("old_package", DET_PKG + "/best.pt")):
rep = "%s/prep_det_%s.json" % (W, name)
r = run([PY_KR, "-B", "-I", CODE + "/scripts/r5_release/rc1_prep_det.py", w, rep], "prep_det_" + name, W + "/run")
out[name] = {"run": r, "report": json.load(open(rep, encoding="utf-8")) if r["exit"] == 0 else None}
return out
# ----------------------------------------------------------------------------------------------- 3
def results_csv(path, train_metrics):
rows = [{k.strip(): v for k, v in r.items()} for r in csv.DictReader(open(path, encoding="utf-8"))]
keys = ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
out = {"rows": len(rows), "first_epoch": rows[0]["epoch"], "last_epoch": rows[-1]["epoch"], "last_time_s": rows[-1]["time"]}
best_map = max(rows, key=lambda r: float(r["metrics/mAP50-95(B)"]))
out["row_highest_map50_95"] = {"epoch": best_map["epoch"], **{k: float(best_map[k]) for k in keys}}
fit = max(rows, key=lambda r: 0.1 * float(r["metrics/mAP50(B)"]) + 0.9 * float(r["metrics/mAP50-95(B)"]))
out["row_highest_0.1map50_0.9map50_95"] = {"epoch": fit["epoch"], **{k: float(fit[k]) for k in keys}}
if isinstance(train_metrics, dict):
match = [r["epoch"] for r in rows if all(k in train_metrics and abs(float(r[k]) - float(train_metrics[k])) < 5.1e-6 for k in keys)]
out["rows_matching_train_metrics_of_best_pt"] = match
if len(match) == 1:
r = [x for x in rows if x["epoch"] == match[0]][0]
out["best_pt_row"] = {"epoch": r["epoch"], **{k: float(r[k]) for k in keys}}
# epochs per job segment: the time column restarts when training resumes
seg, prev = [], None
for r in rows:
t = float(r["time"])
if prev is None or t < prev:
seg.append({"first_epoch": int(r["epoch"]), "last_epoch": int(r["epoch"]), "last_time_s": t})
else:
seg[-1]["last_epoch"], seg[-1]["last_time_s"] = int(r["epoch"]), t
prev = t
out["segments_by_time_column"] = seg
return out
def step3(s2):
out = {}
for name, run_dir, key in (("yolo_s2_d5", NEW_RUN, "new"), ("yolo_s2", OLD_RUN, "old_package")):
rep = (s2.get(key) or {}).get("report") or {}
out[name] = results_csv(run_dir + "/results.csv", rep.get("train_metrics_in_ckpt"))
out[name]["results_csv_sha256"] = sha256(run_dir + "/results.csv")
return out
# ----------------------------------------------------------------------------------------------- 4
def page_list(path):
rows = read_tsv(path)
by_layout, by_lang, by_hand, lines = {}, {}, {}, 0
for r in rows:
p = r["id"].split("_")
assert p[0] == "pg" and p[1] == "train", r["id"]
layout, hand, lang = p[2], p[-2], "_".join(p[3:-2])
by_layout[layout] = by_layout.get(layout, 0) + 1
by_lang[lang] = by_lang.get(lang, 0) + 1
by_hand[hand] = by_hand.get(hand, 0) + 1
lines += int(r["n_lines"])
return {"pages": len(rows), "lines": lines, "by_layout": dict(sorted(by_layout.items())), "by_language": dict(sorted(by_lang.items())),
"by_id_letter_h_or_l": by_hand, "ids": set(r["id"] for r in rows), "sha256": sha256(path)}
def step4():
new = page_list(PG + "/gen_d5/pages_gen_train.tsv")
old = page_list(PG + "/gen/pages_gen_train.tsv")
exc = set(r["id"] for r in read_tsv(PG + "/gen_d5/excluded_pages_personal_fonts.tsv"))
imgs = sorted(os.listdir(PG + "/gen_d5/train/images"))
lab_dir = PG + "/gen_d5/train/labels"
labs = sorted(n for n in os.listdir(lab_dir) if n.endswith(".txt")) if os.path.isdir(lab_dir) else []
lab_lines = 0
for n in labs:
with open(lab_dir + "/" + n, encoding="utf-8") as f:
lab_lines += sum(1 for ln in f if ln.strip())
out = {"gen_d5": {k: v for k, v in new.items() if k != "ids"}, "gen_rc1": {k: v for k, v in old.items() if k != "ids"},
"excluded_pages": len(exc), "excluded_in_gen_d5": len(exc & new["ids"]), "excluded_in_gen_rc1": len(exc & old["ids"]),
"gen_rc1_minus_gen_d5_equals_excluded": (old["ids"] - new["ids"]) == exc, "gen_d5_subset_of_gen_rc1": new["ids"] <= old["ids"],
"gen_d5_images_on_disk": len(imgs), "gen_d5_label_files": len(labs), "gen_d5_label_lines": lab_lines,
"image_stems_equal_page_ids": set(os.path.splitext(n)[0] for n in imgs) == new["ids"]}
return out
# ----------------------------------------------------------------------------------------------- 5
def page_cers(hyp_lines, ref_lines):
"""Unchanged from rc1_check.py."""
nref = sum(len(r) for r in ref_lines)
ro = Levenshtein.distance(" ".join(hyp_lines), " ".join(ref_lines))
if not hyp_lines or not ref_lines:
of = sum(len(h) for h in hyp_lines) + nref
else:
C = process.cdist(hyp_lines, ref_lines, scorer=Levenshtein.distance, dtype=np.int32)
ri, ci = linear_sum_assignment(C)
matched = int(C[ri, ci].sum())
un_h = sum(len(hyp_lines[i]) for i in range(len(hyp_lines)) if i not in set(ri.tolist()))
un_r = sum(len(ref_lines[j]) for j in range(len(ref_lines)) if j not in set(ci.tolist()))
of = matched + un_h + un_r
return ro, of, nref
def school_orig(pid):
"""Unchanged from rc1_check.py: the full-resolution School Notebooks photograph of a VALIDATION page."""
sp, num = pid.split("_")[1], int(pid.split("_")[2])
assert sp == "val"
base = DATA + "/data/raw/school_notebooks_ru"
d = json.load(open("%s/annotations_%s.json" % (base, sp), encoding="utf-8"))
fn = {im["id"]: im["file_name"] for im in d["images"]}[num]
return "%s/val_test_images/%s/%s" % (base, sp, fn)
def iou(a, b):
ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
return inter / u if u > 0 else 0.0
def match_boxes(old, new, thr=0.5):
pairs = sorted(((iou(o, n), i, j) for i, o in enumerate(old) for j, n in enumerate(new)), reverse=True)
used_o, used_n, m = set(), set(), []
for v, i, j in pairs:
if v < thr:
break
if i in used_o or j in used_n:
continue
used_o.add(i)
used_n.add(j)
m.append((i, j, v))
return m
def lines_by_page(path):
out = {}
for r in read_tsv(path):
out.setdefault(r["id"], []).append(r)
return out
def step5():
det_new = W + "/det_pkg_new"
if os.path.isdir(det_new):
shutil.rmtree(det_new)
os.makedirs(det_new)
shutil.copyfile(DET_PKG + "/infer.py", det_new + "/infer.py")
shutil.copyfile(NEW_W, det_new + "/best.pt")
res = {"temporary_detector_folder": det_new, "infer_py_sha256": sha256(det_new + "/infer.py"), "best_pt_sha256": sha256(det_new + "/best.pt")}
res["temporary_folder_equals_package_code_plus_new_weights"] = res["infer_py_sha256"] == EXPECT_DET_INFER and res["best_pt_sha256"] == EXPECT_NEW
gen = {r["id"]: r for r in read_tsv(PG + "/gen/pages_gen_val.tsv") if r["id"] in GEN_IDS}
sch = {r["id"]: r for r in read_tsv(PG + "/school2/pages_school_val.tsv") if r["id"] in SCH_IDS}
pages = [gen[i] for i in GEN_IDS] + [sch[i] for i in SCH_IDS]
for p in pages:
assert "val" in p["id"] and "test" not in p["id"]
man, hi = W + "/pages5.tsv", W + "/pages5_hires.tsv"
with open(man, "w", encoding="utf-8", newline="") as f:
f.write("id\timage\n")
for p in pages:
f.write("%s\t%s\n" % (p["id"], p["image"]))
with open(hi, "w", encoding="utf-8", newline="") as f:
f.write("id\timage\tscale\n")
for p in pages:
if p["id"].startswith("school_"):
f.write("%s\t%s\t%r\n" % (p["id"], school_orig(p["id"]), 1.0 / float(p["scale"])))
res["manifest_equals_rc1"] = open(man, "rb").read() == open(OLD + "/pages5.tsv", "rb").read()
res["hires_equals_rc1"] = open(hi, "rb").read() == open(OLD + "/pages5_hires.tsv", "rb").read()
out_p, out_l, out_b, mods = W + "/page_pages.tsv", W + "/page_lines.tsv", W + "/page_boxes.tsv", W + "/mods_page.json"
r = run([PY_VLM, "-B", "-I", PAGE_PKG + "/infer.py", "--manifest", man, "--out", out_p, "--lines-out", out_l, "--hires-tsv", hi,
"--detector-dir", det_new, "--detector-python", PY_KR, "--device", "cpu", "--threads", "16", "--keep-boxes", out_b,
"--report-modules", mods], "page_pipeline_new_detector", W + "/run")
res["run"] = r
res["arguments_as_rc1_step6_plus"] = "--detector-dir " + det_new
if r["exit"] != 0:
return res
mj = json.load(open(mods, encoding="utf-8"))
res["modules_under_CODE_src_or_scripts"] = [m for m in mj["modules"] if m.startswith(CODE + "/src") or m.startswith(CODE + "/scripts")]
new_boxes = {x["id"]: json.loads(x["boxes"]) for x in read_tsv(out_b)}
old_boxes = {x["id"]: json.loads(x["boxes"]) for x in read_tsv(OLD + "/page_boxes.tsv")}
new_lines, old_lines = lines_by_page(out_l), lines_by_page(OLD + "/page_lines.tsv")
old_check = json.load(open(OLD + "/check_results.json", encoding="utf-8"))["step6_page_pipeline"]
old_rows = {x["id"]: x for x in old_check["per_page"]}
per, tot = [], {"all": [0, 0, 0, 0, 0], "gen": [0, 0, 0, 0, 0], "school": [0, 0, 0, 0, 0]}
for p in pages:
pid = p["id"]
ref = json.loads(p["ref_lines_json"])
nl = [x["text"] for x in new_lines.get(pid, [])]
ol = [x["text"] for x in old_lines.get(pid, [])]
hyp_new, hyp_old = [t for t in nl if t], [t for t in ol if t]
ro_n, of_n, n = page_cers(hyp_new, ref)
ro_o, of_o, n2 = page_cers(hyp_old, ref)
assert n == n2
for k in ("all", "gen" if pid.startswith("pg_") else "school"):
t = tot[k]
t[0] += ro_o
t[1] += of_o
t[2] += ro_n
t[3] += of_n
t[4] += n
ob, nb = old_boxes[pid], new_boxes[pid]
m = match_boxes(ob, nb)
diffs = [max(abs(u - v) for u, v in zip(ob[i], nb[j])) for i, j, _ in m]
# texts on boxes that are the same in both runs (all four coordinates equal after rounding to 0.1 px)
okey = {tuple(round(float(x[c]), 1) for c in ("x0", "y0", "x1", "y1")): x["text"] for x in old_lines.get(pid, [])}
nkey = {tuple(round(float(x[c]), 1) for c in ("x0", "y0", "x1", "y1")): x["text"] for x in new_lines.get(pid, [])}
same_box = sorted(set(okey) & set(nkey))
same_box_text_diff = [[list(k), okey[k], nkey[k]] for k in same_box if okey[k] != nkey[k]]
sm = difflib.SequenceMatcher(a=hyp_old, b=hyp_new, autojunk=False)
ops = [(tag, hyp_old[i1:i2], hyp_new[j1:j2]) for tag, i1, i2, j1, j2 in sm.get_opcodes() if tag != "equal"]
per.append({
"id": pid, "ref_lines": len(ref), "ref_chars": n,
"boxes_old": len(ob), "boxes_new": len(nb), "boxes_matched_iou_0.5": len(m),
"boxes_old_unmatched": len(ob) - len(m), "boxes_new_unmatched": len(nb) - len(m),
"matched_min_iou": round(min((v for _, _, v in m), default=float("nan")), 4),
"matched_max_abs_coord_diff_px": round(max(diffs, default=0.0), 1),
"matched_mean_abs_coord_diff_px": round(float(np.mean(diffs)) if diffs else 0.0, 2),
"boxes_identical_coords": len(same_box),
"identical_boxes_with_different_text": len(same_box_text_diff), "identical_boxes_text_diffs_first5": same_box_text_diff[:5],
"hyp_lines_old": len(hyp_old), "hyp_lines_new": len(hyp_new),
"hyp_lines_equal_in_order": sum(b.size for b in sm.get_matching_blocks()),
"hyp_line_lists_identical": hyp_old == hyp_new,
"line_diff_segments_first8": [[t, a, b] for t, a, b in ops[:8]],
"ro_cer_old": ro_o / max(n, 1), "ro_cer_new": ro_n / max(n, 1), "of_cer_old": of_o / max(n, 1), "of_cer_new": of_n / max(n, 1),
"ro_cer_old_rc1_report_rounded": old_rows[pid]["ro_cer"], "of_cer_old_rc1_report_rounded": old_rows[pid]["of_cer"],
"old_recomputed_equals_rc1_report": round(ro_o / max(n, 1), 4) == old_rows[pid]["ro_cer"] and round(of_o / max(n, 1), 4) == old_rows[pid]["of_cer"],
"page_text_identical": [x for x in read_tsv(out_p) if x["id"] == pid][0]["text"] == [x for x in read_tsv(OLD + "/page_pages.tsv") if x["id"] == pid][0]["text"],
})
res["per_page"] = per
res["micro"] = {k: {"ref_chars": v[4], "ro_cer_old": v[0] / max(v[4], 1), "of_cer_old": v[1] / max(v[4], 1),
"ro_cer_new": v[2] / max(v[4], 1), "of_cer_new": v[3] / max(v[4], 1),
"ro_edits_old": v[0], "of_edits_old": v[1], "ro_edits_new": v[2], "of_edits_new": v[3]} for k, v in tot.items()}
res["micro_old_equals_rc1_report"] = abs(res["micro"]["all"]["ro_cer_old"] - old_check["micro_ro_cer"]) < 1e-12 and abs(res["micro"]["all"]["of_cer_old"] - old_check["micro_of_cer"]) < 1e-12
res["old_run"] = "job 55230 (rc1 final check), DATA/tmp/rc1_check/page_{boxes,lines,pages}.tsv and check_results.json step6_page_pipeline"
return res
def main():
t0 = time.time()
RES["started_utc"] = utc()
RES["slurm_job"] = os.environ.get("SLURM_JOB_ID")
RES["host"] = os.uname().nodename
RES["validation_only"] = True
RES["step1_sha256"] = step1()
say("step1", json.dumps({k: v for k, v in RES["step1_sha256"].items() if "equal" in k}))
RES["step2_checkpoint_metadata"] = step2()
RES["step3_results_csv"] = step3(RES["step2_checkpoint_metadata"])
RES["step4_page_lists"] = step4()
say("step4", json.dumps({k: v for k, v in RES["step4_page_lists"].items() if not isinstance(v, dict)}))
RES["step5_page_pipeline"] = step5()
RES["finished_utc"] = utc()
RES["seconds_total"] = round(time.time() - t0, 1)
with open(W + "/d5_check_results.json", "w", encoding="utf-8") as f:
json.dump(RES, f, indent=1, ensure_ascii=False, default=str)
say("done", W + "/d5_check_results.json")
if __name__ == "__main__":
main()