File size: 12,044 Bytes
cf8c8d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
r"""Synthetic document pages with structure annotations -> page-level Markdown training records.

Input: parquet files with an `image` column and a `json` column holding the page annotation
(`page_information`, `element_bboxes` in reading order with types such as heading, paragraph, list, table
with cells, formula with LaTeX, caption, figure, header, footer, page_number, watermark).

The target is written in the parsing model's own output style (OvisOCR-style document Markdown):
- paragraphs separated by a blank line; headings as Markdown headings (`#` per level);
- tables as compact HTML `<table><thead><tr><td>..</td></tr></thead><tbody>..</tbody></table>`, with
  rowspan / colspan, and the cells of every row in **visual left-to-right order** (the convention of
  OmniDocBench-style ground truth, also for right-to-left scripts);
- display formulas as `$$ latex $$`; figures as `<img src="images/bbox_l_t_r_b.jpg" />` on a 0-1000 grid;
- running headers, footers and page numbers kept as plain text lines (as the model writes them);
  watermarks dropped.

A target is only as good as its match to the model's style: check it with `--validate` first (the base
model's reading of clean pages should agree with the converted target).

    python -m common.synth_convert --input "data/raw/synth_OCR/data/*/*.parquet" --out data/prepared/synth \
        --per-subset 400 --seed 0
"""
import argparse
import glob
import io
import json
import random
import re
from collections import Counter
from pathlib import Path

from .vlm_utils import write_jsonl

SKIP = {"watermark"}
TEXT_TYPES = {"paragraph", "caption", "footnote", "quote", "stat", "header", "footer", "page_number", "title"}
NUM = re.compile(r"^\s*\d+[.)]\s*")
BULLET = re.compile(r"^\s*[-•·*]\s*")
REPEAT = re.compile(r"(.)\1{40,}|(.{2,12}?)\2{15,}", re.S)  # degenerate runs: never train on them


def _cells_html(el):
    """HTML for a table element; cells of each row in visual left-to-right order."""
    cells = el.get("cells") or []
    if not cells:
        return None
    rows = {}
    for c in cells:
        rows.setdefault(c["row"], []).append(c)
    head, body = [], []
    for r in sorted(rows):
        ordered = sorted(rows[r], key=lambda c: c["bbox"][0])  # left edge, left to right
        tds = []
        for c in ordered:
            attrs = ""
            if c.get("rowspan", 1) > 1:
                attrs += f' rowspan="{c["rowspan"]}"'
            if c.get("colspan", 1) > 1:
                attrs += f' colspan="{c["colspan"]}"'
            tds.append(f"<td{attrs}>{_inline(c.get('text', ''))}</td>")
        tr = "<tr>" + "".join(tds) + "</tr>"
        (head if all(c.get("header") for c in rows[r]) and not body else body).append(tr)
    html = "<table>"
    if head:
        html += "<thead>" + "".join(head) + "</thead>"
    if body:
        html += "<tbody>" + "".join(body) + "</tbody>"
    return html + "</table>"


def _inline(s):
    return re.sub(r"\s*\n\s*", " ", s or "").strip()


def _list(el):
    items = [x.strip() for x in (el.get("text") or "").split("\n") if x.strip()]
    if el.get("ordered"):  # (no backslashes inside f-strings: Python < 3.12 rejects them)
        return "\n".join(str(i) + ". " + NUM.sub("", x) for i, x in enumerate(items, 1))
    return "\n".join("- " + BULLET.sub("", x) for x in items)


def element_md(el, img_w, img_h):
    t = el["type"]
    if t in SKIP:
        return None
    if t == "table":
        return _cells_html(el)
    if t == "formula":
        latex = (el.get("latex") or "").strip()
        return f"$$\n{latex}\n$$" if latex else None
    if t == "figure":
        x, y, w, h = el["bbox"]
        sc = lambda v, d: max(0, min(999, int(v / d * 1000)))  # noqa: E731
        return f'<img src="images/bbox_{sc(x, img_w)}_{sc(y, img_h)}_{sc(x + w, img_w)}_{sc(y + h, img_h)}.jpg" />'
    if t == "heading":
        return "#" * max(1, min(6, int(el.get("level") or 2))) + " " + _inline(el.get("text"))
    if t == "list":
        return _list(el)
    text = (el.get("text") or "").strip()
    return text or None


