File size: 7,130 Bytes
7c6d5e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""PlotQA benchmark (real-world data, Bokeh-rendered line / dot / bar charts).

Data: Hugging Face dataset ``martinsinnona/plotqa`` (images + Vega-style specs with
the plotted values), downloaded to ``data/benchmarks/plotqa_raw/{test,train}.parquet``.

    python -m tests.bench_plotqa --split test            # prepare + evaluate
    python -m tests.bench_plotqa --split train --n 200 --out eval_out/plotqa

Metrics: per-point error as a fraction of the y range [min(0, y_min), y_max] (the
true axis limits are not in the spec), recall, and RNSS (ChartQA / DePlot).
"""

from __future__ import annotations

import argparse
import ast
import io
import json
import time
import traceback
from multiprocessing import Pool
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd
from PIL import Image

from plotscribe import export, pipeline
from tests.metrics import AxisInfo, rnss, score_table

RAW = Path("data/benchmarks/plotqa_raw")
OUT = Path("data/benchmarks/plotqa")


def prepare(split: str, n: int | None) -> list[Path]:
    """Write ``<id>.png``, ``<id>.csv`` (ground truth) and ``<id>.json`` (meta) per chart."""
    dest = OUT / split
    dest.mkdir(parents=True, exist_ok=True)
    df = pd.read_parquet(RAW / f"{split}.parquet")
    paths = []
    for i, (img, text) in enumerate(zip(df.image, df.text)):
        if n is not None and i >= n:
            break
        spec = ast.literal_eval(text)
        stem = dest / f"{split}_{i:04d}"
        png = stem.with_suffix(".png")
        if not png.exists():
            Image.open(io.BytesIO(img["bytes"])).convert("RGB").save(png)
        vals = spec["data"]["values"]
        name = spec["encoding"]["y"]["field"]
        gt = pd.DataFrame({"x": [v["x"] for v in vals], name: [float(v["y"]) for v in vals]})
        gt.to_csv(stem.with_suffix(".csv"), index=False)
        stem.with_suffix(".json").write_text(json.dumps(
            {"mark": spec["mark"], "x_type": spec["encoding"]["x"]["type"]}))
        paths.append(png)
    return paths


def _as_numeric(col: pd.Series) -> pd.Series | None:
    v = pd.to_numeric(col.astype(str).str.strip(), errors="coerce")
    return v if v.notna().mean() >= 0.8 else None


def evaluate_one(png: str) -> dict[str, Any]:
    p = Path(png)
    meta = json.loads(p.with_suffix(".json").read_text())
    gt = pd.read_csv(p.with_suffix(".csv"), dtype={"x": str})
    rec: dict[str, Any] = {"chart": p.stem, "mark": meta["mark"], "x_type": meta["x_type"], "ok": False}
    t0 = time.time()
    try:
        res = pipeline.run(p)
    except Exception as exc:  # noqa: BLE001
        rec["error"] = f"{type(exc).__name__}: {exc}"
        rec["trace"] = traceback.format_exc(limit=3)
        return rec
    rec.update(ok=True, runtime_s=time.time() - t0, status=res.extra.get("status"), type=res.chart_type,
               warnings=res.warnings)
    y = gt.iloc[:, 1].to_numpy(float)
    if np.ptp(y) == 0:
        # Degenerate annotation (e.g. values rounded to 0.0 in the dataset): unscoreable.
        rec.update(gt_invalid=True, median_err=np.nan, recall=np.nan, rnss=np.nan, abstain=False)
        return rec
    rec["gt_invalid"] = False
    ya = AxisInfo(min(0.0, y.min()), y.max() if y.max() > min(0.0, y.min()) else y.max() + 1)
    pred = res.table
    if pred is None or any("[px]" in str(c) for c in pred.columns):
        rec.update(median_err=np.nan, recall=0.0, rnss=0.0, abstain=True)
        return rec
    rec["abstain"] = False
    gx = _as_numeric(gt.iloc[:, 0])
    px = _as_numeric(pred.iloc[:, 0]) if len(pred) else None
    if gx is not None and px is not None:
        g2 = gt.assign(x=gx)
        p2 = pred.assign(**{pred.columns[0]: px.to_numpy(float)})
        # Collapse multiple predicted series to the best-matching one (single-series GT).
        xa = AxisInfo(float(gx.min()) - 0.5, float(gx.max()) + 0.5)
        mode = "numeric"
        if meta["mark"] == "bar" or meta["mark"] == "circle":
            mode = "scatter" if meta["mark"] == "circle" else "numeric"
        sc = score_table(p2, g2, mode, xa, ya)
    else:
        sc = score_table(pred, gt.rename(columns={"x": "category"}), "categorical", None, ya)
    s = sc.summary()
    rec.update(median_err=s["median_err"], max_err=s["max_err"], recall=s["recall"],
               n_pred_series=s["n_pred_series"], category_acc=s["category_acc"], rnss=rnss(pred, gt))
    return rec


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test", choices=["test", "train"])
    ap.add_argument("--n", type=int, default=None)
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--out", type=Path, default=Path("eval_out/plotqa"))
    ap.add_argument("--worst", type=int, default=12)
    a = ap.parse_args()
    paths = prepare(a.split, a.n)
    with Pool(a.workers) as pool:
        recs = pool.map(evaluate_one, [str(p) for p in paths], chunksize=1)
    a.out.mkdir(parents=True, exist_ok=True)
    (a.out / "results.json").write_text(json.dumps(recs, indent=1, default=str))
    df = pd.DataFrame(recs)
    if "gt_invalid" in df:
        n_bad = int(df["gt_invalid"].fillna(False).astype(bool).sum())
        if n_bad:
            print(f"excluded {n_bad} chart(s) with degenerate ground truth")
        df = df[~df["gt_invalid"].fillna(False).astype(bool)]
    df["kind"] = df["mark"] + "/" + df["x_type"]
    ok = df[df["ok"]]
    good = ok[~ok["abstain"]]

    def summary(g: pd.DataFrame) -> pd.Series:
        e = g[g["ok"] & ~g["abstain"].astype(bool)]
        return pd.Series({
            "n": len(g), "crash": int((~g["ok"]).sum()),
            "status_ok": (g["status"] == "ok").mean(),
            "abstain": g["abstain"].astype(bool).mean(),
            "rnss": g["rnss"].fillna(0).mean(),
            "recall": g["recall"].fillna(0).mean(),
            "med_err": e["median_err"].median(),
            "p90_chart_err": e["median_err"].quantile(0.9),
            "within_1pct": (e["median_err"] < 0.01).sum() / max(len(g), 1),
            "silent_fail": ((e["status"] == "ok") & ((e["median_err"] > 0.02) | (e["recall"] < 0.5))).sum()
            / max(len(g), 1),
        })

    pd.set_option("display.width", 200, "display.precision", 4)
    table = pd.DataFrame({k: summary(g) for k, g in df.groupby("kind")}).T
    table.loc["ALL"] = summary(df)
    print(table.to_string())
    worst = df.assign(bad=df["rnss"].fillna(-1)).sort_values("bad").head(a.worst)
    wdir = a.out / "worst"
    wdir.mkdir(parents=True, exist_ok=True)
    print("\nworst cases:")
    for _, r in worst.iterrows():
        print(f"  {r['chart']} {r['kind']} status={r.get('status')} type={r.get('type')} rnss={r.get('rnss')!s:.5} "
              f"err={r.get('median_err')!s:.6} | {'; '.join((r.get('warnings') or [])[:3]) if isinstance(r.get('warnings'), list) else r.get('error')}")
        try:
            res = pipeline.run(OUT / a.split / f"{r['chart']}.png")
            export.write_debug_overlay(res, wdir / f"{r['chart']}.debug.png")
        except Exception:  # noqa: BLE001
            pass
    _ = good


if __name__ == "__main__":
    main()