File size: 2,994 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
# /// script
# requires-python = ">=3.10"
# dependencies = ["lxml"]
# ///
"""Deduplicate tables by structure (grid of spans, cell content ignored).

Every <table> of every input file is hashed; the first table seen for each hash is
written to its own file, keeping its text.

Usage: uv run scripts/deduplicate_html.py [--src datasets/VietFinTab-image2html/html]
                                          [--out datasets/VietFinTab-image2html/html_unique]
                                          [--ignore-th]
"""
import argparse
import hashlib
from pathlib import Path

from lxml import html

ROW_XPATH = "./tr | ./thead/tr | ./tbody/tr | ./tfoot/tr"
HEAD = '<!DOCTYPE html>\n<meta charset="utf-8">\n'


def _span(v, zero=1):
    try:
        n = int(v)
    except (TypeError, ValueError):
        return 1
    return zero if n == 0 else max(n, 1)


def table_grid(table, keep_th=True):
    """Cells as (row, col, rowspan, colspan, is_th) in resolved grid coords. Content ignored."""
    rows = table.xpath(ROW_XPATH)
    n_rows = len(rows)
    occupied, cells = set(), []
    for r, tr in enumerate(rows):
        c = 0
        for cell in tr.xpath("./td | ./th"):
            while (r, c) in occupied:
                c += 1
            # shortcut: rowspan=0 -> rest of table (spec: rest of row group), overflow clipped
            rs = min(_span(cell.get("rowspan"), zero=n_rows - r), n_rows - r)
            cs = _span(cell.get("colspan"))
            for dr in range(rs):
                for dc in range(cs):
                    occupied.add((r + dr, c + dc))
            cells.append((r, c, rs, cs, keep_th and cell.tag == "th"))
            c += cs
    return cells


def signature(table, keep_th=True):
    payload = repr(table_grid(table, keep_th)).encode()
    return hashlib.blake2b(payload, digest_size=16).hexdigest()


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--src", type=Path, default=Path("datasets/VietFinTab-image2html/html"))
    p.add_argument("--out", type=Path, default=Path("datasets/VietFinTab-image2html/html_unique"))
    p.add_argument("--ignore-th", action="store_true", help="treat <th> like <td>")
    a = p.parse_args()

    a.out.mkdir(parents=True, exist_ok=True)
    seen, total = set(), 0
    for f in sorted(a.src.glob("*.html")):
        tree = html.fromstring(f.read_bytes())
        # root itself may be the table (a lone <table> parses to the element)
        for i, t in enumerate(tree.iter("table")):
            if t.xpath("ancestor::table"):  # nested: covered by parent
                continue
            total += 1
            sig = signature(t, not a.ignore_th)
            if sig in seen:
                continue
            seen.add(sig)
            body = html.tostring(t, encoding="unicode", with_tail=False)
            (a.out / f"{f.stem}_{i}.html").write_text(HEAD + body + "\n", encoding="utf-8")
    print(f"{total} tables -> {len(seen)} unique, written to {a.out}")


if __name__ == "__main__":
    main()