# /// script
# requires-python = ">=3.10"
# dependencies = ["lxml"]
# ///
"""Deduplicate tables by structure (grid of spans, cell content ignored).
Every
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 = '\n\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 | like | ")
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 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()
|