turkic-ocr-code / scripts /r5_print /r5_print_more_build.py
treoa's picture
Clean up comments and file headers; point to the model repositories
0d02ed4 verified
Raw History Blame Contribute Delete
3.69 kB
#!/usr/bin/env python3
import hashlib
import importlib.util
import io
import json
import os
import re
import sys
import unicodedata
from collections import Counter
raw, out, corpus, modpath = sys.argv[1:5]
spec = importlib.util.spec_from_file_location("rpp", modpath)
rpp = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rpp)
PAGE_LANG = {"kk": "kk", "ky": "ky", "uz": "uz", "tr": "tr", "az": "az", "tt": "tt", "ba": "ba", "tk": "tk", "sah": "sah"}
data = json.load(open(os.path.join(raw, "paragraph", "MORE_paragraph.json"), encoding="utf-8"))
lex = {}
rows = []
stats = Counter()
cyr = re.compile("[Ѐ-ӿ]")
lat = re.compile("[A-Za-zÀ-ɏ]")
for it in data:
code = it["page_info"].get("page_attribute", {}).get("language")
if code not in PAGE_LANG:
continue
imgname = it["page_info"]["image_path"]
stem = os.path.splitext(imgname)[0]
for ld in it["layout_dets"]:
stats[code + "_blocks_total"] += 1
if ld.get("category_type") != "text_block":
stats["not_text_block"] += 1
continue
if (ld.get("attribute") or {}).get("text_rotate", "normal") != "normal":
stats["rotated"] += 1
continue
txt = ld.get("text") or ""
if re.search(r"[$\\<>|]", txt) or "{" in txt:
stats["markup_like"] += 1
continue
txt = unicodedata.normalize("NFC", re.sub(r"\s+", " ", txt)).strip()
if len(txt) < 3:
stats["too_short"] += 1
continue
nc, nl = len(cyr.findall(txt)), len(lat.findall(txt))
script = "Cyrl" if nc > nl else "Latn"
lang = code
if code == "uz":
lang = "uz_cyrl" if script == "Cyrl" else "uz_latn"
full = os.path.join(raw, "paragraph", "images", f"{stem}_{ld.get('anno_id')}.jpg")
if not os.path.exists(full):
stats["paragraph_crop_missing"] += 1
continue
with open(full, "rb") as fi:
sha = hashlib.sha256(fi.read()).hexdigest()
lid = f"more:{lang}:{stem}:{ld.get('anno_id')}"
if lang not in lex:
lex[lang] = rpp.build_lexicon(corpus, lang)[0]
toks = rpp.tokens(txt, lang)
sh = rpp.share(toks, lex[lang]) if len(toks) >= 8 else None
bad_chars = sorted({c for c in txt if c not in rpp.PUNCT and c.lower() not in set(rpp.PROFILES[lang]["letters"]) | set("abcdefghijklmnopqrstuvwxyz")})
rows.append({"id": lid, "image": full, "text": txt, "lang": lang, "script": script, "kind": "typed_real",
"source": "MORE:zimoqingfeng/MORE paragraph (page language code %s)" % code, "split": "test",
"group": stem, "unit": "paragraph", "sha256": sha, "lexicon_share": sh,
"chars_outside_alphabet": bad_chars, "chars": len(txt)})
stats["kept_" + lang] += 1
with open(os.path.join(out, "_sidecars", "more.jsonl"), "w", encoding="utf-8") as fo:
for r in rows:
fo.write(json.dumps(r, ensure_ascii=False) + "\n")
summary = {"kept": len(rows), "stats": dict(stats),
"pages_by_lang": dict(Counter(r["lang"] for r in {(r["group"], r["lang"]): r for r in rows}.values())),
"chars_total": sum(r["chars"] for r in rows),
"low_lexicon_share_blocks(<0.2, >=8 tokens)": [(r["id"], round(r["lexicon_share"], 2)) for r in rows if r["lexicon_share"] is not None and r["lexicon_share"] < 0.2],
"blocks_with_chars_outside_alphabet": sum(1 for r in rows if r["chars_outside_alphabet"])}
json.dump(summary, open(os.path.join(out, "_stats", "more.json"), "w"), indent=1, ensure_ascii=False)
print(json.dumps(summary, ensure_ascii=False)[:3000])