def page_markdown(ann):
    pi = ann["page_information"]
    w, h = pi.get("image_width") or pi["width"], pi.get("image_height") or pi["height"]
    parts = [element_md(e, w, h) for e in ann["element_bboxes"]]
    return "\n\n".join(p for p in parts if p)


GT_CATEGORY = {"paragraph": "text_block", "list": "text_block", "quote": "text_block", "stat": "text_block",
               "footnote": "text_block", "heading": "title", "title": "title", "header": "header", "footer": "footer",
               "page_number": "page_number", "table": "table", "formula": "equation_isolated", "figure": "figure"}
LANG_NAME = {"ar": "Arabic", "en": "English", "zh": "Chinese"}
IGNORED = {"header", "footer", "page_number"}  # no reading-order index, as in the benchmark's own ground truth


def page_gt(ann, image_name):
    """The page in OmniDocBench / MDPBench ground-truth form, so the official scorer can grade readings of it."""
    els, dets, order = ann["element_bboxes"], [], 0
    for i, e in enumerate(els):
        t = e["type"]
        if t == "caption":
            tgt = e.get("target")
            cat = "table_caption" if isinstance(tgt, int) and 0 <= tgt < len(els) and els[tgt]["type"] == "table" \
                else "figure_caption"
        else:
            cat = GT_CATEGORY.get(t)
        if cat is None:
            continue
        x, y, w, h = e["bbox"]
        d = {"category_type": cat, "poly": [x, y, x + w, y, x + w, y + h, x, y + h],
             "order": None if cat in IGNORED else order, "anno_id": i,
             "attribute": {"text_language": LANG_NAME.get((e.get("lang") or ["und"])[0], "Other")},
             "text": "", "html": "", "latex": ""}
        if cat == "table":
            d["html"] = _cells_html(e) or ""
        elif cat == "equation_isolated":
            d["latex"] = (e.get("latex") or "").strip()
        elif cat != "figure":
            d["text"] = (e.get("text") or "").strip() if t != "heading" else _inline(e.get("text"))
        if cat not in IGNORED:
            order += 1
        dets.append(d)
    lang = page_language(ann)
    return {"layout_dets": dets, "extra": {"relation": []},
            "page_info": {"image_path": image_name, "page_attribute": {"language": LANG_NAME.get(lang, "Other")}}}


def page_language(ann):
    c = Counter(l for e in ann["element_bboxes"] for l in e.get("lang", []))
    return c.most_common(1)[0][0] if c else "und"


