File size: 3,789 Bytes
eb58dca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""Export VietFinTab to an image -> HTML dataset (plain <table>, no CSS).

Structure comes from the XML (rows x columns grid, spanning cells -> rowspan/colspan);
text comes from the content JSON, so only the tables with a content label are exported.

Usage: uv run scripts/export_html.py [--root .] [--out datasets/VietFinTab-image2html]
"""
import argparse
import json
import shutil
from html import escape
from pathlib import Path

from export_yolo import boxes


def inside(b, x, y):
    return b[0] <= x <= b[2] and b[1] <= y <= b[3]


def cell_text(tokens):
    """tokens: [(text, (x0, y0, x1, y1))] -> text in reading order (lines by y, then x)."""
    lines = []
    for t, b in sorted(tokens, key=lambda t: t[1][1] + t[1][3]):
        cy, h = (b[1] + b[3]) / 2, b[3] - b[1]
        if lines and cy - lines[-1][0] <= h / 2:
            lines[-1][1].append((b[0], t))
        else:
            lines.append((cy, [(b[0], t)]))
    return " ".join(t for _, line in lines for _, t in sorted(line))


def build_html(rows, cols, spans, ocr):
    rows, cols = sorted(rows, key=lambda b: b[1]), sorted(cols, key=lambda b: b[0])
    center = lambda i, j: ((cols[j][0] + cols[j][2]) / 2, (rows[i][1] + rows[i][3]) / 2)
    anchor, covered = {}, set()  # anchor (i, j) -> (rowspan, colspan, key); covered = merged-away cells
    owner = {}  # (i, j) -> anchor of the cell that contains it
    for s in spans:
        grid = [(i, j) for i in range(len(rows)) for j in range(len(cols)) if inside(s, *center(i, j))]
        if not grid:
            continue
        i0, j0 = min(i for i, _ in grid), min(j for _, j in grid)
        anchor[(i0, j0)] = (max(i for i, _ in grid) - i0 + 1, max(j for _, j in grid) - j0 + 1)
        covered |= set(grid) - {(i0, j0)}
        owner.update({g: (i0, j0) for g in grid})
    tokens = {}
    for t in ocr:
        b = t["bbox"]
        cx, cy = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2
        i = next((i for i, r in enumerate(rows) if r[1] <= cy <= r[3]), None)
        j = next((j for j, c in enumerate(cols) if c[0] <= cx <= c[2]), None)
        if i is not None and j is not None:  # tokens outside the grid are dropped
            tokens.setdefault(owner.get((i, j), (i, j)), []).append((t["text"], b))
    out = ["<!DOCTYPE html>", '<meta charset="utf-8">', '<table border="1">']
    for i in range(len(rows)):
        tds = []
        for j in range(len(cols)):
            if (i, j) in covered:
                continue
            rs, cs = anchor.get((i, j), (1, 1))
            attrs = (f' rowspan="{rs}"' if rs > 1 else "") + (f' colspan="{cs}"' if cs > 1 else "")
            tds.append(f"<td{attrs}>{escape(cell_text(tokens.get((i, j), [])))}</td>")
        out.append(f"<tr>{''.join(tds)}</tr>")
    return "\n".join(out + ["</table>", ""])


def export(root, out):
    meta = [json.loads(l) for l in (root / "metadata.jsonl").read_text().splitlines()]
    meta = [m for m in meta if m["has_content_label"]]
    for d in ("images", "html"):
        (out / d).mkdir(parents=True, exist_ok=True)
    for m in meta:
        _, _, rows, cols, spans, _ = boxes(root / m["structure_file"])
        ocr = json.loads((root / m["content_file"]).read_text())["ocr"]
        shutil.copy2(root / m["file_name"], out / "images" / f"{m['id']}.jpg")
        (out / "html" / f"{m['id']}.html").write_text(build_html(rows, cols, spans, ocr), encoding="utf-8")
    print(f"{len(meta)} tables -> {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-image2html"))
    a = ap.parse_args()
    export(a.root, a.out)