Datasets:
Download scripts/stats.py from dinhanhx/ftu-VietFinTab: direct link, hf CLI and curl.
- Browser
- Download file 4.14 kB
-
https://huggingface.co/datasets/dinhanhx/ftu-VietFinTab/resolve/main/scripts/stats.py
- Command line
-
hf download hf://datasets/dinhanhx/ftu-VietFinTab/scripts/stats.py
-
curl -L -o stats.py https://huggingface.co/datasets/dinhanhx/ftu-VietFinTab/resolve/main/scripts/stats.py
4.14 kB
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = ["matplotlib", "numpy"] | |
| # /// | |
| """Dataset-level charts: tables per company, company x period heatmap, structure distributions. | |
| Usage: uv run scripts/stats.py [--root .] [--out figures] | |
| """ | |
| import argparse | |
| import json | |
| import xml.etree.ElementTree as ET | |
| from collections import Counter | |
| from pathlib import Path | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| BLUE = "#2a78d6" | |
| INK, MUTED = "#0b0b0b", "#52514e" | |
| QORDER = {"Q1": 0, "Q2": 1, "Q3": 2, "Q4": 3, "CN": 4} | |
| plt.rcParams.update({ | |
| "axes.spines.top": False, "axes.spines.right": False, | |
| "axes.edgecolor": MUTED, "axes.labelcolor": MUTED, "xtick.color": MUTED, | |
| "ytick.color": MUTED, "text.color": INK, "axes.titlelocation": "left", | |
| "axes.titleweight": "bold", "figure.dpi": 150, | |
| }) | |
| def load(root): | |
| return [json.loads(l) for l in (root / "metadata.jsonl").read_text().splitlines()] | |
| def per_company(meta, out): | |
| counts = Counter(m["company"] for m in meta).most_common() | |
| names, vals = zip(*counts) | |
| fig, ax = plt.subplots(figsize=(7, 4.5)) | |
| bars = ax.barh(names[::-1], vals[::-1], color=BLUE, height=0.6) | |
| ax.bar_label(bars, padding=3, color=INK) | |
| ax.set(xlabel="Table images", title=f"Tables per company (n={len(meta):,})") | |
| ax.set_xlim(0, max(vals) * 1.1) | |
| fig.tight_layout() | |
| fig.savefig(out / "tables_per_company.png") | |
| def company_period(meta, out): | |
| periods = sorted({(m["year"], m["quarter"]) for m in meta}, key=lambda p: (p[0], QORDER[p[1]])) | |
| companies = sorted({m["company"] for m in meta}) | |
| grid = np.zeros((len(companies), len(periods)), dtype=int) | |
| for m in meta: | |
| grid[companies.index(m["company"]), periods.index((m["year"], m["quarter"]))] += 1 | |
| fig, ax = plt.subplots(figsize=(10, 5.5)) | |
| im = ax.imshow(grid, cmap="Blues", aspect="auto") | |
| ax.set_xticks(range(len(periods)), [f"{q}\n{y}" for y, q in periods]) | |
| ax.set_yticks(range(len(companies)), companies) | |
| for (i, j), v in np.ndenumerate(grid): | |
| ax.text(j, i, v or "", ha="center", va="center", fontsize=7, | |
| color="white" if v > grid.max() * 0.55 else INK) | |
| ax.set_title("Tables per company and reporting period") | |
| for s in ax.spines.values(): | |
| s.set_visible(False) | |
| fig.colorbar(im, ax=ax, label="Table images", shrink=0.8) | |
| fig.tight_layout() | |
| fig.savefig(out / "tables_per_period.png") | |
| def parse(path): | |
| r = ET.parse(path).getroot() | |
| names = Counter(o.findtext("name") for o in r.iter("object")) | |
| return (int(r.findtext("size/width")), int(r.findtext("size/height")), | |
| names["table row"], names["table column"], names["table spanning cell"]) | |
| def structure(meta, root, out): | |
| w, h, rows, cols, spans = np.array([parse(root / m["structure_file"]) for m in meta]).T | |
| panels = [("Rows per table", rows), ("Columns per table", cols), | |
| ("Spanning cells per table", spans), ("Image width (px)", w), | |
| ("Image height (px)", h), ("Aspect ratio (w/h)", w / h)] | |
| fig, axes = plt.subplots(2, 3, figsize=(11, 6)) | |
| for ax, (title, x) in zip(axes.flat, panels): | |
| hi = np.percentile(x, 99) # clip the long tail so the bulk stays readable | |
| ax.hist(x[x <= hi], bins=30, color=BLUE, edgecolor="white", linewidth=0.5) | |
| ax.set(title=title, ylabel="Tables") | |
| ax.annotate(f"median {np.median(x):.4g}\np99 {hi:.4g}", (0.97, 0.95), | |
| xycoords="axes fraction", ha="right", va="top", color=MUTED, fontsize=8) | |
| fig.suptitle("Structure annotation statistics (x-axis clipped at p99)", x=0.01, ha="left", | |
| fontweight="bold") | |
| fig.tight_layout() | |
| fig.savefig(out / "structure_stats.png") | |
| 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("figures")) | |
| a = ap.parse_args() | |
| a.out.mkdir(exist_ok=True) | |
| meta = load(a.root) | |
| per_company(meta, a.out) | |
| company_period(meta, a.out) | |
| structure(meta, a.root, a.out) | |
| print(f"wrote 3 figures to {a.out}/") | |