Download src/pagesynth/generate_pages.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/pagesynth/generate_pages.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/src/pagesynth/generate_pages.py
-
curl -L -o generate_pages.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/pagesynth/generate_pages.py
7.8 kB
| """Driver for pagesynth. | |
| Usage: | |
| python generate_pages.py --type notebook --lang kk --n 100 --seed 1 --strength mixed --out OUT \ | |
| --text-dir TEXT [--start 0] [--overlays 6] [--no-personal-fonts] | |
| --type notebook | worksheet | diagram | table | mixed | |
| --lang kk ky uz_cyrl uz_latn tt ba sah tr az tk | |
| --strength light | medium | heavy | mixed | |
| --start/--n page index range (a Slurm array task uses start = task*1000, n = 1000) | |
| --force key=value (repeatable), illustration only: overrides single decisions of make_page (see generate.make_page); | |
| values: true/false, numbers, comma lists (marks=0,3); the manifest records them. Never used for training pages. | |
| --spots write info.spots (output rectangles of marks and paper effects) into the page JSON, for crops of examples | |
| --allow-vocab-fallback development slices only: use a vocabulary built from the sentence bank when label_words*.json is missing | |
| Output: OUT/<type>/<lang>/<page_id>.jpg and .json, OUT/<type>/<lang>/_log_<start>.jsonl (one | |
| record per page with attempts and failed gates), manifest_<type>_<lang>_<start>.json (provenance: | |
| package version, content hash of the code, font file hashes, corpus file hash). | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| import time | |
| os.environ.setdefault("OMP_NUM_THREADS", "1") | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import cv2 # noqa: E402 | |
| cv2.setNumThreads(1) | |
| from pagesynth import fonts as F # noqa: E402 | |
| from pagesynth import generate as GEN # noqa: E402 | |
| from pagesynth import qa as QA # noqa: E402 | |
| from pagesynth import text as T # noqa: E402 | |
| def code_hash(root): | |
| """Git-free content hash of the package source (sorted relative paths + bytes).""" | |
| h = hashlib.sha256() | |
| for dirpath, dirnames, filenames in os.walk(root): | |
| dirnames[:] = sorted(d for d in dirnames if d not in ("__pycache__", ".venv_gen", "_tmp", "assets", "samples")) | |
| for fn in sorted(filenames): | |
| if fn.endswith((".py", ".sbatch", ".sh")) or fn == "requirements_gen.txt": # code only: reports and problem logs are not hashed | |
| p = os.path.join(dirpath, fn) | |
| h.update(os.path.relpath(p, root).encode("utf-8")) | |
| with open(p, "rb") as f: | |
| h.update(f.read()) | |
| return h.hexdigest() | |
| def generator_hash(root): | |
| """Hash of the generator alone (pagesynth/*.py, generate_pages.py, requirements): unchanged when only analysis scripts change.""" | |
| h = hashlib.sha256() | |
| files = sorted(os.path.join("pagesynth", f) for f in os.listdir(os.path.join(root, "pagesynth")) if f.endswith(".py")) + ["generate_pages.py", "requirements_gen.txt"] | |
| for rel in files: | |
| h.update(rel.encode("utf-8")) | |
| with open(os.path.join(root, rel), "rb") as f: | |
| h.update(f.read()) | |
| return h.hexdigest() | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--type", default="notebook") | |
| ap.add_argument("--lang", required=True) | |
| ap.add_argument("--n", type=int, default=10) | |
| ap.add_argument("--start", type=int, default=0) | |
| ap.add_argument("--seed", type=int, default=1) | |
| ap.add_argument("--strength", default="mixed") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--text-dir", required=True) | |
| ap.add_argument("--overlays", type=int, default=0, help="write overlay images for the first K pages") | |
| ap.add_argument("--no-personal-fonts", action="store_true") | |
| ap.add_argument("--display", action="store_true", help="display-safe text (no person names) and geographic map labels; for showcase pages") | |
| ap.add_argument("--jpeg-quality", type=int, default=92) | |
| ap.add_argument("--force", action="append", default=[]) | |
| ap.add_argument("--spots", action="store_true") | |
| ap.add_argument("--allow-vocab-fallback", action="store_true") | |
| a = ap.parse_args() | |
| force = {} | |
| for kv in a.force: | |
| k, _, v = kv.partition("=") | |
| vals = [] | |
| for tok in v.split(","): | |
| if tok.lower() in ("true", "false"): | |
| vals.append(tok.lower() == "true") | |
| else: | |
| try: | |
| vals.append(int(tok)) | |
| except ValueError: | |
| try: | |
| vals.append(float(tok)) | |
| except ValueError: | |
| vals.append(tok) | |
| force[k] = vals if "," in v else vals[0] | |
| root = os.path.dirname(os.path.abspath(__file__)) | |
| odir = os.path.join(a.out, a.type, a.lang) | |
| os.makedirs(odir, exist_ok=True) | |
| t0 = time.time() | |
| corpus_file = "sentences_display.tsv" if a.display else "sentences.tsv" | |
| banks = GEN.load_banks(a.text_dir, [a.lang], filename=corpus_file) | |
| if banks[a.lang].vocab.source == "bank-fallback" and not a.allow_vocab_fallback: | |
| sys.exit("label vocabulary file missing in %s/%s (run scripts/build_label_vocab.py) - or pass --allow-vocab-fallback for a development slice" % (a.text_dir, a.lang)) | |
| corpus_path = os.path.join(a.text_dir, a.lang, corpus_file) | |
| manifest = dict(package="pagesynth", version=GEN.VERSION, text_version=T.VERSION, code_sha256=code_hash(root), generator_sha256=generator_hash(root), fonts=F.font_manifest(), | |
| corpus=dict(path=corpus_path, sha256=T.content_hash(corpus_path), sentences=len(banks[a.lang])), | |
| calibration_sources=[dict(record="https://zenodo.org/records/15479725", doi="10.5281/zenodo.15479725", licence="CC BY 4.0", | |
| use="calibration of the procedural squared paper only; no pixel of these scans is in any page")], | |
| label_vocab=dict(source=banks[a.lang].vocab.source, words=len(banks[a.lang].vocab)), | |
| map_data=dict(source="Natural Earth 1:50m (public domain), terms checked 19 Nov 2026", url="https://www.naturalearthdata.com/about/terms-of-use/"), | |
| args=vars(a), force=force) | |
| log = open(os.path.join(odir, "_log_%d.jsonl" % a.start), "w", encoding="utf-8") | |
| done = fail = 0 | |
| for i in range(a.start, a.start + a.n): | |
| t1 = time.time() | |
| img, pj, qa, failures = GEN.attempt_page(a.type, a.lang, i, a.seed, a.strength, banks, include_personal=not a.no_personal_fonts, force=force or None, record_spots=a.spots) | |
| rec = dict(index=i, failures=[dict(attempt=x, gate=g, detail=d) for x, g, d in failures], seconds=round(time.time() - t1, 2)) | |
| if img is None: | |
| rec["written"] = False | |
| fail += 1 | |
| else: | |
| pid = pj["page_id"] | |
| cv2.imwrite(os.path.join(odir, pid + ".jpg"), img, [cv2.IMWRITE_JPEG_QUALITY, a.jpeg_quality]) | |
| with open(os.path.join(odir, pid + ".json"), "w", encoding="utf-8") as f: | |
| json.dump(pj, f, ensure_ascii=False, indent=None, separators=(",", ":"), sort_keys=True) | |
| if i - a.start < a.overlays: | |
| cv2.imwrite(os.path.join(odir, pid + "_overlay.jpg"), QA.overlay(img, pj), [cv2.IMWRITE_JPEG_QUALITY, 90]) | |
| rec.update(written=True, page_id=pid, lines=len(pj["lines"]), strength=pj["strength"], mode=pj["geometry"]["mode"], attempt=pj["info"]["attempt"], | |
| licence_class=pj["licence_class"]) | |
| done += 1 | |
| log.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| log.flush() | |
| log.close() | |
| manifest["pages_written"], manifest["pages_failed"], manifest["seconds"] = done, fail, round(time.time() - t0, 1) | |
| with open(os.path.join(a.out, "manifest_%s_%s_%d.json" % (a.type, a.lang, a.start)), "w", encoding="utf-8") as f: | |
| json.dump(manifest, f, ensure_ascii=False, indent=1) | |
| print("pages written %d failed %d seconds %.1f" % (done, fail, time.time() - t0)) | |
| if __name__ == "__main__": | |
| main() | |