"""Convert OCR datasets into the training format each framework expects. Step 1 writes canonical records, one JSONL per split: /canonical/.jsonl fields: id, image (absolute path), text, source, license, language, level ("page" or "line"), split Step 2 converts the canonical records into framework formats (--formats): hf canonical JSONL as-is; read by common/vlm_sft.py and common/vlm_infer.py qwenvl Qwen-VL / GOT format: {"image", "conversations": [human, gpt]} llamafactory LLaMA-Factory sharegpt JSONL + dataset_info.json swift ms-swift format: {"query", "response", "images"} olmocr one single-page PDF + one .md with YAML front matter per page nougat Nougat JSONL + .seek.map byte-offset index paddle_rec PaddleOCR recognizer label files + a character dictionary built from the labels (lines only) Sources are described in a YAML file (see configs/sources.example.yaml). Each source is a set of Parquet files with an image column (bytes or {"bytes": ...}) and a text column: python -m common.data_prep --sources configs/sources.yaml --formats hf qwenvl llamafactory python -m common.data_prep --sources configs/sources.yaml --limit 200 --formats hf # smoke test If you already have canonical JSONL files, skip step 1 with --canonical-dir . """ import argparse import glob import json import os from pathlib import Path import pyarrow.parquet as pq import yaml from PIL import Image from .paths import PREPARED_DIR, REPO_ROOT PAGE_PROMPT = ("Extract the main content from the document in the image, keeping the original structure. " "Convert all formulas to LaTeX and all tables to HTML.") # the FD-RL training prompt LINE_PROMPT = "Transcribe the text in this image exactly." SOURCE_DEFAULTS = {"image_col": "image", "text_col": "text", "level": "page", "license": "unknown", "language": None, "splits": {"train": "train"}} def load_sources(path: Path) -> dict: cfg = yaml.safe_load(Path(path).read_text(encoding="utf-8")) sources = {} for name, s in (cfg.get("sources") or {}).items(): if "files" not in s: raise SystemExit(f"source '{name}' needs a 'files' glob (use {{split}} for the split name)") sources[name] = {**SOURCE_DEFAULTS, **s} if not sources: raise SystemExit(f"no sources defined in {path}") return sources def _ext(b: bytes) -> str: if b[:3] == b"\xff\xd8\xff": return ".jpg" if b[:8] == b"\x89PNG\r\n\x1a\n": return ".png" return ".img" def _image_bytes(value): return value["bytes"] if isinstance(value, dict) else value def build_canonical(sources: dict, limit: int, out_dir: Path) -> dict: img_dir = out_dir / "images" img_dir.mkdir(parents=True, exist_ok=True) (out_dir / "canonical").mkdir(parents=True, exist_ok=True) writers, counts = {}, {} for src, cfg in sources.items(): for file_split, our_split in cfg["splits"].items(): # ${VAR} in a path comes from the environment (e.g. ${OCR_RAW_DIR}), so configs carry no machine paths pattern = os.path.expandvars(cfg["files"]).format(split=file_split) if "$" in pattern: raise SystemExit(f"source '{src}': unset environment variable in {cfg['files']}") if not Path(pattern).is_absolute(): pattern = str(REPO_ROOT / pattern) files = sorted(glob.glob(pattern)) if not files: print(f"warning: no files match {pattern}") continue n = 0 for f in files: pf = pq.ParquetFile(f) for rg in range(pf.num_row_groups): if limit and n >= limit: break for row in pf.read_row_group(rg, columns=[cfg["image_col"], cfg["text_col"]]).to_pylist(): if limit and n >= limit: break b = _image_bytes(row[cfg["image_col"]]) rid = f"{src}_{our_split}_{n:07d}" p = img_dir / (rid + _ext(b)) if not p.exists(): p.write_bytes(b) rec = {"id": rid, "image": str(p.resolve()), "text": row[cfg["text_col"]] or "", "source": src, "license": cfg["license"], "language": cfg["language"], "level": cfg["level"], "split": our_split} if our_split not in writers: writers[our_split] = open(out_dir / "canonical" / f"{our_split}.jsonl", "w", encoding="utf-8") writers[our_split].write(json.dumps(rec, ensure_ascii=False) + "\n") n += 1 if limit and n >= limit: break counts[f"{src}/{our_split}"] = n for w in writers.values(): w.close() print("canonical records:", counts) return {s: out_dir / "canonical" / f"{s}.jsonl" for s in writers} def read_jsonl(p): with open(p, encoding="utf-8-sig") as fh: for line in fh: if line.strip(): yield json.loads(line) def choose_prompt(rec, page_prompt=None, line_prompt=None): """Line records get the line prompt; page records get page_prompt (e.g. a model's own prompts/*.txt) or the default page prompt. A model's page prompt never replaces the line prompt.""" if rec.get("level") == "line": return line_prompt or LINE_PROMPT return page_prompt or PAGE_PROMPT def prompt_for(rec): return choose_prompt(rec) def export_qwenvl(split_files, out): out.mkdir(parents=True, exist_ok=True) for split, p in split_files.items(): rows = [{"image": r["image"], "conversations": [ {"from": "human", "value": "\n" + prompt_for(r)}, {"from": "gpt", "value": r["text"]}]} for r in read_jsonl(p)] (out / f"{split}.json").write_text(json.dumps(rows, ensure_ascii=False), encoding="utf-8") print("qwenvl ->", out) def export_llamafactory(split_files, out): out.mkdir(parents=True, exist_ok=True) info = {} for split, p in split_files.items(): name = f"ocr_{split}" with open(out / f"{name}.jsonl", "w", encoding="utf-8") as fh: for r in read_jsonl(p): fh.write(json.dumps({"messages": [ {"role": "user", "content": "" + prompt_for(r)}, {"role": "assistant", "content": r["text"]}], "images": [r["image"]]}, ensure_ascii=False) + "\n") info[name] = { "file_name": f"{name}.jsonl", "formatting": "sharegpt", "columns": {"messages": "messages", "images": "images"}, "tags": {"role_tag": "role", "content_tag": "content", "user_tag": "user", "assistant_tag": "assistant"}, } (out / "dataset_info.json").write_text(json.dumps(info, indent=2), encoding="utf-8") print("llamafactory ->", out) def export_swift(split_files, out): out.mkdir(parents=True, exist_ok=True) for split, p in split_files.items(): with open(out / f"{split}.jsonl", "w", encoding="utf-8") as fh: for r in read_jsonl(p): fh.write(json.dumps({"query": "" + prompt_for(r), "response": r["text"], "images": [r["image"]]}, ensure_ascii=False) + "\n") print("swift ->", out) def export_olmocr(split_files, out): # olmOCR trains on single-page PDFs paired with .md files that carry YAML front matter. for split, p in split_files.items(): d = out / split d.mkdir(parents=True, exist_ok=True) for r in read_jsonl(p): if r.get("level") == "line": continue # olmOCR is page-level pdf = d / (r["id"] + ".pdf") if not pdf.exists(): Image.open(r["image"]).convert("RGB").save(pdf, "PDF", resolution=150) fm = (f"---\nprimary_language: {r.get('language') or 'null'}\nis_rotation_valid: True\n" f"rotation_correction: 0\nis_table: {'", out) def export_nougat(split_files, out): # Nougat: .jsonl with "image" and "markdown", plus .seek.map (byte offsets). out.mkdir(parents=True, exist_ok=True) name_map = {"eval": "validation"} for split, p in split_files.items(): name = name_map.get(split, split) offsets = [] with open(out / f"{name}.jsonl", "wb") as fh: for r in read_jsonl(p): offsets.append(fh.tell()) img = Path(r["image"]).resolve().as_posix() # absolute: Path(root) / abs -> abs fh.write(json.dumps({"image": img, "markdown": r["text"], "source": r["source"]}, ensure_ascii=False).encode("utf-8") + b"\n") (out / f"{name}.seek.map").write_text(json.dumps(offsets), encoding="utf-8") print("nougat ->", out) def export_paddle_rec(split_files, out): # PaddleOCR SimpleDataSet: "\t