File size: 7,798 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
"""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()