ftu-VietFinTab / scripts /export_yolo.py
dinhanhx's picture
Add conversion scripts (YOLO, COCO, HTML) and tests
eb58dca
Raw History Blame Contribute Delete
3.21 kB
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""Export VietFinTab to a YOLO detection dataset: classes row, column, cell, table.
The source has no plain cell boxes, so cells are derived: every row x column
intersection not covered by a spanning cell, plus the spanning cells themselves.
Usage: uv run scripts/export_yolo.py [--root .] [--out VietFinTab-reconstruction] [--val 0.1] [--seed 0]
"""
import argparse
import json
import random
import shutil
import xml.etree.ElementTree as ET
from pathlib import Path
NAMES = ["row", "column", "cell", "table"]
def boxes(xml_path):
r = ET.parse(xml_path).getroot()
W, H = int(r.findtext("size/width")), int(r.findtext("size/height"))
by = {}
for o in r.iter("object"):
b = o.find("bndbox")
by.setdefault(o.findtext("name"), []).append(
tuple(float(b.findtext(k)) for k in ("xmin", "ymin", "xmax", "ymax")))
return (W, H, by.get("table row", []), by.get("table column", []),
by.get("table spanning cell", []), by.get("table", []))
def cells(rows, cols, spans):
out = list(spans)
for _, y0, _, y1 in rows:
for x0, _, x1, _ in cols:
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
if not any(a <= cx <= c and b <= cy <= d for a, b, c, d in spans):
out.append((x0, y0, x1, y1))
return out
def yolo_lines(W, H, groups):
lines = []
for cls, bs in enumerate(groups):
for x0, y0, x1, y1 in bs:
x0, x1, y0, y1 = max(x0, 0), min(x1, W), max(y0, 0), min(y1, H)
if x1 <= x0 or y1 <= y0:
continue # degenerate after clipping
lines.append(f"{cls} {(x0 + x1) / 2 / W:.6f} {(y0 + y1) / 2 / H:.6f} "
f"{(x1 - x0) / W:.6f} {(y1 - y0) / H:.6f}")
return lines
def export(root, out, val, seed):
meta = [json.loads(l) for l in (root / "metadata.jsonl").read_text().splitlines()]
random.Random(seed).shuffle(meta)
n_val = round(len(meta) * val)
for i, m in enumerate(meta):
split = "val" if i < n_val else "train"
W, H, rows, cols, spans, table = boxes(root / m["structure_file"])
for kind in ("images", "labels"):
(out / kind / split).mkdir(parents=True, exist_ok=True)
shutil.copy2(root / m["file_name"], out / "images" / split / f"{m['id']}.jpg")
(out / "labels" / split / f"{m['id']}.txt").write_text(
"\n".join(yolo_lines(W, H, [rows, cols, cells(rows, cols, spans), table])) + "\n")
names = "\n".join(f" {i}: {n}" for i, n in enumerate(NAMES))
(out / "data.yaml").write_text(
f"path: {out.resolve()}\ntrain: images/train\nval: images/val\nnames:\n{names}\n")
print(f"{len(meta) - n_val} train / {n_val} val -> {out}/")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent)
ap.add_argument("--out", type=Path, default=Path("datasets/VietFinTab-reconstruction-yolo"))
ap.add_argument("--val", type=float, default=0.1)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
export(a.root, a.out, a.val, a.seed)