File size: 39,308 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 | """R5 DATA: build the real-data manifests of round R5 (shared TSV format of the R5 common specification).
Stages (run in this order; each stage writes its outputs and a stage log, and is skipped if its log exists, unless --force):
kohtd K1 split -> kohtd_{train,val,test}, kohtd_screen_v1 (V1, unchanged), kohtd_lmtune (500 validation crops not in V1, seed 20261121)
hkr HKR words (Kaggle mirror zip): extract jpg, official split (train / val / test1 / test2) from the project's HKR audit manifest
chd Cyrillic Handwriting Dataset (CHD): extract png; official train / test; validation carved from train by word type
school school_notebooks_ru: word crops from pupil_text polygons, page split kept
rukopys RUKOPYS test: handwritten, legible, Ukrainian line crops from the boxes (test only)
hash sha256 + perceptual hash (64-bit pHash) of every image in every manifest
dedupe drop train images that are byte-identical or near-identical (pHash distance <= 4) to a val or test image of any source
Raw manifests (before dedupe) go to DATA/data/processed/r5/manifests_pre_dedupe/, final ones to .../r5/manifests/.
Nothing here trains or scores a model. Test images are read only to cut line crops (rukopys, school) and to hash them for the duplicate check; none is shown or scored.
"""
import argparse
import collections
import csv
import gzip
import hashlib
import io
import json
import multiprocessing as mp
import os
import sys
import time
import unicodedata
import zipfile
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
DATA = Path("/path/to/TURKIC_OCR_DATA")
RAW = DATA / "data/raw"
PROC = DATA / "data/processed"
R5 = PROC / "r5"
PRE = R5 / "manifests_pre_dedupe"
MAN = R5 / "manifests"
IMG = R5 / "images"
LOGS = R5 / "build_logs"
HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]
KK_LETTERS = set("әғқңөұүһіӘҒҚҢӨҰҮҺІ")
KOHTD_IMG = PROC / "kohtd_words_raw/KOHTD_dataset/HK_dataset/img"
K1 = PROC / "kohtd_split_v1"
V1_PATH = DATA / "outputs/j11_stage1_kohtd/screen_set_v1.tsv"
V1_SHA = "aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec"
HKR_MANIFEST = R5 / "inputs/hkr_manifest.tsv.gz"
CRC = cv2.IMWRITE_PNG_COMPRESSION
NPROC = int(os.environ.get("SLURM_CPUS_PER_TASK", "4"))
def nfc(s):
return unicodedata.normalize("NFC", s)
def clean(s):
"""NFC, tabs and line breaks to one space, strip the ends."""
s = nfc(s)
for ch in ("\t", "\r", "\n"):
s = s.replace(ch, " ")
return s.strip()
def write_manifest(path, rows):
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8", newline="") as f:
f.write("\t".join(HDR) + "\n")
for r in rows:
f.write("\t".join(str(r[k]) for k in HDR) + "\n")
def read_manifest(path):
rows = []
with open(path, encoding="utf-8", newline="") as f:
header = f.readline().rstrip("\n").split("\t")
assert header == HDR, (path, header)
for line in f:
parts = line.rstrip("\n").split("\t")
assert len(parts) == len(HDR), (path, parts)
rows.append(dict(zip(HDR, parts)))
return rows
def sha256_file(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def stage_log(name, info):
LOGS.mkdir(parents=True, exist_ok=True)
info["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with open(LOGS / f"stage_{name}.json", "w", encoding="utf-8") as f:
json.dump(info, f, ensure_ascii=False, indent=1)
def row(id_, image, text, lang, script, kind, source, split, group, unit):
return dict(id=id_, image=str(image), text=text, lang=lang, script=script, kind=kind,
source=source, split=split, group=group, unit=unit)
# ----------------------------------------------------------------------------- KOHTD
def read_k1(path):
out = []
with open(path, encoding="utf-8", newline="") as f:
header = f.readline().rstrip("\n").split("\t")
assert header[:3] == ["crop_file", "form_id", "label"], header
for line in f:
parts = line.rstrip("\n").split("\t")
# label is the third column; key_type (last) never contains a tab
crop_file, form_id = parts[0], parts[1]
key_type = parts[-1] if len(header) == 4 else ""
label = "\t".join(parts[2:-1]) if len(header) == 4 else "\t".join(parts[2:])
out.append((crop_file, form_id, label, key_type))
return out
def stage_kohtd():
info = {"stage": "kohtd"}
sets = {}
altered = collections.Counter()
for sp, fn in (("train", "train.tsv"), ("val", "validation.tsv"), ("test", "test.tsv")):
rows = []
for crop_file, form_id, label, key_type in read_k1(K1 / fn):
t = clean(label)
if t != label:
altered[sp] += 1
if key_type == "numbered":
grp = "kohtd_form_" + form_id
else: # scan-named crop: the unit is the scan file name (split_spec_v1, K1 report)
grp = "kohtd_scan_" + crop_file[:-4].replace("word_croped_", "", 1).rsplit("_", 2)[0]
rows.append(row("kohtd:" + crop_file[:-4], KOHTD_IMG / crop_file, t, "kk", "Cyrl", "hand_real",
"kohtd", "val" if sp == "val" else sp, grp, "word"))
sets[sp] = rows
# does every image exist?
missing = collections.Counter()
for sp, rows in sets.items():
for r in rows:
if not Path(r["image"]).exists():
missing[sp] += 1
info["missing_images"] = dict(missing)
info["labels_changed_by_cleaning"] = dict(altered)
info["empty_labels"] = {sp: sum(1 for r in rows if r["text"] == "") for sp, rows in sets.items()}
# train: empty labels are not usable targets; they are listed and dropped from TRAIN only
train_rows = [r for r in sets["train"] if r["text"] != ""]
info["train_empty_label_rows_dropped"] = len(sets["train"]) - len(train_rows)
write_manifest(PRE / "kohtd_train.tsv", train_rows)
write_manifest(PRE / "kohtd_val.tsv", sets["val"])
write_manifest(PRE / "kohtd_test.tsv", sets["test"])
# V1 screen set, unchanged
v1_sha = sha256_file(V1_PATH)
assert v1_sha == V1_SHA, v1_sha
val_by_file = {r["id"]: r for r in sets["val"]}
v1_rows = []
with open(V1_PATH, encoding="utf-8", newline="") as f:
header = f.readline().rstrip("\n").split("\t")
assert header == ["crop_file", "form_id", "label"], header
for line in f:
crop_file, form_id, label = line.rstrip("\n").split("\t")[:3]
rid = "kohtd:" + crop_file[:-4]
base = val_by_file[rid]
assert base["text"] == clean(label), (rid, base["text"], label)
v1_rows.append(dict(base))
write_manifest(PRE / "kohtd_screen_v1.tsv", v1_rows)
v1_ids = {r["id"] for r in v1_rows}
cand = [r for r in sets["val"] if r["id"] not in v1_ids]
rng = np.random.default_rng(20261121)
pick = np.sort(rng.choice(len(cand), size=500, replace=False))
lm_rows = [dict(cand[i]) for i in pick]
write_manifest(PRE / "kohtd_lmtune.tsv", lm_rows)
info.update(v1_sha256=v1_sha, v1_rows=len(v1_rows), lmtune_candidates=len(cand), lmtune_rows=len(lm_rows),
lmtune_method="numpy.random.default_rng(20261121).choice(len(candidates), 500, replace=False), sorted by index; "
"candidates = rows of kohtd_val.tsv (K1 validation.tsv order) whose crop is not in V1",
numpy=np.__version__,
counts={sp: len(rows) for sp, rows in sets.items()},
forms={sp: len({r["group"] for r in rows}) for sp, rows in sets.items()})
# sidecar: language evidence per label (Kazakh-specific letter or not)
ev = collections.Counter()
side = PRE / "kohtd_label_lang_evidence.tsv"
with open(side, "w", encoding="utf-8") as f:
f.write("id\tsplit\tevidence\n")
for sp, rows in (("train", train_rows), ("val", sets["val"]), ("test", sets["test"])):
for r in rows:
t = r["text"]
if any(c in KK_LETTERS for c in t):
e = "kk_specific_letter"
elif any("Ѐ" <= c <= "ӿ" for c in t):
e = "cyrillic_no_specific_letter"
else:
e = "no_cyrillic_letter"
ev[(sp, e)] += 1
f.write(f"{r['id']}\t{sp}\t{e}\n")
info["label_lang_evidence"] = {f"{k[0]}:{k[1]}": v for k, v in sorted(ev.items())}
stage_log("kohtd", info)
print(json.dumps(info, ensure_ascii=False)[:2000])
# ----------------------------------------------------------------------------- HKR
HKR_PREFIX = "HKR_Dataset_Words_Public/20200923_Dataset_Words_Public/"
def stage_hkr():
info = {"stage": "hkr"}
with gzip.open(HKR_MANIFEST, "rt", encoding="utf-8") as f:
rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
man = {r["id"]: r for r in rd}
info["manifest_rows"] = len(man)
z = zipfile.ZipFile(RAW / "hkr_words_kaggle_scispecai/hkr_dat.zip")
names = set(z.namelist())
out_dir = IMG / "hkr"
out_dir.mkdir(parents=True, exist_ok=True)
ann_keys = collections.Counter()
rows = {"train": [], "val": [], "test1": [], "test2": []}
n_text_diff = 0
n_missing_in_manifest = 0
for mid in sorted(man):
jn = HKR_PREFIX + "ann/" + mid + ".json"
jp = HKR_PREFIX + "img/" + mid + ".jpg"
if jn not in names or jp not in names:
info.setdefault("missing_in_zip", []).append(mid)
continue
ann = json.loads(z.read(jn).decode("utf-8"))
ann_keys.update(ann.keys())
text = clean(ann["description"])
if text != clean(man[mid]["text"]):
n_text_diff += 1
dst = out_dir / (mid + ".jpg")
if not dst.exists():
dst.write_bytes(z.read(jp))
parts = mid.split("_")
group = "hkr_t%s_i%s" % (parts[0], parts[2]) # template, filled-form instance (project inference, N9d / H1-10)
lang = "kk" if any(c in KK_LETTERS for c in text) else "ru"
sp = man[mid]["split"]
rows[sp].append(row("hkr:" + mid, dst, text, lang, "Cyrl", "hand_real", "hkr_words",
"train" if sp == "train" else "val" if sp == "val" else "test", group, "word"))
# zip entries not in manifest
zip_ids = {n[len(HKR_PREFIX + "img/"):-4] for n in names if n.startswith(HKR_PREFIX + "img/") and n.endswith(".jpg")}
n_missing_in_manifest = len(zip_ids - set(man))
info.update(ann_keys=dict(ann_keys), text_differs_from_manifest=n_text_diff, zip_ids_not_in_manifest=n_missing_in_manifest,
counts={k: len(v) for k, v in rows.items()},
kk_labelled={k: sum(1 for r in v if r["lang"] == "kk") for k, v in rows.items()},
groups={k: len({r["group"] for r in v}) for k, v in rows.items()})
# empty labels
for k in rows:
info.setdefault("empty_labels", {})[k] = sum(1 for r in rows[k] if r["text"] == "")
rows["train"] = [r for r in rows["train"] if r["text"] != ""]
write_manifest(PRE / "hkr_train.tsv", rows["train"])
write_manifest(PRE / "hkr_val.tsv", rows["val"])
write_manifest(PRE / "hkr_test1.tsv", rows["test1"])
write_manifest(PRE / "hkr_test2.tsv", rows["test2"])
info["manifest_sha256"] = sha256_file(HKR_MANIFEST)
stage_log("hkr", info)
print(json.dumps(info, ensure_ascii=False)[:2000])
# ----------------------------------------------------------------------------- CHD
def stage_chd():
info = {"stage": "chd"}
z = zipfile.ZipFile(RAW / "chd/archive.zip")
out_dir = IMG / "chd"
(out_dir / "train").mkdir(parents=True, exist_ok=True)
(out_dir / "test").mkdir(parents=True, exist_ok=True)
rows = {"train": [], "val": [], "test": []}
names = set(z.namelist())
carve = collections.Counter()
for sp in ("train", "test"):
raw = z.read(sp + ".tsv").decode("utf-8")
for line in raw.split("\n"):
line = line.rstrip("\r")
if not line.strip():
continue
fn, _, label = line.partition("\t")
text = clean(label)
member = sp + "/" + fn
if member not in names:
info.setdefault("missing_in_zip", []).append(member)
continue
dst = out_dir / sp / fn
if not dst.exists():
dst.write_bytes(z.read(member))
stem = fn[:-4]
# group = word type (CHD has no writer or page id): sha1 of the NFC label
gid = "chd_w" + hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
target = sp
if sp == "train":
h = int(hashlib.sha256(("R5-chd-val-v1:" + text).encode("utf-8")).hexdigest()[:8], 16) % 100
if h < 5:
target = "val"
rows[target].append(row("chd:" + sp + "_" + stem, dst, text, "ru", "Cyrl", "hand_real", "chd",
"val" if target == "val" else target, gid, "word"))
carve[target] += 1
info.update(counts={k: len(v) for k, v in rows.items()},
empty_labels={k: sum(1 for r in v if r["text"] == "") for k, v in rows.items()},
distinct_words={k: len({r["text"] for r in v}) for k, v in rows.items()},
val_rule="validation = train rows whose label word type has sha256('R5-chd-val-v1:'+label)[:8] mod 100 < 5, "
"so a word type is never in train and validation; official test unchanged")
for k in rows:
rows[k] = [r for r in rows[k] if r["text"] != ""] if k == "train" else rows[k]
write_manifest(PRE / "chd_train.tsv", rows["train"])
write_manifest(PRE / "chd_val.tsv", rows["val"])
write_manifest(PRE / "chd_test.tsv", rows["test"])
# overlap of word types between train and official test
tr = {r["text"] for r in rows["train"]}
te = [r["text"] for r in rows["test"]]
info["official_test_rows_whose_word_is_in_train"] = sum(1 for t in te if t in tr)
stage_log("chd", info)
print(json.dumps(info, ensure_ascii=False)[:2000])
# ----------------------------------------------------------------------------- school notebooks
def poly_pts(seg):
flat = seg[0] if seg and isinstance(seg[0], list) else seg
pts = np.array(flat, dtype=np.float32).reshape(-1, 2)
return pts
def cut_word(page, pts, pad=3):
"""Cut one word: axis-aligned patch around the polygon, levelled by the long edge of its minimum-area rectangle when tilted."""
H, W = page.shape[:2]
x, y, w, h = cv2.boundingRect(pts.astype(np.int32))
if w < 6 or h < 6:
return None
rect = cv2.minAreaRect(pts)
box = cv2.boxPoints(rect)
e0, e1 = box[1] - box[0], box[2] - box[1]
d = e0 if np.linalg.norm(e0) >= np.linalg.norm(e1) else e1
long_len, short_len = max(np.linalg.norm(e0), np.linalg.norm(e1)), min(np.linalg.norm(e0), np.linalg.norm(e1))
theta = float(np.degrees(np.arctan2(d[1], d[0])))
if theta > 90:
theta -= 180
if theta <= -90:
theta += 180
if abs(theta) < 2.0 or abs(theta) > 30 or long_len < 1.2 * short_len:
x0, y0, x1, y1 = max(0, x - pad), max(0, y - pad), min(W, x + w + pad), min(H, y + h + pad)
c = page[y0:y1, x0:x1]
return c if c.shape[0] >= 6 and c.shape[1] >= 6 else None
r = int(np.hypot(w, h)) + pad + 4
px0, py0, px1, py1 = max(0, x - r), max(0, y - r), min(W, x + w + r), min(H, y + h + r)
patch = page[py0:py1, px0:px1]
cx, cy = rect[0][0] - px0, rect[0][1] - py0
M = cv2.getRotationMatrix2D((cx, cy), theta, 1.0)
rot = cv2.warpAffine(patch, M, (patch.shape[1], patch.shape[0]), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
p2 = cv2.transform((pts - np.array([px0, py0], dtype=np.float32)).reshape(-1, 1, 2), M).reshape(-1, 2)
x2, y2, w2, h2 = cv2.boundingRect(p2.astype(np.int32))
x0, y0 = max(0, x2 - pad), max(0, y2 - pad)
x1, y1 = min(rot.shape[1], x2 + w2 + pad), min(rot.shape[0], y2 + h2 + pad)
c = rot[y0:y1, x0:x1]
return c if c.shape[0] >= 6 and c.shape[1] >= 6 else None
def school_page_job(args):
split, page_info, words, src = args # words: list of (ann_index, text, seg)
fn = page_info["file_name"]
W, H = page_info["width"], page_info["height"]
stem = fn.rsplit(".", 1)[0]
out_dir = IMG / "school" / split / stem
out_dir.mkdir(parents=True, exist_ok=True)
try:
if src[0] == "zip":
with zipfile.ZipFile(src[1]) as z:
data = z.read("images/" + fn)
im = Image.open(io.BytesIO(data))
else:
im = Image.open(src[1] + "/" + fn)
im.load()
size_note = "ok"
if im.size != (W, H):
if im.size == (H, W):
from PIL import ImageOps
im = ImageOps.exif_transpose(im)
size_note = "exif_transposed"
if im.size != (W, H):
return fn, [], {"error": "size_mismatch", "got": im.size, "want": (W, H)}
page = cv2.cvtColor(np.array(im.convert("RGB")), cv2.COLOR_RGB2BGR)
except Exception as e: # noqa
return fn, [], {"error": repr(e)}
out_rows = []
skipped = collections.Counter()
for ai, text, seg in words:
try:
pts = poly_pts(seg)
c = cut_word(page, pts)
except Exception:
c = None
if c is None:
skipped["bad_polygon_or_tiny"] += 1
continue
dst = out_dir / f"{ai}.png"
cv2.imwrite(str(dst), c, [CRC, 1])
out_rows.append((ai, text, str(dst)))
return fn, out_rows, {"skipped": dict(skipped), "size_note": size_note}
def stage_school():
info = {"stage": "school"}
base = RAW / "school_notebooks_ru"
zip_path = str(base / "images.zip")
jobs = []
for sp in ("train", "val", "test"):
d = json.load(open(base / f"annotations_{sp}.json", encoding="utf-8"))
pages = {i["id"]: i for i in d["images"]}
words = collections.defaultdict(list)
n_empty = 0
for ai, a in enumerate(d["annotations"]):
if a["category_id"] != 0:
continue
t = clean((a.get("attributes") or {}).get("translation") or "")
if t == "":
n_empty += 1
continue
words[a["image_id"]].append((ai, t, a["segmentation"]))
info.setdefault("empty_translation_skipped", {})[sp] = n_empty
src = ("zip", zip_path) if sp == "train" else ("dir", str(base / "val_test_images" / sp))
for iid, w in words.items():
jobs.append((sp, pages[iid], w, src))
info["pages_with_words"] = collections.Counter(j[0] for j in jobs)
t0 = time.time()
rows = {"train": [], "val": [], "test": []}
errors = {}
skipped = collections.Counter()
with mp.Pool(NPROC) as pool:
for k, (sp_job, res) in enumerate(zip(jobs, pool.imap(school_page_job, jobs, chunksize=4))):
sp = sp_job[0]
fn, out_rows, meta = res
if "error" in meta:
errors[fn] = meta
for kk, v in meta.get("skipped", {}).items():
skipped[kk] += v
stem = fn.rsplit(".", 1)[0]
for ai, text, dst in out_rows:
rows[sp].append(row(f"school:{sp}_{stem}_{ai}", dst, text, "ru", "Cyrl", "hand_real", "school_notebooks_ru",
sp, "school_page_" + stem, "word"))
if k % 200 == 0:
print("school pages", k, "of", len(jobs), "elapsed", round(time.time() - t0), flush=True)
info.update(counts={k: len(v) for k, v in rows.items()}, page_errors=errors, skipped=dict(skipped),
pages={k: len({r["group"] for r in v}) for k, v in rows.items()},
crop_rule="category pupil_text (id 0) with a non-empty translation; axis-aligned patch of the polygon with 3 px padding, "
"levelled by the long edge of the polygon's minimum-area rectangle when the tilt is between 2 and 30 degrees; no masking",
pages_total=len(jobs))
write_manifest(PRE / "school_train.tsv", rows["train"])
write_manifest(PRE / "school_val.tsv", rows["val"])
write_manifest(PRE / "school_test.tsv", rows["test"])
stage_log("school", info)
print(json.dumps(info, ensure_ascii=False, default=str)[:2000])
# ----------------------------------------------------------------------------- RUKOPYS test
def stage_rukopys():
info = {"stage": "rukopys"}
base = RAW / "rukopys_test/test"
recs = [json.loads(l) for l in open(base / "metadata.jsonl", encoding="utf-8")]
rows = []
skip = collections.Counter()
for rec in recs:
stem = rec["file_name"].split("/")[-1].rsplit(".", 1)[0]
page = cv2.imread(str(base / rec["file_name"]), cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
if page is None:
skip["page_unreadable"] += 1
continue
H, W = page.shape[:2]
if (W, H) != (rec["image_width"], rec["image_height"]):
skip["size_mismatch_page"] += 1
continue
out_dir = IMG / "rukopys" / stem
out_dir.mkdir(parents=True, exist_ok=True)
for ri, reg in enumerate(rec["regions"]):
if reg["type"] != "handwritten":
continue
if reg["language"] != "uk" or reg["legibility"] != "legible":
skip["handwritten_not_uk_or_illegible"] += 1
continue
t = clean(reg["text"])
if t == "" or "[illegible]" in t or "~~" in t:
skip["empty_or_marked_text"] += 1
continue
x1, y1, x2, y2 = [int(v) for v in reg["bbox"]]
x1, y1, x2, y2 = max(0, x1 - 4), max(0, y1 - 4), min(W, x2 + 4), min(H, y2 + 4)
if x2 - x1 < 8 or y2 - y1 < 8:
skip["tiny_box"] += 1
continue
dst = out_dir / f"{ri}.png"
cv2.imwrite(str(dst), page[y1:y2, x1:x2], [CRC, 1])
rows.append(row(f"rukopys:{stem}_{ri}", dst, t, "other", "Cyrl", "hand_real", "rukopys_test", "test",
"rukopys_page_" + stem, "line"))
info.update(counts={"test": len(rows)}, pages=len({r["group"] for r in rows}), skipped=dict(skip),
rule="regions of type handwritten, language uk, legibility legible, no ~~ or [illegible] markers; bbox plus 4 px; "
"orientation as stored (README v2.4: boxes agree with pixels)")
write_manifest(PRE / "rukopys_test.tsv", rows)
stage_log("rukopys", info)
print(json.dumps(info, ensure_ascii=False)[:2000])
# ----------------------------------------------------------------------------- hashing
def phash64(gray):
small = cv2.resize(gray, (32, 32), interpolation=cv2.INTER_AREA).astype(np.float32)
dct = cv2.dct(small)
low = dct[:8, :8]
med = np.median(low)
bits = (low > med).flatten()
return int.from_bytes(np.packbits(bits).tobytes(), "big")
def hash_job(item):
rid, path = item
try:
data = open(path, "rb").read()
sha = hashlib.sha256(data).hexdigest()
arr = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_GRAYSCALE | cv2.IMREAD_IGNORE_ORIENTATION)
if arr is None:
return rid, sha, "", 0, 0
return rid, sha, "%016x" % phash64(arr), arr.shape[1], arr.shape[0]
except Exception:
return rid, "", "", 0, 0
ALL_MANIFESTS = ["kohtd_train", "kohtd_val", "kohtd_test", "hkr_train", "hkr_val", "hkr_test1", "hkr_test2",
"chd_train", "chd_val", "chd_test", "school_train", "school_val", "school_test", "rukopys_test"]
def stage_hash():
info = {"stage": "hash"}
items = []
for m in ALL_MANIFESTS:
for r in read_manifest(PRE / (m + ".tsv")):
items.append((r["id"], r["image"]))
# val rows that are also in V1 / lmtune are the same ids: nothing to add
print("hashing", len(items), flush=True)
t0 = time.time()
out = LOGS / "hashes.tsv"
n_fail = 0
with open(out, "w", encoding="utf-8") as f, mp.Pool(NPROC) as pool:
f.write("id\tsha256\tphash\twidth\theight\n")
for k, res in enumerate(pool.imap(hash_job, items, chunksize=400)):
if res[1] == "" or res[2] == "":
n_fail += 1
f.write("%s\t%s\t%s\t%d\t%d\n" % res)
if k % 50000 == 0:
print("hashed", k, round(time.time() - t0), flush=True)
info.update(images=len(items), failed=n_fail, seconds=round(time.time() - t0),
hash="64-bit pHash of the grey image: 32x32 INTER_AREA, DCT, low 8x8, bit = coefficient > median (imagehash-style); distance = Hamming")
stage_log("hash", info)
print(info)
# ----------------------------------------------------------------------------- dedupe
def stage_dedupe():
info = {"stage": "dedupe"}
hashes = {}
with open(LOGS / "hashes.tsv", encoding="utf-8") as f:
f.readline()
for line in f:
rid, sha, ph, w, h = line.rstrip("\n").split("\t")
hashes[rid] = (sha, int(ph, 16) if ph else None, int(w), int(h))
man = {m: read_manifest(PRE / (m + ".tsv")) for m in ALL_MANIFESTS}
meta = [] # (id, source, split, text, manifest)
for m, rows in man.items():
for r in rows:
meta.append((r["id"], r["source"], r["split"], r["text"], m))
idx = {t[0]: i for i, t in enumerate(meta)}
ids = [t[0] for t in meta]
ph = np.array([hashes[i][1] if hashes[i][1] is not None else 0 for i in ids], dtype=np.uint64)
ok = np.array([hashes[i][1] is not None for i in ids])
sha = [hashes[i][0] for i in ids]
split = np.array([t[2] for t in meta])
is_train = split == "train"
is_ref = (split == "val") | (split == "test")
info["images_hashed"] = len(ids)
info["images_without_hash"] = int((~ok).sum())
# exact duplicates: sha256 groups with a train member and a val/test member
bysha = collections.defaultdict(list)
for i, s in enumerate(sha):
if s:
bysha[s].append(i)
drop = {} # train index -> (reason, partner index)
n_exact_groups = 0
for s, members in bysha.items():
if len(members) < 2:
continue
trn = [i for i in members if is_train[i]]
ref = [i for i in members if is_ref[i]]
if trn and ref:
n_exact_groups += 1
for i in trn:
drop[i] = ("byte_identical", ref[0])
info["exact_groups_train_vs_valtest"] = n_exact_groups
info["train_dropped_exact"] = len(drop)
# near duplicates (distance <= 4) with multi-index hashing: 5 chunks of the 64 bits
def near_pairs(a_idx, b_idx, maxd=4):
"""best partner (b, distance) for every a with Hamming(ph[a], ph[b]) <= maxd. Exact: five 13/12-bit chunks;
a pair at distance <= 4 differs in at most 4 chunks, so it shares at least one chunk."""
a_idx = np.array(a_idx)
b_idx = np.array(b_idx)
pa, pb = ph[a_idx], ph[b_idx]
best = {}
for s0, wd in zip([0, 13, 26, 39, 52], [13, 13, 13, 13, 12]):
mask = np.uint64((1 << wd) - 1)
ka = (pa >> np.uint64(s0)) & mask
kb = (pb >> np.uint64(s0)) & mask
order_b = np.argsort(kb, kind="stable")
kb_sorted = kb[order_b]
order_a = np.argsort(ka, kind="stable")
ka_sorted = ka[order_a]
keys, starts = np.unique(ka_sorted, return_index=True)
ends = np.append(starts[1:], len(ka_sorted))
for key, e_lo, e_hi in zip(keys, starts, ends):
lo = np.searchsorted(kb_sorted, key, "left")
hi = np.searchsorted(kb_sorted, key, "right")
if hi == lo:
continue
aa = order_a[e_lo:e_hi]
bb = order_b[lo:hi]
blk = max(1, int(2e7 // len(bb)))
for j in range(0, len(aa), blk):
sub = aa[j:j + blk]
d = np.bitwise_count(pa[sub][:, None] ^ pb[bb][None, :]).astype(np.int16)
dm = np.where(d <= maxd, d, 99)
am = dm.argmin(axis=1)
mv = dm[np.arange(len(sub)), am]
for u in np.nonzero(mv <= maxd)[0]:
ai, bi, dv = int(a_idx[sub[u]]), int(b_idx[bb[am[u]]]), int(mv[u])
if ai not in best or dv < best[ai][1]:
best[ai] = (bi, dv)
return best
tr_idx = [i for i in range(len(ids)) if is_train[i] and ok[i]]
ref_idx = [i for i in range(len(ids)) if is_ref[i] and ok[i]]
t0 = time.time()
near_train = near_pairs(tr_idx, ref_idx)
info["near_pair_search_seconds"] = round(time.time() - t0)
info["train_images_with_a_near_partner_in_valtest"] = len(near_train)
n_near_only = 0
for a, (b, d) in near_train.items():
if a not in drop:
drop[a] = ("near_phash_d%d" % d, b)
n_near_only += 1
info["train_dropped_near_only"] = n_near_only
info["train_dropped_total"] = len(drop)
# HKR vs KOHTD: any split of KOHTD (the owner's extra check); HKR train rows overlapping any KOHTD image are dropped
hk_all = [i for i, t in enumerate(meta) if t[1] == "hkr_words" and ok[i]]
ko_all = [i for i, t in enumerate(meta) if t[1] == "kohtd" and ok[i]]
ko_sha = collections.defaultdict(list)
for i in ko_all:
ko_sha[sha[i]].append(i)
hk_exact = [i for i in hk_all if sha[i] in ko_sha]
hk_near_a = near_pairs(hk_all, ko_all)
n_hk_extra = 0
for i in set(hk_exact) | set(hk_near_a):
if is_train[i] and i not in drop:
if i in hk_near_a:
b, d = hk_near_a[i]
drop[i] = ("hkr_vs_kohtd_near_d%d" % d, b)
else:
drop[i] = ("hkr_vs_kohtd_byte_identical", ko_sha[sha[i]][0])
n_hk_extra += 1
info["hkr_vs_kohtd"] = {
"hkr_images_checked": len(hk_all), "kohtd_images_checked": len(ko_all),
"hkr_byte_identical_to_a_kohtd_image": len(hk_exact),
"hkr_with_near_phash_partner_in_kohtd": len(hk_near_a),
"hkr_train_rows_additionally_dropped": n_hk_extra,
}
# diagnostics: of the dropped, how many pairs share the same label (true duplicates) and which partner split / source
why = collections.Counter()
same_label = collections.Counter()
pair_src = collections.Counter()
for a, (reason, b) in drop.items():
key = reason.split("_d")[0] if reason.startswith("near") else reason
why[key] += 1
same_label[(key, meta[a][3] == meta[b][3])] += 1
pair_src[(meta[a][1], meta[b][1], meta[b][2])] += 1
info["dropped_by_reason"] = dict(why)
info["dropped_pairs_label_same_vs_different"] = {f"{k[0]}|same_label={k[1]}": v for k, v in same_label.items()}
info["dropped_train_source_vs_partner_source_split"] = {f"{k[0]} <- {k[1]}:{k[2]}": v for k, v in sorted(pair_src.items())}
# diagnostics only: val vs test near-duplicates across sets (not acted on)
v_idx = [i for i in range(len(ids)) if split[i] == "val" and ok[i]]
t_idx = [i for i in range(len(ids)) if split[i] == "test" and ok[i]]
vt = near_pairs(v_idx, t_idx)
info["diagnostic_val_images_with_a_near_partner_in_test"] = len(vt)
info["diagnostic_val_vs_test_by_source"] = dict(collections.Counter(f"{meta[a][1]}:val ~ {meta[b][0].split(':')[0]}:test" for a, (b, d) in vt.items()))
# rewrite train manifests, write the dropped list
per = {}
drop_ids = {ids[a]: (reason, ids[b]) for a, (reason, b) in drop.items()}
for m, rows in man.items():
if not m.endswith("_train"):
write_manifest(MAN / (m + ".tsv"), rows)
continue
keep = [r for r in rows if r["id"] not in drop_ids]
per[m] = {"before": len(rows), "after": len(keep), "dropped": len(rows) - len(keep)}
write_manifest(MAN / (m + ".tsv"), keep)
# subsets of validation (V1, lmtune) copied unchanged
for m in ("kohtd_screen_v1", "kohtd_lmtune"):
write_manifest(MAN / (m + ".tsv"), read_manifest(PRE / (m + ".tsv")))
info["train_manifests"] = per
with open(LOGS / "dedupe_dropped.tsv", "w", encoding="utf-8") as f:
f.write("dropped_train_id\treason\tpartner_id\tpartner_split\tdropped_label\tpartner_label\n")
for a, (reason, b) in sorted(drop.items(), key=lambda kv: ids[kv[0]]):
f.write("\t".join([ids[a], reason, ids[b], meta[b][2], meta[a][3], meta[b][3]]) + "\n")
stage_log("dedupe", info)
print(json.dumps(info, ensure_ascii=False)[:3500])
# ----------------------------------------------------------------------------- synthetic manifests of GEN: hash and report-only duplicate check
def synth_manifest_names():
return sorted(q.stem for pat in ("synth_*.tsv", "az_localdoc_*.tsv") for q in MAN.glob(pat) if q.stem.rsplit("_", 1)[-1] in ("train", "val", "test"))
def stage_hash_synth():
"""Hash the images of GEN's synthetic manifests (synth_*_{train,val,test}), clutter and page images included, and of the extra Azerbaijani test manifest."""
info = {"stage": "hash_synth"}
items = []
names = synth_manifest_names()
for m in names:
for r in read_manifest(MAN / (m + ".tsv")):
items.append((r["id"], r["image"]))
print("hashing synthetic", len(items), "images from", names, flush=True)
t0 = time.time()
n_fail = 0
with open(LOGS / "hashes_synth.tsv", "w", encoding="utf-8") as f, mp.Pool(NPROC) as pool:
f.write("id\tsha256\tphash\twidth\theight\n")
for k, res in enumerate(pool.imap(hash_job, items, chunksize=400)):
if res[1] == "" or res[2] == "":
n_fail += 1
f.write("%s\t%s\t%s\t%d\t%d\n" % res)
info.update(manifests=names, images=len(items), failed=n_fail, seconds=round(time.time() - t0))
stage_log("hash_synth", info)
print(info)
def near_best(ph, a_idx, b_idx, maxd=4):
a_idx, b_idx = np.array(a_idx), np.array(b_idx)
pa, pb = ph[a_idx], ph[b_idx]
best = {}
for s0, wd in zip([0, 13, 26, 39, 52], [13, 13, 13, 13, 12]):
mask = np.uint64((1 << wd) - 1)
ka = (pa >> np.uint64(s0)) & mask
kb = (pb >> np.uint64(s0)) & mask
order_b = np.argsort(kb, kind="stable")
kb_sorted = kb[order_b]
order_a = np.argsort(ka, kind="stable")
ka_sorted = ka[order_a]
keys, starts = np.unique(ka_sorted, return_index=True)
ends = np.append(starts[1:], len(ka_sorted))
for key, e_lo, e_hi in zip(keys, starts, ends):
lo, hi = np.searchsorted(kb_sorted, key, "left"), np.searchsorted(kb_sorted, key, "right")
if hi == lo:
continue
aa, bb = order_a[e_lo:e_hi], order_b[lo:hi]
blk = max(1, int(2e7 // len(bb)))
for j in range(0, len(aa), blk):
sub = aa[j:j + blk]
d = np.bitwise_count(pa[sub][:, None] ^ pb[bb][None, :]).astype(np.int16)
dm = np.where(d <= maxd, d, 99)
am = dm.argmin(axis=1)
mv = dm[np.arange(len(sub)), am]
for u in np.nonzero(mv <= maxd)[0]:
ai, bi, dv = int(a_idx[sub[u]]), int(b_idx[bb[am[u]]]), int(mv[u])
if ai not in best or dv < best[ai][1]:
best[ai] = (bi, dv)
return best
def stage_dedupe_all():
"""Report-only duplicate check over ALL manifests in the folder (real and synthetic). Rewrites nothing.
Writes build_logs/dedupe_all.json and dedupe_all_dropped.tsv: the train images that WOULD be dropped, with reason and partner."""
info = {"stage": "dedupe_all", "mode": "report only: no manifest is rewritten"}
hashes = {}
for fn in ("hashes.tsv", "hashes_synth.tsv"):
if not (LOGS / fn).exists():
continue
with open(LOGS / fn, encoding="utf-8") as f:
f.readline()
for line in f:
rid, sha, ph_, w, h = line.rstrip("\n").split("\t")
hashes[rid] = (sha, int(ph_, 16) if ph_ else None)
names = [q.stem for q in sorted(MAN.glob("*.tsv")) if not q.name.endswith(".meta.tsv") and q.stem not in ("kohtd_screen_v1", "kohtd_lmtune", "kohtd_test_p2", "kohtd_test_p2b", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000")]
meta = []
for m in names:
for r in read_manifest(MAN / (m + ".tsv")):
if r["id"] in hashes:
meta.append((r["id"], r["source"], r["split"], r["text"], m, r["kind"]))
ids = [t[0] for t in meta]
ph = np.array([hashes[i][1] if hashes[i][1] is not None else 0 for i in ids], dtype=np.uint64)
ok = np.array([hashes[i][1] is not None for i in ids])
split = np.array([t[2] for t in meta])
tr = [i for i in range(len(ids)) if split[i] == "train" and ok[i]]
rf = [i for i in range(len(ids)) if split[i] in ("val", "test") and ok[i]]
bysha = collections.defaultdict(list)
for i in rf:
bysha[hashes[ids[i]][0]].append(i)
drop = {}
for i in tr:
s_ = hashes[ids[i]][0]
if s_ in bysha:
drop[i] = ("byte_identical", bysha[s_][0])
near = near_best(ph, tr, rf)
for a, (b, d) in near.items():
if a not in drop:
drop[a] = ("near_phash_d%d" % d, b)
by = collections.Counter((meta[a][4], r_.split("_d")[0] if r_.startswith("near") else r_, meta[a][5]) for a, (r_, b) in drop.items())
info.update(manifests_checked=names, images=len(ids), train_images=len(tr), valtest_images=len(rf), would_drop_total=len(drop),
would_drop_by_manifest_and_reason={f"{k[0]} | {k[1]} | kind {k[2]}": v for k, v in sorted(by.items())})
with open(LOGS / "dedupe_all_dropped.tsv", "w", encoding="utf-8") as f:
f.write("train_id\tmanifest\tkind\treason\tpartner_id\tpartner_manifest\tsame_label\n")
for a, (r_, b) in sorted(drop.items(), key=lambda kv: ids[kv[0]]):
f.write("\t".join([ids[a], meta[a][4], meta[a][5], r_, ids[b], meta[b][4], str(meta[a][3] == meta[b][3])]) + "\n")
stage_log("dedupe_all", info)
print(json.dumps(info, ensure_ascii=False)[:3000])
STAGES = {"kohtd": stage_kohtd, "hkr": stage_hkr, "chd": stage_chd, "school": stage_school,
"rukopys": stage_rukopys, "hash": stage_hash, "dedupe": stage_dedupe,
"hash_synth": stage_hash_synth, "dedupe_all": stage_dedupe_all}
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("stages", nargs="+")
ap.add_argument("--force", action="store_true")
a = ap.parse_args()
for s in a.stages:
if (LOGS / f"stage_{s}.json").exists() and not a.force:
print("skip (log exists):", s)
continue
print("=== stage", s, flush=True)
STAGES[s]()
|