Datasets:
Download scripts/overlay.py from dinhanhx/ftu-VietFinTab: direct link, hf CLI and curl.
- Browser
- Download file 1.99 kB
-
https://huggingface.co/datasets/dinhanhx/ftu-VietFinTab/resolve/main/scripts/overlay.py
- Command line
-
hf download hf://datasets/dinhanhx/ftu-VietFinTab/scripts/overlay.py
-
curl -L -o overlay.py https://huggingface.co/datasets/dinhanhx/ftu-VietFinTab/resolve/main/scripts/overlay.py
1.99 kB
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = ["pillow"] | |
| # /// | |
| """Draw structure (and OCR, if labeled) boxes on a table image. | |
| Usage: uv run scripts/overlay.py [ID ...] [--root .] [--out figures] | |
| With no ID, picks 3 random tables that have content labels. | |
| """ | |
| import argparse | |
| import json | |
| import random | |
| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| from PIL import Image, ImageDraw | |
| COLORS = {"table": "#0b0b0b", "table row": "#2a78d6", "table column": "#eb6834", | |
| "table spanning cell": "#1baf7a"} | |
| OCR = "#e87ba4" | |
| def overlay(m, root, out): | |
| img = Image.open(root / m["file_name"]).convert("RGB") | |
| d = ImageDraw.Draw(img, "RGBA") | |
| for o in ET.parse(root / m["structure_file"]).getroot().iter("object"): | |
| name, b = o.findtext("name"), o.find("bndbox") | |
| box = [int(b.findtext(k)) for k in ("xmin", "ymin", "xmax", "ymax")] | |
| c = COLORS.get(name, "#808080") | |
| if name == "table spanning cell": | |
| d.rectangle(box, fill=c + "40") | |
| d.rectangle(box, outline=c, width=2) | |
| if m["has_content_label"]: | |
| for t in json.loads((root / m["content_file"]).read_text())["ocr"]: | |
| d.rectangle(t["bbox"], outline=OCR, width=1) | |
| path = out / f"overlay_{m['id']}.png" | |
| img.save(path) | |
| return path | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("ids", nargs="*") | |
| ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent) | |
| ap.add_argument("--out", type=Path, default=Path("figures")) | |
| a = ap.parse_args() | |
| a.out.mkdir(exist_ok=True) | |
| meta = [json.loads(l) for l in (a.root / "metadata.jsonl").read_text().splitlines()] | |
| if a.ids: | |
| by_id = {m["id"]: m for m in meta} | |
| pick = [by_id[i] for i in a.ids] # KeyError on unknown id is the right failure | |
| else: | |
| pick = random.sample([m for m in meta if m["has_content_label"]], 3) | |
| for m in pick: | |
| print(overlay(m, a.root, a.out)) | |