def line_height(ann):
    """Median text-line height in image pixels: below ~16 px Arabic dots and diacritics are barely resolved,
    and training on text the model cannot see teaches it to guess."""
    hs = sorted(l["bbox"][3] for l in ann.get("line_bboxes", []) if l.get("bbox") and l["bbox"][3] > 0)
    return hs[len(hs) // 2] if hs else 0.0


def page_id(subset, parquet_file, ann, fallback):
    """Unique per page: subset, shard number (train-00002-of-00008 -> 00002) and the page id in the shard."""
    stem = Path(parquet_file).stem
    m = re.match(r".*?-(\d+)-of-\d+$", stem)
    shard = m.group(1) if m else stem
    return f"synth_{subset}_{shard}_{ann['page_information'].get('id', fallback)}"


def effects(ann):
    pi = ann["page_information"]
    return "photo" if pi.get("photo") else "scan" if pi.get("scan") else "clean"


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--input", required=True, help="glob of parquet files (subset = parent folder name)")
    ap.add_argument("--out", required=True, help="folder for images/ and synth.jsonl")
    ap.add_argument("--per-subset", type=int, default=0, help="pages per subset (0 = all)")
    ap.add_argument("--only-clean", action="store_true", help="no photo / scan effects (for --validate sets)")
    ap.add_argument("--languages", nargs="*", help="keep pages whose main language is one of these")
    ap.add_argument("--min-line-px", type=float, default=0.0,
                    help="drop pages whose median text-line height is below this many image pixels (e.g. 16)")
    ap.add_argument("--skip-subsets", nargs="*", default=[],
                    help="subset folders to leave out (e.g. receipts, whose key-value blocks are labelled as tables)")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--bench", help="also write a benchmark subset of this name (gt.json + items.jsonl) for "
                                    "`python -m common.mdpbench score`; page ids get a language prefix (ar_...)")
    a = ap.parse_args(argv)
    import pyarrow.parquet as pq

    out = Path(a.out)
    (out / "images").mkdir(parents=True, exist_ok=True)
    by_subset = {}
    for f in sorted(glob.glob(a.input)):
        if Path(f).parent.name not in a.skip_subsets:
            by_subset.setdefault(Path(f).parent.name, []).append(f)
    rng = random.Random(a.seed)
    records, dropped, gts, seen = [], Counter(), [], set()
    for sub, files in sorted(by_subset.items()):
        kept = 0
        files = files[:]
        rng.shuffle(files)
        for f in files:
            pf = pq.ParquetFile(f)
            for batch in pf.iter_batches(batch_size=32):
                for row in batch.to_pylist():
                    if a.per_subset and kept >= a.per_subset:
                        break
                    ann = json.loads(row["json"])
                    if a.only_clean and effects(ann) != "clean":
                        continue
                    lang = page_language(ann)
                    if a.languages and lang not in a.languages:
                        continue
                    lh = line_height(ann)
                    if lh < a.min_line_px:
                        dropped["text too small"] += 1
                        continue
                    text = page_markdown(ann)
                    if not text.strip():
                        dropped["empty"] += 1
                        continue
                    if REPEAT.search(text):
                        dropped["repetition"] += 1
                        continue
                    pid = page_id(sub, f, ann, kept)
                    if pid in seen:
                        raise SystemExit(f"duplicate page id {pid}: ids must be unique across shards")
                    seen.add(pid)
                    img = out / "images" / f"{pid}.png"
                    if not img.exists():
                        img.write_bytes(row["image"]["bytes"])
                    records.append({"id": pid, "image": str(img.resolve()), "text": text, "source": f"synth_OCR/{sub}",
                                    "license": "see dataset card", "language": lang, "level": "page", "split": "train",
                                    "effects": effects(ann), "template": ann["page_information"].get("template"),
                                    "line_px": round(lh, 1)})
                    if a.bench:
                        gts.append(page_gt(ann, f"{lang}_{pid}.png"))
                    kept += 1
                if a.per_subset and kept >= a.per_subset:
                    break
            if a.per_subset and kept >= a.per_subset:
                break
        print(f"{sub}: {kept} pages", flush=True)
    write_jsonl(out / "synth.jsonl", records)
    if a.bench:
        from .mdpbench import BENCH_DIR
        d = BENCH_DIR / "subsets" / a.bench
        d.mkdir(parents=True, exist_ok=True)
        (d / "gt.json").write_text(json.dumps(gts, ensure_ascii=False), encoding="utf-8")
        write_jsonl(d / "items.jsonl", [{"id": f"{r['language']}_{r['id']}", "image": r["image"], "text": "",
                                         "level": "page", "language": r["language"]} for r in records])
        print(f"benchmark subset {a.bench}: {len(gts)} pages -> {d}")
    langs = Counter(r["language"] for r in records)
    print(f"{len(records)} records -> {out / 'synth.jsonl'} | languages {dict(langs)} | dropped {dict(dropped)}")


if __name__ == "__main__":
    main()