File size: 41,646 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 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 | #!/usr/bin/env python3
"""R5 PRINT stage B: PDF text layer -> line crops for ONE language-script (ZEN4 job).
Steps (per language):
1. parse every PDF in RAW/<lang>/<docid>/doc.pdf with PyMuPDF (never executes anything inside it):
page and line gates, text normalisation, character allow-list, script-mixing check, language gate
(share of tokens in the top words of the project's own reference text for that language).
2. document gate, split by document (stratified, seeded), exact-text leakage filter for val/test.
3. line sampling (water-filling over documents), page render at a random 150-300 dpi, crops with
2-6 px padding, sha256 of every crop, sidecar JSONL (id, image, text, page, dpi, bbox, sha256, ...).
Run: python -I r5_print_process.py --lang kk --raw RAW --out OUT --corpus CORPUS_DIR --workers 8
"""
import argparse
import hashlib
import io
import json
import math
import os
import random
import re
import signal
import sys
import time
import unicodedata
import collections
from collections import Counter
import numpy as np
import pymupdf
from PIL import Image
SEED = 20261121
RU = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
PROFILES = {
"kk": dict(script="Cyrl", letters=RU + "әғқңөұүһі"),
"ky": dict(script="Cyrl", letters=RU + "ңөү"),
"uz_cyrl": dict(script="Cyrl", letters=RU + "ўқғҳ"),
"tt": dict(script="Cyrl", letters=RU + "әөүҗңһ"),
"ba": dict(script="Cyrl", letters=RU + "әөүғҡңҙҫһ"),
"sah": dict(script="Cyrl", letters=RU + "ҕҥөүһ"),
"tr": dict(script="Latn", letters="abcçdefgğhıijklmnoöprsştuüvyzqwxâîû"),
"az": dict(script="Latn", letters="abcçdeəfgğhxıijkqlmnoöprsştuüvyzwâ"),
"tk": dict(script="Latn", letters="abcçdefghijklmnoprstuvwyzäöüýňşž"),
"uz_latn": dict(script="Latn", letters="abcdefghijklmnopqrstuvxyz" + "ʻʼ"),
}
APOS = "ʻʼ'’‘`´"
# letters that Russian or English text never has (used to keep Russian and English lines out of a language)
# letters whose printed form has a tail below the baseline; if the text layer says one of them but the pixels show no tail,
# the font printed the plain letter (k, x, n, s) and the label is wrong
TAIL = set("қҚҳҲңҢҫҪ") # not the Sakha letter ҥ: it carries a hook at the top right, no tail
SPEC = {"kk": "әғқңөұүһі", "ky": "ңөү", "uz_cyrl": "ўқғҳ", "tt": "әөүҗңһ", "ba": "әөүғҡңҙҫһ", "sah": "ҕҥөүһ",
"tr": "çğıöşü", "az": "əçğıöşü", "tk": "äçöüýňşž", "uz_latn": "ʻʼ"}
PUNCT = set(" .,:;!?-–—‑−_'\"’‘“”«»„‚()[]{}/\\%№§°+=<>*&#@$€£|~^…·•ʻʼ`´" + "0123456789")
CYR = re.compile("[Ѐ-ӿ]")
LAT = re.compile("[A-Za-zÀ-ɏ]")
LIG = {"ff": "ff", "fi": "fi", "fl": "fl", "ffi": "ffi", "ffl": "ffl", "ſt": "st", "st": "st"}
SPACES = dict.fromkeys([0xA0, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
0x202F, 0x205F, 0x3000], " ")
DROPCH = {0xAD: None, 0x200B: None, 0x200C: None, 0x200D: None, 0x2060: None, 0xFEFF: None, 0x200E: None, 0x200F: None}
class Timeout(Exception):
pass
def _alarm(signum, frame):
raise Timeout()
def lower_key(s, lang):
if lang in ("tr", "az"):
s = s.replace("İ", "i").replace("I", "ı")
s = s.lower()
if lang == "uz_latn":
for a in APOS:
s = s.replace(a, "ʻ")
return s
TOK = re.compile(r"[^\W\d_]+(?:ʻ[^\W\d_]+)*", re.U)
def tokens(s, lang):
return TOK.findall(lower_key(s, lang))
EXCLUDE = set() # documents left out after the audit found that their text layer disagrees with the visible glyphs
KNOWN = set() # words seen at least twice in the reference text of the language (filled by build_lexicon)
def build_lexicon(corpus_dir, lang, nsent=250000, topk=4000):
global KNOWN
p = os.path.join(corpus_dir, "train", lang, "sentences.tsv")
c = Counter()
n = 0
with open(p, encoding="utf-8") as f:
for line in f:
parts = line.rstrip("\n").split("\t", 1)
if len(parts) < 2:
continue
c.update(tokens(parts[1], lang))
n += 1
if n >= nsent:
break
KNOWN = {w for w, k in c.items() if k >= 2}
return {w for w, _ in c.most_common(topk)}, n
def share(toks, lex):
if not toks:
return None
return sum(1 for t in toks if t in lex) / len(toks)
def normalise(raw):
r0 = raw.rstrip()
if r0.endswith("\u00ad"):
raw = r0[:-1] + "-" # a soft hyphen at the end of a line is printed as a hyphen
s = raw.translate(DROPCH)
for k, v in LIG.items():
s = s.replace(k, v)
s = s.translate(SPACES)
s = re.sub(r"\s+", " ", s).strip()
return unicodedata.normalize("NFC", s)
def line_ok(s, lang):
"""returns (ok, reason)"""
prof = PROFILES[lang]
if len(s) < 3 or len(s) > 160:
return False, "length"
letters = set(prof["letters"]) | set(prof["letters"].upper())
if lang in ("tr", "az"):
letters |= {"İ"}
allowed_lat = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
nlet = 0
for ch in s:
if ch in PUNCT:
continue
if ch in letters:
nlet += 1
continue
if prof["script"] == "Cyrl" and ch in allowed_lat:
nlet += 1
continue
if prof["script"] == "Latn" and ch in allowed_lat:
nlet += 1
continue
return False, "charset"
if lang == "uz_latn" and ("\u201e" in s or "\u201a" in s):
return False, "odd_apostrophe" # low quotes stand in for the okina in some fonts; the glyph and the code disagree
if prof["script"] == "Latn" and CYR.search(s):
return False, "cyrillic_in_latin"
if nlet < 2 or nlet < 0.5 * len(s.replace(" ", "")):
return False, "few_letters"
if re.search(r"[^\W\d_]\d+[^\W\d_]", s):
return False, "digit_inside_word"
# script mixing inside one word (homoglyph risk)
for w in re.split(r"[\s\-–—/.,;:!?()\[\]«»“”\"]+", s):
if w and CYR.search(w) and LAT.search(w):
return False, "mixed_script_word"
if prof["script"] == "Cyrl":
nl = len(LAT.findall(s))
if nl > 0.3 * max(1, nlet):
return False, "too_latin"
return True, ""
def order_blocks(blocks, W):
"""column ordering: full-width blocks split bands; inside a band, columns left to right."""
blocks = sorted(blocks, key=lambda b: (b["bbox"][1], b["bbox"][0]))
out, band = [], []
def flush():
cols = []
for b in sorted(band, key=lambda b: b["bbox"][0]):
x0, x1 = b["bbox"][0], b["bbox"][2]
placed = False
for c in cols:
ov = min(x1, c["x1"]) - max(x0, c["x0"])
if ov > 0.3 * min(x1 - x0, c["x1"] - c["x0"]):
c["items"].append(b)
c["x0"], c["x1"] = min(c["x0"], x0), max(c["x1"], x1)
placed = True
break
if not placed:
cols.append({"x0": x0, "x1": x1, "items": [b]})
for c in sorted(cols, key=lambda c: c["x0"]):
out.extend(sorted(c["items"], key=lambda b: b["bbox"][1]))
band.clear()
for b in blocks:
if b["bbox"][2] - b["bbox"][0] > 0.6 * W:
flush()
out.append(b)
else:
band.append(b)
flush()
return out
def rect_overlap(a, b):
x0, y0 = max(a[0], b[0]), max(a[1], b[1])
x1, y1 = min(a[2], b[2]), min(a[3], b[3])
if x1 <= x0 or y1 <= y0:
return 0.0
return (x1 - x0) * (y1 - y0)
def parse_page(page, lang, lex):
W, H = page.rect.width, page.rect.height
st = {"lines_seen": 0}
if page.rotation != 0:
return None, "rotated_page", st
if W > 1500 or H > 1500 or W < 100 or H < 100:
return None, "odd_page_size", st
try:
tt = page.get_texttrace()
except Exception:
tt = []
gmap = {}
for sp in tt:
if sp.get("type") == 3 or sp.get("opacity", 1) == 0:
return None, "invisible_text", st
f_ = sp.get("font")
for c_ in sp.get("chars", ()):
ch_ = chr(c_[0])
if ch_.isalpha():
gmap.setdefault(f"{f_}|{c_[1]}", set()).add(ch_.lower())
try:
infos = page.get_image_info()
except Exception:
infos = []
irects = []
for im in infos:
bb = im.get("bbox")
if bb:
irects.append(tuple(bb))
if (bb[2] - bb[0]) * (bb[3] - bb[1]) > 0.5 * W * H:
return None, "fullpage_image", st
d = page.get_text("dict", flags=pymupdf.TEXTFLAGS_DICT & ~pymupdf.TEXT_PRESERVE_IMAGES)
allchars = 0
bad = 0
blocks = []
for b in d["blocks"]:
if b.get("type") != 0:
continue
lines = []
for ln in b["lines"]:
sp = ln["spans"]
if not sp:
continue
txt = "".join(s["text"] for s in sp)
allchars += len(txt)
bad += sum(1 for ch in txt if 0xE000 <= ord(ch) <= 0xF8FF or ch == "�" or ord(ch) < 32)
lines.append({"bbox": tuple(ln["bbox"]), "dir": ln["dir"], "spans": sp, "raw": txt})
if lines:
blocks.append({"bbox": tuple(b["bbox"]), "lines": lines})
if allchars < 40:
return None, "little_text", st
if bad / max(1, allchars) > 0.005:
return None, "broken_tounicode", st
blocks = order_blocks(blocks, W)
alllines = [ln["bbox"] for b in blocks for ln in b["lines"] if abs(ln["dir"][1]) <= 0.05 and ln["dir"][0] > 0]
page_tokens = []
cand = []
for bi, b in enumerate(blocks):
btoks = []
blines = []
for ln in b["lines"]:
st["lines_seen"] += 1
if abs(ln["dir"][1]) > 0.05 or ln["dir"][0] <= 0:
continue
s = normalise(ln["raw"])
ok, why = line_ok(s, lang)
if not ok:
st["rej_" + why] = st.get("rej_" + why, 0) + 1
continue
sp = ln["spans"]
size = max(x["size"] for x in sp)
if size < 6.5 or max(x["size"] for x in sp) > 2.2 * min(x["size"] for x in sp):
st["rej_size"] = st.get("rej_size", 0) + 1
continue
gap_bad = False
for a, c in zip(sp, sp[1:]):
if c["bbox"][0] - a["bbox"][2] > 1.6 * size:
gap_bad = True
if gap_bad:
st["rej_gap"] = st.get("rej_gap", 0) + 1
continue
bb = ln["bbox"]
area = max(1e-6, (bb[2] - bb[0]) * (bb[3] - bb[1]))
if any(rect_overlap(bb, r) > 0.05 * area for r in irects):
st["rej_image_overlap"] = st.get("rej_image_overlap", 0) + 1
continue
tk = tokens(s, lang)
if len(tk) >= 5 and sum(1 for t in tk if t not in KNOWN) > 0.5 * len(tk):
st["rej_oov"] = st.get("rej_oov", 0) + 1
continue
btoks.extend(tk)
blines.append({"bbox": bb, "text": s, "size": size, "block": bi, "ntok": len(tk), "share": share(tk, lex),
"base": sp[0]["origin"][1]})
page_tokens.extend(btoks)
bsh = share(btoks, lex) if len(btoks) >= 8 else None
for ln in blines:
ln["block_share"] = bsh
cand.extend(blines)
# where the box of a neighbouring line overlaps this line's box, cut in the middle of the overlap
for a_ in cand:
ab = a_["bbox"]
acy = (ab[1] + ab[3]) / 2
ct, cb = None, None
for c_ in alllines:
if c_ == ab:
continue
if min(ab[2], c_[2]) - max(ab[0], c_[0]) <= 0:
continue
ccy = (c_[1] + c_[3]) / 2
if ccy < acy and c_[3] > ab[1]:
m = (ab[1] + c_[3]) / 2
ct = m if ct is None else max(ct, m)
elif ccy > acy and c_[1] < ab[3]:
m = (ab[3] + c_[1]) / 2
cb = m if cb is None else min(cb, m)
base_, size_ = a_["base"], a_["size"]
if ct is not None:
ct = min(ct, base_ - 0.95 * size_)
if cb is not None:
cb = max(cb, base_ + 0.30 * size_)
a_["cut_top"], a_["cut_bot"] = ct, cb
# overlap between lines (superimposed text)
keep = []
for i, a in enumerate(cand):
area = max(1e-6, (a["bbox"][2] - a["bbox"][0]) * (a["bbox"][3] - a["bbox"][1]))
clash = False
for j, c in enumerate(cand):
if i != j and rect_overlap(a["bbox"], c["bbox"]) > 0.3 * min(
area, (c["bbox"][2] - c["bbox"][0]) * (c["bbox"][3] - c["bbox"][1])):
clash = True
break
if clash:
st["rej_line_overlap"] = st.get("rej_line_overlap", 0) + 1
else:
keep.append(a)
psh = share(page_tokens, lex) if len(page_tokens) >= 15 else None
st["page_share"] = psh
st["page_tokens"] = len(page_tokens)
return {"lines": keep, "page_share": psh, "ntok": len(page_tokens), "gmap": gmap}, "", st
def parse_doc(job):
docdir, lang, lexlist, maxpages = job
lex = set(lexlist)
docid = os.path.basename(docdir)
res = {"docid": docid, "status": "ok", "pages_total": 0, "pages_sampled": 0, "page_reject": {}, "pages": {}}
signal.signal(signal.SIGALRM, _alarm)
signal.alarm(150)
try:
doc = pymupdf.open(os.path.join(docdir, "doc.pdf"))
if doc.needs_pass or doc.is_encrypted:
res["status"] = "encrypted"
return res
n = doc.page_count
res["pages_total"] = n
rng = random.Random(f"{SEED}-{docid}")
idx = list(range(n))
if n > maxpages:
idx = sorted(rng.sample(idx, maxpages))
res["pages_sampled"] = len(idx)
shares = []
docmap = {} # (font, glyph id) -> letters the text layer assigns to that glyph
agg = Counter()
for pno in idx:
try:
page = doc.load_page(pno)
out, why, st = parse_page(page, lang, lex)
except Timeout:
raise
except Exception as e:
res["page_reject"]["exc_" + type(e).__name__] = res["page_reject"].get("exc_" + type(e).__name__, 0) + 1
continue
for k, v in st.items():
if isinstance(v, int):
agg[k] += v
if out is None:
res["page_reject"][why] = res["page_reject"].get(why, 0) + 1
continue
for k_, v_ in out.pop("gmap").items():
docmap.setdefault(k_, set()).update(v_)
if out["page_share"] is not None:
shares.append(out["page_share"])
res["pages"][str(pno)] = out
# one glyph that the text layer reads as two different letters (a hooked letter shown as the plain one)
res["ambiguous_glyphs"] = sorted(f"{k_}={''.join(sorted(v_))}" for k_, v_ in docmap.items() if len(v_) >= 2)[:8]
res["n_ambiguous_glyphs"] = sum(1 for v_ in docmap.values() if len(v_) >= 2)
res["line_stats"] = dict(agg)
res["median_page_share"] = float(np.median(shares)) if shares else None
res["pages_with_share"] = len(shares)
except Timeout:
res["status"] = "timeout"
except Exception as e:
res["status"] = "error:" + type(e).__name__ + ":" + str(e)[:80]
finally:
signal.alarm(0)
return res
def render_job(job):
docdir, lang, docid, split, outdir, pages = job
# pages: {pno: [ {idx, text, bbox, ...}, ...]}
recs = []
nchk = nbad = 0
signal.signal(signal.SIGALRM, _alarm)
signal.alarm(240)
try:
doc = pymupdf.open(os.path.join(docdir, "doc.pdf"))
for pno_s, lines in pages.items():
pno = int(pno_s)
rng = random.Random(f"{SEED}-{docid}-{pno}")
dpi = rng.randint(150, 300)
page = doc.load_page(pno)
pix = page.get_pixmap(matrix=pymupdf.Matrix(dpi / 72, dpi / 72), colorspace=pymupdf.csRGB, alpha=False)
img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
sc = dpi / 72.0
gpage = np.asarray(img.convert("L"), dtype=np.int16)
try:
rd = page.get_text("rawdict", flags=pymupdf.TEXTFLAGS_RAWDICT & ~pymupdf.TEXT_PRESERVE_IMAGES)
except Exception:
rd = {"blocks": []}
chars_by_line = {}
for b_ in rd["blocks"]:
if b_.get("type") != 0:
continue
for l_ in b_["lines"]:
chars_by_line[tuple(round(v, 1) for v in l_["bbox"])] = [c_ for s_ in l_["spans"] for c_ in s_["chars"]]
for ln in lines:
chs = chars_by_line.get(tuple(round(v, 1) for v in ln["bbox"]))
if chs is None:
for k_, v_ in chars_by_line.items():
if max(abs(k_[i_] - ln["bbox"][i_]) for i_ in range(4)) < 0.2:
chs = v_
break
if chs is not None:
tail_bad = False
for c_ in chs:
if c_["c"] not in TAIL:
continue
bx0, by0, bx1, by1 = c_["bbox"]
w_ = bx1 - bx0
base_ = c_["origin"][1]
ya, yb = int((base_ + 0.04 * ln["size"]) * sc), int((base_ + 0.28 * ln["size"]) * sc)
xa, xb = int((bx0 - 0.05 * w_) * sc), int((bx1 + 0.12 * w_) * sc)
if yb - ya < 2 or xb - xa < 2:
continue
full_ = gpage[max(0, int(by0 * sc)):int(by1 * sc), max(0, xa):xb]
reg = gpage[max(0, ya):yb, max(0, xa):xb]
if full_.size == 0 or reg.size == 0:
continue
nchk += 1
if int((np.abs(reg - np.median(full_)) > 60).sum()) < 2:
nbad += 1
tail_bad = True
if tail_bad:
recs.append({"id": ln["id"], "drop": "tail_letter_without_tail"})
continue
# (1) a hole between two characters: a glyph without a text-layer code was left out;
# (2) a letter or digit whose box shows no ink: hidden, clipped or covered
size_ = ln["size"]
miss_bad = False
lx0, ly0, lx1, ly1 = ln["bbox"]
band_ = gpage[max(0, int(ly0 * sc)):int(ly1 * sc), max(0, int(lx0 * sc)):int(lx1 * sc)]
if band_.size:
bgm = float(np.median(band_))
# (1) ink inside a gap between two characters that the text layer does not account for
for a_c, b_c in zip(chs, chs[1:]):
if (b_c["bbox"][0] - a_c["bbox"][2]) > 0.15 * size_:
gx0, gx1 = int((a_c["bbox"][2] + 0.04 * size_) * sc), int((b_c["bbox"][0] - 0.04 * size_) * sc)
gy0 = int((a_c["bbox"][1] + 0.3 * (a_c["bbox"][3] - a_c["bbox"][1])) * sc)
gy1 = int((a_c["bbox"][3] - 0.3 * (a_c["bbox"][3] - a_c["bbox"][1])) * sc)
if gx1 - gx0 >= 2 and gy1 - gy0 >= 2:
greg = gpage[max(0, gy0):gy1, max(0, gx0):gx1]
if greg.size and int((np.abs(greg - bgm) > 60).sum()) >= 4:
miss_bad = True
break
if not miss_bad:
for c_ in chs:
if not c_["c"].isalnum():
continue
bx0, by0, bx1, by1 = c_["bbox"]
w_ = bx1 - bx0
xa, xb = int((bx0 + 0.1 * w_) * sc), int((bx1 - 0.1 * w_) * sc)
ya, yb = int(by0 * sc), int(by1 * sc)
if xb - xa < 1 or yb - ya < 2:
continue
reg = gpage[max(0, ya):yb, max(0, xa):xb]
if reg.size and int((np.abs(reg - bgm) > 60).sum()) < 2:
miss_bad = True
break
if miss_bad:
recs.append({"id": ln["id"], "drop": "missing_or_hidden_glyph"})
continue
bad_space = False
for c_ in chs:
if not c_["c"].isspace():
continue
bx0, by0, bx1, by1 = c_["bbox"]
w_ = bx1 - bx0
xa, xb = int((bx0 + 0.2 * w_) * sc), int((bx1 - 0.2 * w_) * sc)
ya, yb = int(by0 * sc), int(by1 * sc)
if xb - xa < 2 or yb - ya < 6:
continue
reg = gpage[max(0, ya):yb, max(0, xa):xb]
if reg.size == 0:
continue
rmed = np.median(gpage[max(0, ya):yb, max(0, xa - 3 * (xb - xa)):xb + 3 * (xb - xa)])
rows = (np.abs(reg - rmed) > 80).any(axis=1).mean()
if rows >= 0.35 and w_ * sc > 3:
bad_space = True
break
if bad_space:
recs.append({"id": ln["id"], "drop": "space_over_ink"})
continue
else:
pass
lines_ok = True
pad = rng.randint(2, 6)
x0, y0, x1, y1 = ln["bbox"]
box = (max(0, int(math.floor(x0 * sc)) - pad), max(0, int(math.floor(y0 * sc)) - pad),
min(img.width, int(math.ceil(x1 * sc)) + pad), min(img.height, int(math.ceil(y1 * sc)) + pad))
if ln.get("cut_top") is not None:
box = (box[0], max(box[1], int(math.ceil(ln["cut_top"] * sc))), box[2], box[3])
if ln.get("cut_bot") is not None:
box = (box[0], box[1], box[2], min(box[3], int(math.floor(ln["cut_bot"] * sc))))
w, h = box[2] - box[0], box[3] - box[1]
if h < 14 or w < 30 or w / h > 120:
recs.append({"id": ln["id"], "drop": "geometry"})
continue
crop = img.crop(box)
g = np.asarray(crop.convert("L"), dtype=np.int16)
med = np.median(g)
mask = np.abs(g - med) > 60
cols = np.flatnonzero(mask.any(axis=0))
if len(cols) == 0:
recs.append({"id": ln["id"], "drop": "ink"})
continue
# ink touching the left or right border of the crop (middle rows): a neighbouring glyph or word is cut off
r0 = int(0.25 * mask.shape[0])
band = mask[r0:max(int(0.75 * mask.shape[0]), r0 + 1), :]
if int(band[:, 0].sum()) >= 2 or int(band[:, -1].sum()) >= 2:
recs.append({"id": ln["id"], "drop": "edge_clipped"})
continue
# trim blank space left and right of the ink (spaces, tabs), keep the padding
l_, r_ = max(0, int(cols[0]) - pad), min(crop.width, int(cols[-1]) + 1 + pad)
if r_ - l_ < 30:
recs.append({"id": ln["id"], "drop": "geometry"})
continue
if l_ > 0 or r_ < crop.width:
crop = crop.crop((l_, 0, r_, crop.height))
g = g[:, l_:r_]
mask = mask[:, l_:r_]
w = crop.width
dark = float(mask.mean())
if dark < 0.012 or dark > 0.6:
recs.append({"id": ln["id"], "drop": "ink"})
continue
bio = io.BytesIO()
crop.save(bio, format="PNG", compress_level=4)
data = bio.getvalue()
sha = hashlib.sha256(data).hexdigest()
rel = os.path.join(split, docid, f"{ln['id'].split(':')[-1]}.png")
full = os.path.join(outdir, rel)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, "wb") as fo:
fo.write(data)
recs.append({"id": ln["id"], "image": full, "sha256": sha, "dpi": dpi, "pad": pad,
"w": w, "h": h, "ink": round(dark, 4)})
recs.append({"docstat": [docid, nchk, nbad]})
except Timeout:
recs.append({"drop": "timeout_job", "docid": docid})
except Exception as e:
recs.append({"drop": "error:" + type(e).__name__ + ":" + str(e)[:60], "docid": docid})
finally:
signal.alarm(0)
return recs
def waterfill(avail, total, per_doc_max):
"""avail: {doc: n}; returns {doc: quota} spreading `total` as evenly as the caps allow."""
quota = {d: 0 for d in avail}
rem = total
docs = sorted(avail, key=lambda d: avail[d])
left = len(docs)
for d in docs:
share_ = rem // left if left else 0
q = min(avail[d], per_doc_max, max(share_, 1) if rem > 0 else 0)
quota[d] = q
rem -= q
left -= 1
# one more pass to hand out the remainder to docs that still have room
if rem > 0:
for d in sorted(avail, key=lambda d: -avail[d]):
room = min(avail[d], per_doc_max) - quota[d]
add = min(room, rem)
quota[d] += add
rem -= add
if rem <= 0:
break
return quota
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--lang", required=True)
ap.add_argument("--raw", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--corpus", required=True)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--maxpages", type=int, default=60)
ap.add_argument("--calibrate", action="store_true")
ap.add_argument("--exclude", default="", help="file with one document id per line to leave out of every split")
ap.add_argument("--tr_tbmm_max_share", type=float, default=0.3)
a = ap.parse_args()
lang = a.lang
t_start = time.time()
global EXCLUDE
if a.exclude and os.path.exists(a.exclude):
EXCLUDE = {x.strip() for x in open(a.exclude, encoding="utf-8") if x.strip()}
if not a.calibrate:
# one worker per language: whichever job starts first takes the lock (mkdir is atomic)
os.makedirs(os.path.join(a.out, "_locks"), exist_ok=True)
try:
os.mkdir(os.path.join(a.out, "_locks", lang))
except FileExistsError:
print(lang, "already taken by another job or finished; nothing to do", flush=True)
return
lex, nsent = build_lexicon(a.corpus, lang)
print(lang, "lexicon", len(lex), "from sentences", nsent, flush=True)
os.makedirs(os.path.join(a.out, "_stats"), exist_ok=True)
os.makedirs(os.path.join(a.out, "_sidecars"), exist_ok=True)
if a.calibrate:
sh = []
rng = random.Random(SEED)
sents = []
with open(os.path.join(a.corpus, "val", lang, "sentences.tsv"), encoding="utf-8") as f:
for i, line in enumerate(f):
parts = line.rstrip("\n").split("\t", 1)
if len(parts) == 2:
sents.append(parts[1])
if i > 60000:
break
for _ in range(500):
txt = " ".join(rng.sample(sents, 12))
sh.append(share(tokens(txt, lang), lex))
print("pseudo-page share (12 held-out sentences): min %.3f p5 %.3f median %.3f" % (min(sh), np.percentile(sh, 5), np.median(sh)))
cross = {}
for ol in PROFILES:
if ol == lang:
continue
osn = []
with open(os.path.join(a.corpus, "val", ol, "sentences.tsv"), encoding="utf-8") as f:
for i, line in enumerate(f):
parts = line.rstrip("\n").split("\t", 1)
if len(parts) == 2:
osn.append(parts[1])
if i > 6000:
break
xs = [share(tokens(" ".join(rng.sample(osn, 12)), lang), lex) for _ in range(100)]
cross[ol] = (round(float(np.median(xs)), 3), round(float(np.max(xs)), 3))
print("other languages vs this lexicon (median, max):", cross)
return
rawlang = os.path.join(a.raw, lang)
docs = sorted(d for d in os.listdir(rawlang) if os.path.exists(os.path.join(rawlang, d, "meta.json")))
print(lang, "documents on disk", len(docs), flush=True)
import multiprocessing as mp
ctx = mp.get_context("fork")
lexlist = sorted(lex)
jobs = [(os.path.join(rawlang, d), lang, lexlist, a.maxpages) for d in docs]
parsed = {}
with ctx.Pool(a.workers, maxtasksperchild=20) as pool:
for r in pool.imap_unordered(parse_doc, jobs, chunksize=1):
parsed[r["docid"]] = r
print(lang, "parsed", len(parsed), "in", round(time.time() - t_start), "s", flush=True)
# document gate
T_PAGE, T_DOC = 0.33, 0.38
good, rej = {}, Counter()
doc_rows = []
for docid, r in parsed.items():
meta = json.load(open(os.path.join(rawlang, docid, "meta.json"), encoding="utf-8"))
info = {"docid": docid, "host": meta.get("host"), "url": meta.get("url"), "source": meta.get("source"),
"pages_total": r["pages_total"], "pages_sampled": r["pages_sampled"], "status": r["status"],
"page_reject": r["page_reject"], "median_page_share": r.get("median_page_share")}
if r["status"] != "ok":
rej[r["status"].split(":")[0]] += 1
info["verdict"] = "reject:" + r["status"][:40]
doc_rows.append(info)
continue
if docid in EXCLUDE:
rej["excluded_after_audit"] += 1
info["verdict"] = "reject:excluded_after_audit (text layer and visible glyphs disagree)"
doc_rows.append(info)
continue
keep_pages = {}
for pno, p in r["pages"].items():
ps = p["page_share"]
lines = []
for ln in p["lines"]:
bs = ln.get("block_share")
ref = bs if bs is not None else ps
if ref is None:
ref = r.get("median_page_share")
if ref is None or ref < T_PAGE:
continue
if ln["ntok"] >= 5 and ln["share"] is not None and ln["share"] < 0.2:
continue
if not any(ch in SPEC[lang] for ch in lower_key(ln["text"], lang)):
# no letter of the language's own: keep only lines with at least 3 words that match its vocabulary well
if ln["ntok"] < 3 or ln["share"] is None or ln["share"] < 0.6:
continue
lines.append(ln)
if lines:
keep_pages[pno] = lines
nl = sum(len(v) for v in keep_pages.values())
info["eligible_lines"] = nl
msh = r.get("median_page_share")
if msh is None or msh < T_DOC:
rej["language_gate"] += 1
info["verdict"] = "reject:language_gate"
doc_rows.append(info)
continue
if nl < 30:
rej["few_lines"] += 1
info["verdict"] = "reject:few_lines"
doc_rows.append(info)
continue
info["verdict"] = "accepted"
doc_rows.append(info)
good[docid] = {"meta": meta, "pages": keep_pages}
tbmm_dropped = 0
if lang == "tr":
tb = sorted(d for d in good if good[d]["meta"].get("source") == "tbmm_minutes")
others = len(good) - len(tb)
tb_max = int(math.floor(a.tr_tbmm_max_share / (1 - a.tr_tbmm_max_share) * others))
if len(tb) > tb_max:
random.Random(f"{SEED}-tbmmcap").shuffle(tb)
for d in tb[tb_max:]:
del good[d]
tbmm_dropped += 1
print(lang, "documents accepted", len(good), "rejected", dict(rej), "tbmm_dropped_for_share", tbmm_dropped, flush=True)
# per-document exact duplicates of text (headers repeated on every page)
for docid, g in good.items():
seen = set()
for pno in sorted(g["pages"], key=int):
new = []
for ln in g["pages"][pno]:
if ln["text"] in seen:
continue
seen.add(ln["text"])
new.append(ln)
g["pages"][pno] = new
# split by document
ids = sorted(good)
rng = random.Random(f"{SEED}-{lang}")
rng.shuffle(ids)
n = len(ids)
if n >= 20:
nv, nt = max(3, round(0.05 * n)), max(5, round(0.15 * n))
elif n >= 12:
nv, nt = 2, max(3, round(0.15 * n))
elif n >= 6:
nv, nt = 1, 2
elif n >= 3:
nv, nt = 0, 1
else:
nv, nt = 0, 0
split_of = {d: "train" for d in ids}
# held-out documents are drawn (in the seeded shuffled order) among documents with at least 40 eligible lines,
# so that val and test can reach their line targets; documents with fewer lines stay in train
avail0 = {d: sum(len(v) for v in good[d]["pages"].values()) for d in ids}
cands = [d for d in ids if avail0[d] >= 40]
for i, d in enumerate(cands):
if i < nt:
split_of[d] = "test"
elif i < nt + nv:
split_of[d] = "val"
print(lang, "split docs", Counter(split_of.values()), flush=True)
# TBMM share cap for tr (train only: keep test/val diverse by simply capping documents)
train_text = set()
for d in ids:
if split_of[d] == "train":
for p in good[d]["pages"].values():
for ln in p:
train_text.add(ln["text"])
test_text = set()
leak = Counter()
for sp in ("test", "val"):
for d in ids:
if split_of[d] != sp:
continue
for pno in list(good[d]["pages"]):
new = []
for ln in good[d]["pages"][pno]:
if ln["text"] in train_text:
leak[sp + "_text_in_train"] += 1
continue
if sp == "val" and ln["text"] in test_text:
leak["val_text_in_test"] += 1
continue
new.append(ln)
if sp == "test":
test_text.add(ln["text"])
good[d]["pages"][pno] = new
targets = {"train": 7500, "val": 520, "test": 850}
permax = {"train": 900, "val": 300, "test": 300}
perpage = {"train": 60, "val": 14, "test": 14}
sel = {} # docid -> {pno: [lines]}
quota_info = {}
for sp in ("train", "val", "test"):
dl = [d for d in ids if split_of[d] == sp]
if not dl:
continue
avail = {d: sum(len(v) for v in good[d]["pages"].values()) for d in dl}
quota = waterfill(avail, targets[sp], permax[sp])
quota_info[sp] = {"docs": len(dl), "available": sum(avail.values()), "quota": sum(quota.values())}
for d in dl:
r2 = random.Random(f"{SEED}-{lang}-{d}-sel")
pnos = sorted(good[d]["pages"], key=int)
r2.shuffle(pnos)
left = quota[d]
chosen = {}
rounds = 0
while left > 0 and rounds < 10:
progressed = False
for pno in pnos:
if left <= 0:
break
have = chosen.setdefault(pno, [])
pool = [ln for ln in good[d]["pages"][pno] if ln not in have]
k = min(left, perpage[sp] * (rounds + 1) - len(have), len(pool))
if k <= 0:
continue
have.extend(r2.sample(pool, k))
left -= k
progressed = True
rounds += 1
if not progressed:
break
sel[d] = {p: v for p, v in chosen.items() if v}
# ids: sort lines of every page by their position (stable order) and number them
outdir = a.out
rjobs = []
meta_of = {}
for d, pages in sel.items():
sp = split_of[d]
pg = {}
for pno, lines in pages.items():
lines = sorted(lines, key=lambda x: (x["block"], x["bbox"][1], x["bbox"][0]))
lst = []
for k, ln in enumerate(lines):
lid = f"printreal:{lang}:{d}:p{int(pno):04d}l{k:03d}"
lst.append({"id": lid, "bbox": ln["bbox"], "text": ln["text"], "size": ln["size"],
"cut_top": ln.get("cut_top"), "cut_bot": ln.get("cut_bot")})
meta_of[lid] = {"docid": d, "split": sp, "page": int(pno), "text": ln["text"], "bbox": ln["bbox"],
"size_pt": round(ln["size"], 2)}
pg[pno] = lst
rjobs.append((os.path.join(rawlang, d), lang, d, sp, os.path.join(outdir, lang), pg))
print(lang, "render jobs", len(rjobs), "lines", len(meta_of), flush=True)
drops = Counter()
tail_stat = collections.defaultdict(lambda: [0, 0])
rows = []
with ctx.Pool(a.workers, maxtasksperchild=10) as pool:
for recs in pool.imap_unordered(render_job, rjobs, chunksize=1):
for rc in recs:
if "docstat" in rc:
d_, a_, b_ = rc["docstat"]
tail_stat[d_][0] += a_
tail_stat[d_][1] += b_
continue
if "drop" in rc:
drops[rc["drop"]] += 1
continue
m = meta_of[rc["id"]]
dmeta = good[m["docid"]]["meta"]
rows.append({"id": rc["id"], "image": rc["image"], "text": m["text"], "lang": lang,
"script": PROFILES[lang]["script"], "kind": "typed_real",
"source": ("tbmm_minutes" if dmeta.get("source") == "tbmm_minutes" else "finepdfs:" + dmeta.get("host", "")),
"split": m["split"], "group": m["docid"], "unit": "line",
"page": m["page"], "dpi": rc["dpi"], "pad": rc["pad"], "w": rc["w"], "h": rc["h"],
"ink": rc["ink"], "bbox_pt": [round(x, 2) for x in m["bbox"]], "size_pt": m["size_pt"],
"sha256": rc["sha256"], "url": dmeta.get("url"), "doc_sha256": dmeta.get("sha256")})
suspect = sorted(d for d, (a_, b_) in tail_stat.items() if a_ >= 10 and b_ / a_ >= 0.05)
if suspect:
rows = [r for r in rows if r["group"] not in set(suspect)]
# crop-level dedupe by sha256 (identical crops, e.g. repeated headings)
seen, final = set(), []
dupc = 0
for r in sorted(rows, key=lambda r: r["id"]):
if r["sha256"] in seen:
dupc += 1
try:
os.remove(r["image"])
except OSError:
pass
continue
seen.add(r["sha256"])
final.append(r)
sidecar = os.path.join(a.out, "_sidecars", f"{lang}.jsonl")
with open(sidecar, "w", encoding="utf-8") as fo:
for r in final:
fo.write(json.dumps(r, ensure_ascii=False) + "\n")
cnt = {}
for sp in ("train", "val", "test"):
rs = [r for r in final if r["split"] == sp]
cnt[sp] = {"lines": len(rs), "documents": len({r["group"] for r in rs}),
"pages": len({(r["group"], r["page"]) for r in rs})}
stats = {"lang": lang, "documents_on_disk": len(docs), "documents_accepted": len(good), "doc_rejects": dict(rej), "tbmm_dropped_for_share": tbmm_dropped,
"split_docs": dict(Counter(split_of.values())), "leakage_removed": dict(leak), "quota": quota_info,
"render_drops": dict(drops), "suspect_docs_tail_check": suspect,
"tail_check": {d: v for d, v in tail_stat.items() if v[1] > 0}, "crop_dup_dropped": dupc, "counts": cnt,
"hosts_accepted": len({good[d]["meta"].get("host") for d in good}), "seconds": round(time.time() - t_start),
"thresholds": {"T_PAGE_block_or_page_share": T_PAGE, "T_DOC_median_page_share": T_DOC,
"lexicon_words": len(lex), "lexicon_sentences": nsent}}
with open(os.path.join(a.out, "_stats", f"{lang}.json"), "w") as fo:
json.dump(stats, fo, indent=1, ensure_ascii=False)
with open(os.path.join(a.out, "_stats", f"{lang}_docs.jsonl"), "w", encoding="utf-8") as fo:
for r in doc_rows:
r["split"] = split_of.get(r["docid"])
fo.write(json.dumps(r, ensure_ascii=False) + "\n")
print(lang, "DONE", json.dumps(cnt), "drops", dict(drops), flush=True)
if __name__ == "__main__":
main()
|