turkic-ocr-code / scripts /r5_print /r5_print_assemble.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
9.73 kB
#!/usr/bin/env python3
"""R5 PRINT stage E: sidecars -> manifests, duplicate check by crop sha256, counts.json, evalsets.json.
Reads DATA/data/processed/r5/print_real/_sidecars/<lang>.jsonl (one per language-script) and more.jsonl.
Writes print_real_{train,val,test}.tsv and more_real_print.tsv into DATA/data/processed/r5/manifests/,
adds three entries to evalsets.json (re-read right before the atomic replace), writes counts.json.
Usage: python -I r5_print_assemble.py OUT_JSON_DIR
"""
import collections
import concurrent.futures as cf
import hashlib
import json
import os
import sys
import time
import unicodedata
D = "/path/to/TURKIC_OCR_DATA/data/processed/r5"
PR = D + "/print_real"
MAN = D + "/manifests"
OUTDIR = sys.argv[1]
MORE_ONLY = len(sys.argv) > 2 and sys.argv[2] == "more_only"
HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]
LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"]
NOW = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def sha256_file(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for c in iter(lambda: f.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def read_jsonl(p):
if not os.path.exists(p):
return []
return [json.loads(x) for x in open(p, encoding="utf-8")]
def write_manifest(path, rows):
tmp = path + ".part"
with open(tmp, "w", encoding="utf-8", newline="") as f:
f.write("\t".join(HDR) + "\n")
for r in rows:
t = unicodedata.normalize("NFC", r["text"])
assert "\t" not in t and "\n" not in t and "\r" not in t
f.write("\t".join([r["id"], r["image"], t, r["lang"], r["script"], r["kind"], r["source"], r["split"], r["group"], r["unit"]]) + "\n")
os.replace(tmp, path)
# hashes of every crop of the other manifests (stage DATA's table of 20 Nov) and of GEN's images so far
other = set()
other_files = []
for hp in (D + "/build_logs/hashes.tsv", D + "/build_logs/hashes_synth.tsv"):
if os.path.exists(hp):
other_files.append(hp)
with open(hp, encoding="utf-8") as f:
next(f)
for line in f:
other.add(line.split("\t", 2)[1])
print("other-manifest sha256 values", len(other), other_files, flush=True)
def opens(path):
"""True if the file exists and PIL can read it as an image (header and checksums)."""
try:
from PIL import Image
with Image.open(path) as im:
im.verify()
return True
except Exception:
return False
rows = []
dropped = collections.Counter()
for lg in LANGS:
for r in read_jsonl(f"{PR}/_sidecars/{lg}.jsonl"):
if r["sha256"] in other:
dropped["crop_sha256_in_other_manifest"] += 1
continue
if not os.path.exists(r["image"]):
dropped["image_missing"] += 1
continue
rows.append(r)
# every image must exist and open (added after a draft pointed to rewritten crops)
with cf.ThreadPoolExecutor(16) as ex:
flags = list(ex.map(opens, [r["image"] for r in rows], chunksize=256))
n_checked = len(rows)
rows = [r for r, ok in zip(rows, flags) if ok]
dropped["image_unreadable"] += n_checked - len(rows)
# duplicate crops across languages
seen = set()
final = []
for r in sorted(rows, key=lambda r: r["id"]):
if r["sha256"] in seen:
dropped["crop_sha256_duplicate_in_print_real"] += 1
continue
seen.add(r["sha256"])
final.append(r)
by_split = {sp: [r for r in final if r["split"] == sp] for sp in ("train", "val", "test")}
if not MORE_ONLY:
for sp, rs in by_split.items():
write_manifest(f"{MAN}/print_real_{sp}.tsv", rs)
# MORE
more = [r for r in read_jsonl(f"{PR}/_sidecars/more.jsonl") if r["sha256"] not in other]
with cf.ThreadPoolExecutor(16) as ex:
mflags = list(ex.map(opens, [r["image"] for r in more]))
dropped["more_image_unreadable"] += sum(1 for f in mflags if not f)
more = [r for r, ok in zip(more, mflags) if ok]
write_manifest(f"{MAN}/more_real_print.tsv", sorted(more, key=lambda r: r["id"]))
# counts
counts = {"generated_utc": NOW, "dropped_in_assembly": dict(dropped),
"image_check": {"rows_checked_exists_and_opens": n_checked, "rows_kept": len(final),
"rows_dropped_missing_file": int(dropped.get("image_missing", 0)),
"rows_dropped_unreadable": int(dropped.get("image_unreadable", 0)),
"more_rows_dropped_unreadable": int(dropped.get("more_image_unreadable", 0))},
"per_language": {}, "totals": {}}
for lg in LANGS:
st = {}
sp_path = f"{PR}/_stats/{lg}.json"
if os.path.exists(sp_path):
st = json.load(open(sp_path, encoding="utf-8"))
ent = {"script": "Latn" if lg in ("tr", "az", "tk", "uz_latn") else "Cyrl", "documents_on_disk": st.get("documents_on_disk"),
"documents_accepted": st.get("documents_accepted"), "document_rejects": st.get("doc_rejects"),
"hosts_accepted": st.get("hosts_accepted"), "splits": {}}
for sp in ("train", "val", "test"):
rs = [r for r in by_split[sp] if r["lang"] == lg]
ent["splits"][sp] = {"documents": len({r["group"] for r in rs}), "pages": len({(r["group"], r["page"]) for r in rs}), "lines": len(rs),
"characters": sum(len(r["text"]) for r in rs)}
ent["sources"] = dict(collections.Counter(r["source"] for r in final if r["lang"] == lg).most_common(8))
counts["per_language"][lg] = ent
counts["totals"] = {sp: {"documents": len({r["group"] for r in by_split[sp]}), "lines": len(by_split[sp])} for sp in by_split}
mc = collections.Counter(r["lang"] for r in more)
counts["more_real_print"] = {"paragraphs": len(more), "by_lang": dict(mc), "pages": len({(r["group"]) for r in more}),
"characters": sum(len(r["text"]) for r in more)}
os.makedirs(OUTDIR, exist_ok=True)
json.dump(counts, open(os.path.join(OUTDIR, "counts_more_only.json" if MORE_ONLY else "counts.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
# evalsets.json: three entries, atomic replace after a fresh read
sha = {n: sha256_file(f"{MAN}/{n}.tsv") for n in (("more_real_print",) if MORE_ONLY else ("print_real_val", "print_real_test", "more_real_print"))}
def langs_of(rs):
return dict(collections.Counter(r["lang"] for r in rs))
entries = [
{"name": "print_real_val", "manifest": f"{MAN}/print_real_val.tsv", "split": "val", "locked": False, "status": "ready",
"purpose": "Validation lines cut from real born-digital PDFs (exact text layer), 10 language-scripts, documents disjoint from the training and test documents. For selection only.",
"n_rows": len(by_split["val"]), "n_groups": len({r["group"] for r in by_split["val"]}), "manifest_sha256": sha.get("print_real_val"),
"langs": langs_of(by_split["val"]), "unit": "line", "group_unit": "source document",
"split_rule": "documents split by seeded shuffle (seed 20261121) per language-script, about 80/5/15; exact line texts that occur in a training document are removed from val and test",
"owner": "PRINT"},
{"name": "print_real_test", "manifest": f"{MAN}/print_real_test.tsv", "split": "test", "locked": True, "status": "ready",
"purpose": "Typed endpoint N (version 3 section 1): lines cut from real born-digital PDFs with an exact text layer, per language-script, documents disjoint from train and val. The machine audit of 50 random lines per language-script is in OUT/audit.json (checked by machine viewing, not by a human).",
"n_rows": len(by_split["test"]), "n_groups": len({r["group"] for r in by_split["test"]}), "manifest_sha256": sha.get("print_real_test"),
"langs": langs_of(by_split["test"]), "unit": "line", "group_unit": "source document", "endpoint": "N",
"split_rule": "as print_real_val", "owner": "PRINT",
"caution": "document counts per language-script are small for the thin languages; see counts.json; the text is the PDF's own text layer, not a human transcript"},
{"name": "more_real_print", "manifest": f"{MAN}/more_real_print.tsv", "split": "test", "locked": True, "status": "ready",
"purpose": "MORE benchmark (zimoqingfeng/MORE), paragraph part, in-scope languages: text blocks cut from real PDF pages; labels are model-assisted and human-refined per the README. Paragraph level (unit paragraph), never cut into lines.",
"n_rows": len(more), "n_groups": len({r["group"] for r in more}), "manifest_sha256": sha.get("more_real_print"),
"langs": dict(mc), "unit": "paragraph", "group_unit": "source page", "owner": "PRINT",
"licence_note": "the README carries an Apache-2.0 badge in its metadata; the repository has no licence file",
"caution": "unit paragraph is not in the shared unit list (word, line, page); the manifest validator of stage DATA will flag it; newlines inside a block were replaced by one space"},
]
ev_path = D + "/evalsets.json"
reg = json.load(open(ev_path, encoding="utf-8"))
if MORE_ONLY:
entries = [e for e in entries if e["name"] == "more_real_print"]
names = {e["name"] for e in entries}
reg["sets"] = [e for e in reg["sets"] if e.get("name") not in names] + entries
tmp = ev_path + ".print.part"
json.dump(reg, open(tmp, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
os.replace(tmp, ev_path)
json.dump({"note": "entries added by stage PRINT; r5_registry.py rewrites evalsets.json from its own list and would drop them, so merge this file there", "sets": entries},
open(D + "/evalsets_extra_print.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(json.dumps(counts["totals"]), json.dumps(counts["more_real_print"]), dict(dropped))