aziz9788's picture
Initial commit
cf8c8d4
Raw History Blame Contribute Delete
11.9 kB
"""Convert OCR datasets into the training format each framework expects.
Step 1 writes canonical records, one JSONL per split:
<OCR_PREPARED_DIR>/canonical/<split>.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 <folder>.
"""
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": "<image>\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": "<image>" + 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": "<image>" + 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: {'<table' in r['text']}\nis_diagram: False\n---\n")
(d / (r["id"] + ".md")).write_text(fm + r["text"], encoding="utf-8")
print("olmocr ->", out)
def export_nougat(split_files, out):
# Nougat: <split>.jsonl with "image" and "markdown", plus <split>.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: "<image path>\t<label>" per line; line-level records only.
out.mkdir(parents=True, exist_ok=True)
chars = set()
for split, p in split_files.items():
n = 0
with open(out / f"rec_{split}.txt", "w", encoding="utf-8") as fh:
for r in read_jsonl(p):
if r.get("level") != "line":
continue
label = r["text"].replace("\t", " ").replace("\n", " ").strip()
if not label:
continue
chars.update(label)
fh.write(f"{r['image']}\t{label}\n")
n += 1
print(f"paddle_rec {split}: {n} lines")
chars.discard(" ") # PaddleOCR adds the space itself when use_space_char is true
(out / "dict.txt").write_text("\n".join(sorted(chars)) + "\n", encoding="utf-8")
print(f"paddle_rec -> {out} (dictionary: {len(chars)} characters)")
EXPORTERS = {
"qwenvl": export_qwenvl, "llamafactory": export_llamafactory, "swift": export_swift,
"olmocr": export_olmocr, "nougat": export_nougat, "paddle_rec": export_paddle_rec,
}
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--sources", type=Path, help="YAML file describing the datasets (configs/sources.example.yaml)")
src.add_argument("--canonical-dir", type=Path, help="folder that already holds canonical <split>.jsonl files")
ap.add_argument("--only", nargs="+", help="use only these source names from the YAML file")
ap.add_argument("--limit", type=int, default=0, help="max records per source split (0 = all)")
ap.add_argument("--formats", nargs="+", default=["hf"], choices=["hf", *EXPORTERS])
ap.add_argument("--out", type=Path, default=PREPARED_DIR)
a = ap.parse_args(argv)
if a.canonical_dir:
split_files = {p.stem: p for p in sorted(a.canonical_dir.glob("*.jsonl"))}
if not split_files:
raise SystemExit(f"no *.jsonl files in {a.canonical_dir}")
else:
sources = load_sources(a.sources)
if a.only:
unknown = set(a.only) - set(sources)
if unknown:
raise SystemExit(f"unknown source(s): {', '.join(sorted(unknown))}")
sources = {k: v for k, v in sources.items() if k in a.only}
split_files = build_canonical(sources, a.limit, a.out)
for f in a.formats:
if f != "hf":
EXPORTERS[f](split_files, a.out / f)
if __name__ == "__main__":
main()