File size: 2,702 Bytes
6f423bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate plotscribe on hand-labelled real charts in tests/real/ (same metrics as synthetic)."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
import pandas as pd

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


def _infer(gt: pd.DataFrame, meta: dict) -> tuple[str, AxisInfo | None, AxisInfo]:
    first = gt.columns[0]
    vals = gt[gt.columns[1:]].to_numpy(float)
    if "kind" in meta:
        kind = meta["kind"]
    elif first == "category":
        kind = "bar"
    elif (gt[gt.columns[1:]].notna().sum(axis=1) == 1).all() and gt.shape[1] > 2:
        kind = "scatter"
    else:
        kind = "line"
    mode = "scatter" if kind == "scatter" else ("categorical" if first == "category" else "numeric")
    ylo, yhi = meta.get("ylim", [np.nanmin(vals), np.nanmax(vals)])
    if ylo == yhi:
        yhi = ylo + 1
    ya = AxisInfo(min(ylo, yhi), max(ylo, yhi), log=bool(meta.get("ylog")))
    xa = None
    if mode != "categorical":
        x = pd.to_numeric(gt[first], errors="coerce")
        xlo, xhi = meta.get("xlim", [x.min(), x.max()])
        xa = AxisInfo(min(xlo, xhi), max(xlo, xhi) if xhi != xlo else xlo + 1)
    return mode, xa, ya


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dir", type=Path, default=Path(__file__).parent / "real")
    ap.add_argument("--out", type=Path, default=None)
    a = ap.parse_args()
    rows = []
    for img in sorted(p for p in a.dir.iterdir() if p.suffix.lower() in (".png", ".jpg", ".jpeg")):
        gt_path = img.with_suffix(".csv")
        if not gt_path.exists():
            print(f"skip {img.name}: no ground-truth CSV")
            continue
        gt = pd.read_csv(gt_path)
        meta_path = img.with_suffix(".json")
        meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}
        mode, xa, ya = _infer(gt, meta)
        res = pipeline.run(img)
        sc = score_table(res.table, gt, mode, xa, ya)
        rows.append({"chart": img.name, "status": res.extra.get("status"), "type": res.chart_type,
                     **{k: v for k, v in sc.summary().items() if k != "notes"}})
        if a.out:
            export.write_all(res, a.out, img.stem, debug=True)
    if not rows:
        print(f"no labelled charts in {a.dir}")
        return
    df = pd.DataFrame(rows)
    pd.set_option("display.width", 200)
    print(df.to_string(index=False))
    print(f"\nmedian of per-chart median error: {df['median_err'].median():.4%}  "
          f"mean recall: {df['recall'].mean():.3f}  series count ok: {df['series_count_ok'].mean():.2f}")


if __name__ == "__main__":
    main()