File size: 4,143 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
91
92
93
94
95
96
97
98
99
100
101
102
103
# /// 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}/")