Commit ·
4d058f6
0
Parent(s):
Publish the Chart Parsing Benchmark (2500 charts)
Browse files- .gitattributes +60 -0
- README.md +127 -0
- benchmark_meta.json +14 -0
- data/test-00000-of-00001.parquet +3 -0
- score.py +741 -0
.gitattributes
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
pretty_name: Chart Parsing Benchmark
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
task_categories:
|
| 7 |
+
- image-to-text
|
| 8 |
+
- image-text-to-text
|
| 9 |
+
tags:
|
| 10 |
+
- chart
|
| 11 |
+
- chart-understanding
|
| 12 |
+
- chart-to-table
|
| 13 |
+
- structured-extraction
|
| 14 |
+
- benchmark
|
| 15 |
+
- leaderboard
|
| 16 |
+
size_categories:
|
| 17 |
+
- 1K<n<10K
|
| 18 |
+
configs:
|
| 19 |
+
- config_name: default
|
| 20 |
+
data_files:
|
| 21 |
+
- split: test
|
| 22 |
+
path: data/test-*
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
# Chart Parsing Benchmark
|
| 26 |
+
|
| 27 |
+
**Chart image in, structured JSON out.** A fixed, test-only benchmark for turning a chart image into its
|
| 28 |
+
title, chart type, data table, encoding, axes, series, legend, and data labels. It holds
|
| 29 |
+
**2500 charts** and is the set behind the [leaderboard](https://huggingface.co/spaces/nutrientdocs/chart-parsing-leaderboard). Every entry sees the same charts and the same
|
| 30 |
+
prompt, and the reference scorer ships in this repository, so any result here can be reproduced.
|
| 31 |
+
|
| 32 |
+
- 🎯 **Model:** [`nutrientdocs/chart-parsing-vlm`](https://huggingface.co/nutrientdocs/chart-parsing-vlm)
|
| 33 |
+
- 🧪 **Try it:** [`nutrientdocs/chart-parsing-demo`](https://huggingface.co/spaces/nutrientdocs/chart-parsing-demo)
|
| 34 |
+
- 🏆 **Leaderboard:** [`nutrientdocs/chart-parsing-leaderboard`](https://huggingface.co/spaces/nutrientdocs/chart-parsing-leaderboard)
|
| 35 |
+
|
| 36 |
+
| chart type | charts |
|
| 37 |
+
| --- | --- |
|
| 38 |
+
| line | 552 |
|
| 39 |
+
| bar | 463 |
|
| 40 |
+
| pie | 249 |
|
| 41 |
+
| scatter | 235 |
|
| 42 |
+
| area | 224 |
|
| 43 |
+
| box | 171 |
|
| 44 |
+
| bubble | 164 |
|
| 45 |
+
| heatmap | 100 |
|
| 46 |
+
| histogram | 54 |
|
| 47 |
+
| treemap | 54 |
|
| 48 |
+
| combo | 51 |
|
| 49 |
+
| funnel | 49 |
|
| 50 |
+
| radar | 46 |
|
| 51 |
+
| violin | 33 |
|
| 52 |
+
| stem | 25 |
|
| 53 |
+
| step | 15 |
|
| 54 |
+
| candlestick | 15 |
|
| 55 |
+
|
| 56 |
+
## Task and prompt
|
| 57 |
+
|
| 58 |
+
Every entry on the leaderboard uses the same system prompt and instruction, shipped with the scorer. The
|
| 59 |
+
model returns one JSON object. The `target` column holds the reference JSON as a string.
|
| 60 |
+
|
| 61 |
+
## Metrics
|
| 62 |
+
|
| 63 |
+
The ranking metric is the **mean per-chart cell F1 at 3% tolerance** (`mean_f1_tol3`): each chart's data cells
|
| 64 |
+
are scored for precision, recall, and F1, and the per-chart F1 is averaged so every chart counts once,
|
| 65 |
+
whatever its table size. Cells are never pooled across charts.
|
| 66 |
+
|
| 67 |
+
A cell matches when its row identity (the first column plus every text column) and its column agree and
|
| 68 |
+
the value is close enough. Row order never matters. Tables with a single value column, or whose rows all
|
| 69 |
+
repeat one value, match on row identity alone. Three tolerance levels are reported side by side:
|
| 70 |
+
|
| 71 |
+
| metric | a value counts as correct when it is |
|
| 72 |
+
|---|---|
|
| 73 |
+
| `mean_f1` | strict: relative 1e-3 |
|
| 74 |
+
| `mean_f1_tol3` | exact (relative 1e-3) when the chart prints data labels, 3% in percentage points for share charts (pie, donut, 100%-stacked, treemap), otherwise 3% of the chart's value range. Histogram bin-edge columns are not scored; histograms are scored on the per-bin frequency |
|
| 75 |
+
| `mean_f1_tol5` | exact (relative 1e-3) when the chart prints data labels, 5% in percentage points for share charts (pie, donut, 100%-stacked, treemap), otherwise 5% of the chart's value range. Histogram bin-edge columns are not scored; histograms are scored on the per-bin frequency |
|
| 76 |
+
|
| 77 |
+
The 3% level is the ranking metric because it matches what a careful reader can recover from the pixels;
|
| 78 |
+
the strict level exposes models that copy printed labels well, and the 5% level shows how much is lost
|
| 79 |
+
to small estimation error. Also reported: table shape match, per-field accuracy (chart type, title, axis
|
| 80 |
+
labels, scales, legend, data labels, column types and roles), and set F1 for `encoding` and `series`.
|
| 81 |
+
|
| 82 |
+
## Scoring
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
python score.py --benchmark-repo nutrientdocs/chart-parsing-benchmark \
|
| 86 |
+
--predictions preds.jsonl --out result.json --name my-model
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
`preds.jsonl` has one `{"id": ..., "text": ...}` line per chart, where `text` is the raw model output.
|
| 90 |
+
The scorer is self-contained and needs only `datasets`. Submit the resulting JSON with the model ID,
|
| 91 |
+
license, and runtime details for review. Entries on the leaderboard carry one of three labels:
|
| 92 |
+
|
| 93 |
+
| label | meaning |
|
| 94 |
+
|---|---|
|
| 95 |
+
| `commercial` | Nutrient model, weights under a commercial Nutrient license |
|
| 96 |
+
| `provider` | cloud model reached through its vendor API |
|
| 97 |
+
| `open` | open-weight model served locally with the benchmark prompt |
|
| 98 |
+
|
| 99 |
+
## Schema
|
| 100 |
+
|
| 101 |
+
```python
|
| 102 |
+
from datasets import load_dataset
|
| 103 |
+
benchmark = load_dataset("nutrientdocs/chart-parsing-benchmark", split="test")
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
| Field | Meaning |
|
| 107 |
+
|---|---|
|
| 108 |
+
| `id` | Stable chart identifier |
|
| 109 |
+
| `image` | RGB chart image |
|
| 110 |
+
| `chart_type`, `title` | Flat copies of target fields for filtering |
|
| 111 |
+
| `category` | Source label from ChartGen |
|
| 112 |
+
| `data_source` | Always `render` in this set |
|
| 113 |
+
| `target` | Reference JSON as a string |
|
| 114 |
+
|
| 115 |
+
## License and attribution
|
| 116 |
+
|
| 117 |
+
Charts derive from [SD122025/ChartGen-200K](https://huggingface.co/datasets/SD122025/ChartGen-200K),
|
| 118 |
+
released under CC BY 4.0. This benchmark keeps the same license. The Nutrient Chart Parsing model
|
| 119 |
+
evaluated on it is commercial; to evaluate or deploy it, [contact Nutrient](https://www.nutrient.io/contact-sales/).
|
| 120 |
+
|
| 121 |
+
## About the author
|
| 122 |
+
|
| 123 |
+
<a href="https://nutrient.io/">
|
| 124 |
+
<img src="https://avatars2.githubusercontent.com/u/1527679?v=3&s=200" height="80" />
|
| 125 |
+
</a>
|
| 126 |
+
|
| 127 |
+
This project is maintained and funded by [Nutrient](https://nutrient.io/) - The deterministic document infrastructure enterprises run their highest-stakes workflows on: replayable output, clear exceptions, and full audit trails on the messy, regulated documents where AI alone breaks.
|
benchmark_meta.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo": "nutrientdocs/chart-parsing-benchmark",
|
| 3 |
+
"version": "v4",
|
| 4 |
+
"content_hash": "78180236fbc904e2ec67acf37805fd06e381476d15791c5335ce1f0dc19102ca",
|
| 5 |
+
"n_charts": 2500,
|
| 6 |
+
"headline": "mean per-chart cell F1 at 3% tolerance",
|
| 7 |
+
"headline_metric": "mean_f1_tol3",
|
| 8 |
+
"value_tolerance": "relative 1e-3",
|
| 9 |
+
"tolerance_levels": {
|
| 10 |
+
"mean_f1": "strict: relative 1e-3",
|
| 11 |
+
"mean_f1_tol3": "exact (relative 1e-3) when the chart prints data labels, 3% in percentage points for share charts (pie, donut, 100%-stacked, treemap), otherwise 3% of the chart's value range. Histogram bin-edge columns are not scored; histograms are scored on the per-bin frequency",
|
| 12 |
+
"mean_f1_tol5": "exact (relative 1e-3) when the chart prints data labels, 5% in percentage points for share charts (pie, donut, 100%-stacked, treemap), otherwise 5% of the chart's value range. Histogram bin-edge columns are not scored; histograms are scored on the per-bin frequency"
|
| 13 |
+
}
|
| 14 |
+
}
|
data/test-00000-of-00001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c876589ca5467552ee99a17177b6fe499058dc252363afde0f1187213cbe759c
|
| 3 |
+
size 85863326
|
score.py
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference scorer for the chart-parsing benchmark.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python score.py --benchmark-repo nutrientdocs/chart-parsing-benchmark --predictions preds.jsonl --out result.json --name my-model
|
| 5 |
+
|
| 6 |
+
`preds.jsonl` holds one JSON object per line: {"id": "<chart id>", "text": "<raw model output>"}.
|
| 7 |
+
The JSON object inside `text` is extracted and scored; anything around it is ignored.
|
| 8 |
+
Only `datasets` is required. Generated from utils/tables.py and training/evaluation.py of the
|
| 9 |
+
chart-parsing-model repository; do not edit by hand.
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
|
| 17 |
+
AXIS_CHANNELS = ("x", "y", "z")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def extract_target(text):
|
| 21 |
+
if isinstance(text, dict):
|
| 22 |
+
return text
|
| 23 |
+
if not text:
|
| 24 |
+
return {}
|
| 25 |
+
depth = 0
|
| 26 |
+
start = -1
|
| 27 |
+
for index, char in enumerate(text):
|
| 28 |
+
if char == "{":
|
| 29 |
+
if depth == 0:
|
| 30 |
+
start = index
|
| 31 |
+
depth += 1
|
| 32 |
+
elif char == "}" and depth > 0:
|
| 33 |
+
depth -= 1
|
| 34 |
+
if depth == 0 and start != -1:
|
| 35 |
+
try:
|
| 36 |
+
return json.loads(text[start:index + 1])
|
| 37 |
+
except json.JSONDecodeError:
|
| 38 |
+
start = -1
|
| 39 |
+
return {}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _column_names(columns):
|
| 43 |
+
return [str(column.get("name")) if isinstance(column, dict) else str(column) for column in columns]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _is_blank(value):
|
| 47 |
+
return value is None or (isinstance(value, str) and value.strip() == "")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _normalize_label(value):
|
| 51 |
+
number = to_number(str(value))
|
| 52 |
+
if number is None:
|
| 53 |
+
return str(value).strip().lower()
|
| 54 |
+
return str(int(number)) if number.is_integer() else repr(number)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _label_column_positions(rows, width):
|
| 58 |
+
positions = {0}
|
| 59 |
+
for index in range(1, width):
|
| 60 |
+
values = [row[index] for row in rows if index < len(row) and not _is_blank(row[index])]
|
| 61 |
+
if values and all(to_number(str(value)) is None for value in values):
|
| 62 |
+
positions.add(index)
|
| 63 |
+
return positions
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
ANY_COLUMN = "*"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _value_positions(rows, width, label_positions):
|
| 70 |
+
positions = []
|
| 71 |
+
for index in range(width):
|
| 72 |
+
if index in label_positions:
|
| 73 |
+
continue
|
| 74 |
+
if any(index < len(row) and not _is_blank(row[index]) for row in rows):
|
| 75 |
+
positions.append(index)
|
| 76 |
+
return positions
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _rows_are_constant(rows, value_positions):
|
| 80 |
+
for row in rows:
|
| 81 |
+
values = {str(row[index]) for index in value_positions if index < len(row) and not _is_blank(row[index])}
|
| 82 |
+
if len(values) > 1:
|
| 83 |
+
return False
|
| 84 |
+
return True
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def data_cells(columns, rows):
|
| 88 |
+
if not isinstance(columns, list) or not isinstance(rows, list):
|
| 89 |
+
return {}
|
| 90 |
+
rows = [row for row in rows if isinstance(row, (list, tuple)) and row]
|
| 91 |
+
if not rows:
|
| 92 |
+
return {}
|
| 93 |
+
names = [name.strip().lower() for name in _column_names(columns)]
|
| 94 |
+
width = max(len(row) for row in rows)
|
| 95 |
+
spatial = any(isinstance(column, dict) and column.get("role") == "z" for column in columns)
|
| 96 |
+
label_positions = _label_column_positions(rows, width)
|
| 97 |
+
if spatial:
|
| 98 |
+
label_positions |= {index for index,column in enumerate(columns) if isinstance(column,dict) and column.get("role") in ("x","y")}
|
| 99 |
+
value_positions = _value_positions(rows, width, label_positions)
|
| 100 |
+
collapse = len(value_positions) == 1 or _rows_are_constant(rows, value_positions)
|
| 101 |
+
cells = {}
|
| 102 |
+
occurrences = {}
|
| 103 |
+
for row in rows:
|
| 104 |
+
identity = tuple(f"{(columns[index].get('role', names[index]) if index < len(columns) and isinstance(columns[index],dict) else f'col{index}')}={_normalize_label(row[index])}" for index in sorted(label_positions) if index < len(row)) if spatial else tuple(sorted(_normalize_label(row[index]) for index in label_positions if index < len(row)))
|
| 105 |
+
occurrence = occurrences.get(identity,0)
|
| 106 |
+
occurrences[identity] = occurrence+1
|
| 107 |
+
if occurrence:
|
| 108 |
+
identity += (("occurrence",occurrence),)
|
| 109 |
+
row_columns = set()
|
| 110 |
+
for index in value_positions:
|
| 111 |
+
if index >= len(row) or _is_blank(row[index]):
|
| 112 |
+
continue
|
| 113 |
+
column = ANY_COLUMN if collapse else (names[index] if index < len(names) else f"col{index}")
|
| 114 |
+
if column in row_columns:
|
| 115 |
+
continue
|
| 116 |
+
row_columns.add(column)
|
| 117 |
+
key = (identity, column)
|
| 118 |
+
cells[key] = str(row[index])
|
| 119 |
+
return cells
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _row_cell_matches(predictions, golds, rel_tol, abs_tol):
|
| 123 |
+
edges = [[index for index,(candidate_column,candidate) in enumerate(predictions) if (column == candidate_column or ANY_COLUMN in (column,candidate_column)) and values_match(candidate,value,rel_tol=rel_tol,abs_tol=abs_tol)] for column,value in golds]
|
| 124 |
+
assigned = {}
|
| 125 |
+
|
| 126 |
+
def match(gold, seen):
|
| 127 |
+
for candidate in edges[gold]:
|
| 128 |
+
if candidate in seen:
|
| 129 |
+
continue
|
| 130 |
+
seen.add(candidate)
|
| 131 |
+
if candidate not in assigned or match(assigned[candidate],seen):
|
| 132 |
+
assigned[candidate] = gold
|
| 133 |
+
return True
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
return sum(match(gold,set()) for gold in range(len(edges)))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _maximum_row_matches(weights):
|
| 140 |
+
if not weights or not weights[0]:
|
| 141 |
+
return 0
|
| 142 |
+
width = max(len(weights),len(weights[0]))
|
| 143 |
+
costs = [[-weights[row][column] if row < len(weights) and column < len(weights[row]) else 0 for column in range(width)] for row in range(width)]
|
| 144 |
+
row_potential,column_potential,assigned,previous = [[0]*(width+1) for _ in range(4)]
|
| 145 |
+
for row in range(1,width+1):
|
| 146 |
+
assigned[0] = row
|
| 147 |
+
column = 0
|
| 148 |
+
distances,used = [float('inf')]*(width+1),[False]*(width+1)
|
| 149 |
+
while True:
|
| 150 |
+
used[column] = True
|
| 151 |
+
current_row = assigned[column]
|
| 152 |
+
delta,next_column = float('inf'),0
|
| 153 |
+
for candidate in range(1,width+1):
|
| 154 |
+
if used[candidate]:
|
| 155 |
+
continue
|
| 156 |
+
cost = costs[current_row-1][candidate-1]-row_potential[current_row]-column_potential[candidate]
|
| 157 |
+
if cost < distances[candidate]:
|
| 158 |
+
distances[candidate],previous[candidate] = cost,column
|
| 159 |
+
if distances[candidate] < delta:
|
| 160 |
+
delta,next_column = distances[candidate],candidate
|
| 161 |
+
for candidate in range(width+1):
|
| 162 |
+
if used[candidate]:
|
| 163 |
+
row_potential[assigned[candidate]] += delta
|
| 164 |
+
column_potential[candidate] -= delta
|
| 165 |
+
else:
|
| 166 |
+
distances[candidate] -= delta
|
| 167 |
+
column = next_column
|
| 168 |
+
if assigned[column] == 0:
|
| 169 |
+
break
|
| 170 |
+
while column:
|
| 171 |
+
prior = previous[column]
|
| 172 |
+
assigned[column] = assigned[prior]
|
| 173 |
+
column = prior
|
| 174 |
+
return -sum(costs[assigned[column]-1][column-1] for column in range(1,width+1))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def count_matches(pred_cells, gold_cells, rel_tol=1e-3, abs_tol=1e-6):
|
| 178 |
+
def groups(cells):
|
| 179 |
+
grouped = {}
|
| 180 |
+
for (identity,column),value in cells.items():
|
| 181 |
+
base = tuple(part for part in identity if not isinstance(part,tuple))
|
| 182 |
+
grouped.setdefault(base,{}).setdefault(identity,[]).append((column,value))
|
| 183 |
+
return grouped
|
| 184 |
+
|
| 185 |
+
predictions,golds = groups(pred_cells),groups(gold_cells)
|
| 186 |
+
total = 0
|
| 187 |
+
for identity,rows in golds.items():
|
| 188 |
+
candidates = list(predictions.get(identity,{}).values())
|
| 189 |
+
weights = [[_row_cell_matches(candidate,row,rel_tol,abs_tol) for candidate in candidates] for row in rows.values()]
|
| 190 |
+
total += _maximum_row_matches(weights)
|
| 191 |
+
return total
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def to_number(text):
|
| 195 |
+
cleaned = text.strip().replace(",", "").replace("\u2212", "-").rstrip("%").strip()
|
| 196 |
+
try:
|
| 197 |
+
return float(cleaned)
|
| 198 |
+
except ValueError:
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def values_match(a, b, rel_tol=1e-3, abs_tol=1e-6):
|
| 203 |
+
left, right = to_number(a), to_number(b)
|
| 204 |
+
if left is not None and right is not None:
|
| 205 |
+
return math.isclose(left, right, rel_tol=rel_tol, abs_tol=abs_tol)
|
| 206 |
+
return a.strip().lower() == b.strip().lower()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
import json
|
| 211 |
+
import time
|
| 212 |
+
from collections import defaultdict
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
STRICT_TOLERANCE = (1e-3, 1e-6)
|
| 216 |
+
TOLERANCE_LEVELS = {"tol3": 0.03, "tol5": 0.05}
|
| 217 |
+
SHARE_POINTS_SCALE = 100.0
|
| 218 |
+
SHARE_CHART_TYPES = {"treemap"}
|
| 219 |
+
HISTOGRAM_EDGE_TOKENS = ("start", "end")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _norm(value):
|
| 223 |
+
return value.strip().lower() if isinstance(value, str) else value
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _present(value):
|
| 227 |
+
if value is None:
|
| 228 |
+
return False
|
| 229 |
+
if isinstance(value, str):
|
| 230 |
+
return value.strip() != ""
|
| 231 |
+
return True
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _to_float(value):
|
| 235 |
+
try:
|
| 236 |
+
return float(value)
|
| 237 |
+
except (TypeError, ValueError):
|
| 238 |
+
return None
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _exact_eq(pred, gold):
|
| 242 |
+
return pred == gold
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _text_eq(pred, gold):
|
| 246 |
+
return _norm(pred) == _norm(gold)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _num_eq(pred, gold):
|
| 250 |
+
left, right = _to_float(pred), _to_float(gold)
|
| 251 |
+
return left is not None and values_match(str(left), str(right))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _mapping(target, key):
|
| 255 |
+
value = target.get(key) if isinstance(target, dict) else None
|
| 256 |
+
return value if isinstance(value, dict) else {}
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _axis(target, channel):
|
| 260 |
+
axis = _mapping(target, "axes").get(channel)
|
| 261 |
+
return axis if isinstance(axis, dict) else {}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _value_representation(target, key):
|
| 265 |
+
return _mapping(target, "valueRepresentation").get(key)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
SCALAR_FIELDS = (
|
| 269 |
+
("type", lambda t: t.get("chartType"), _exact_eq),
|
| 270 |
+
("title", lambda t: t.get("title"), _text_eq),
|
| 271 |
+
("value_mode", lambda t: _value_representation(t, "mode"), _exact_eq),
|
| 272 |
+
("value_format", lambda t: _value_representation(t, "format"), _text_eq),
|
| 273 |
+
("x_label", lambda t: _axis(t, "x").get("label"), _text_eq),
|
| 274 |
+
("y_label", lambda t: _axis(t, "y").get("label"), _text_eq),
|
| 275 |
+
("z_label", lambda t: _axis(t, "z").get("label"), _text_eq),
|
| 276 |
+
("x_scale", lambda t: _axis(t, "x").get("scale"), _exact_eq),
|
| 277 |
+
("y_scale", lambda t: _axis(t, "y").get("scale"), _exact_eq),
|
| 278 |
+
("z_scale", lambda t: _axis(t, "z").get("scale"), _exact_eq),
|
| 279 |
+
("legend_visible", lambda t: _mapping(t, "legend").get("visible"), _exact_eq),
|
| 280 |
+
("datalabels_visible", lambda t: _mapping(t, "dataLabels").get("visible"), _exact_eq),
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _scalar_observe(getter, eq):
|
| 285 |
+
def observe(pred, gold):
|
| 286 |
+
gold_value, pred_value = getter(gold), getter(pred)
|
| 287 |
+
gold_present, pred_present = _present(gold_value), _present(pred_value)
|
| 288 |
+
correct = gold_present and pred_present and eq(pred_value, gold_value)
|
| 289 |
+
return [(gold_present, pred_present, correct)]
|
| 290 |
+
|
| 291 |
+
return observe
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _axis_names(pred, gold):
|
| 295 |
+
return set(AXIS_CHANNELS) | set(_mapping(pred, "axes")) | set(_mapping(gold, "axes"))
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _observe_secondary_axis(attr, eq):
|
| 299 |
+
def observe(pred, gold):
|
| 300 |
+
observations = []
|
| 301 |
+
for channel in sorted(_axis_names(pred,gold) - set(AXIS_CHANNELS)):
|
| 302 |
+
gold_value,pred_value = _axis(gold,channel).get(attr),_axis(pred,channel).get(attr)
|
| 303 |
+
gold_present,pred_present = _present(gold_value),_present(pred_value)
|
| 304 |
+
observations.append((gold_present,pred_present,gold_present and pred_present and eq(pred_value,gold_value)))
|
| 305 |
+
return observations
|
| 306 |
+
|
| 307 |
+
return observe
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _observe_axis_bounds(pred, gold):
|
| 311 |
+
observations = []
|
| 312 |
+
for channel in sorted(_axis_names(pred,gold)):
|
| 313 |
+
gold_axis, pred_axis = _axis(gold, channel), _axis(pred, channel)
|
| 314 |
+
for key in ("min", "max"):
|
| 315 |
+
gold_value, pred_value = gold_axis.get(key), pred_axis.get(key)
|
| 316 |
+
gold_present, pred_present = gold_value is not None, pred_value is not None
|
| 317 |
+
correct = gold_present and pred_present and _num_eq(pred_value, gold_value)
|
| 318 |
+
observations.append((gold_present, pred_present, correct))
|
| 319 |
+
return observations
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _row_width(row):
|
| 323 |
+
return len(row) if isinstance(row, (list, tuple)) else -1
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _columns_by_name(target):
|
| 327 |
+
data = _data(target)
|
| 328 |
+
source = data.get("columns")
|
| 329 |
+
columns = {}
|
| 330 |
+
for column in source if isinstance(source, list) else []:
|
| 331 |
+
if isinstance(column, dict) and column.get("name") is not None:
|
| 332 |
+
columns[_norm(column["name"])] = column
|
| 333 |
+
return columns
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _observe_column_attr(attr, eq):
|
| 337 |
+
def observe(pred, gold):
|
| 338 |
+
gold_columns, pred_columns = _columns_by_name(gold), _columns_by_name(pred)
|
| 339 |
+
observations = []
|
| 340 |
+
for name, gold_column in gold_columns.items():
|
| 341 |
+
gold_value = gold_column.get(attr)
|
| 342 |
+
pred_column = pred_columns.get(name)
|
| 343 |
+
pred_value = pred_column.get(attr) if pred_column else None
|
| 344 |
+
gold_present, pred_present = _present(gold_value), _present(pred_value)
|
| 345 |
+
correct = gold_present and pred_present and eq(pred_value, gold_value)
|
| 346 |
+
observations.append((gold_present, pred_present, correct))
|
| 347 |
+
return observations
|
| 348 |
+
|
| 349 |
+
return observe
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
OBSERVATION_FIELDS = (
|
| 353 |
+
tuple((key, _scalar_observe(getter, eq)) for key, getter, eq in SCALAR_FIELDS)
|
| 354 |
+
+ (
|
| 355 |
+
("axis_bound", _observe_axis_bounds),
|
| 356 |
+
("secondary_axis_label", _observe_secondary_axis("label", _text_eq)),
|
| 357 |
+
("secondary_axis_scale", _observe_secondary_axis("scale", _exact_eq)),
|
| 358 |
+
("column_type", _observe_column_attr("type", _exact_eq)),
|
| 359 |
+
("column_role", _observe_column_attr("role", _exact_eq)),
|
| 360 |
+
("column_unit", _observe_column_attr("unit", _text_eq)),
|
| 361 |
+
)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _key(value):
|
| 366 |
+
if isinstance(value, str):
|
| 367 |
+
return _norm(value)
|
| 368 |
+
if value is None or isinstance(value, (int, float, bool)):
|
| 369 |
+
return value
|
| 370 |
+
return str(value)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _encoding_pairs(target):
|
| 374 |
+
encoding = target.get("encoding")
|
| 375 |
+
if not isinstance(encoding, dict):
|
| 376 |
+
return set()
|
| 377 |
+
return {(str(channel), _key(field)) for channel, field in encoding.items() if _present(field)}
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _series_pairs(target):
|
| 381 |
+
series = target.get("series")
|
| 382 |
+
if not isinstance(series, list):
|
| 383 |
+
return set()
|
| 384 |
+
pairs = set()
|
| 385 |
+
for entry in series:
|
| 386 |
+
if isinstance(entry, dict):
|
| 387 |
+
pairs.add((_key(entry.get("name")), _key(entry.get("field"))))
|
| 388 |
+
return pairs
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _series_axis_pairs(target):
|
| 392 |
+
series = target.get("series") if isinstance(target, dict) else None
|
| 393 |
+
if not isinstance(series, list):
|
| 394 |
+
return set()
|
| 395 |
+
return {(_key(entry.get('field')), _key(entry['axis'])) for entry in series if isinstance(entry, dict) and entry.get('axis')}
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
SET_FIELDS = (
|
| 399 |
+
("encoding", _encoding_pairs),
|
| 400 |
+
("series", _series_pairs),
|
| 401 |
+
("series_axis", _series_axis_pairs),
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _data(target):
|
| 406 |
+
data = target.get("data") if isinstance(target, dict) else None
|
| 407 |
+
return data if isinstance(data, dict) else {"columns": [], "rows": []}
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _value_range(gold):
|
| 411 |
+
data = _data(gold)
|
| 412 |
+
columns = data.get("columns", [])
|
| 413 |
+
spatial = any(isinstance(column,dict) and column.get("role") == "z" for column in columns)
|
| 414 |
+
positions = [index for index,column in enumerate(columns) if isinstance(column,dict) and column.get("role") in ("z","value")] if spatial else list(range(1,len(columns)))
|
| 415 |
+
values = [to_number(str(row[index])) for row in data.get("rows", []) if isinstance(row, (list, tuple)) for index in positions if index < len(row)]
|
| 416 |
+
values = [value for value in values if value is not None]
|
| 417 |
+
if not values:
|
| 418 |
+
return 1.0
|
| 419 |
+
return (max(values) - min(values)) or max(abs(value) for value in values) or 1.0
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _stores_shares(gold):
|
| 423 |
+
return _value_representation(gold, "mode") == "percentage_of_total" or gold.get("chartType") in SHARE_CHART_TYPES
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def chart_tolerance(gold, fraction):
|
| 427 |
+
if fraction is None or (gold.get("dataLabels") or {}).get("visible"):
|
| 428 |
+
return STRICT_TOLERANCE
|
| 429 |
+
if _stores_shares(gold):
|
| 430 |
+
return (0.0, fraction * SHARE_POINTS_SCALE)
|
| 431 |
+
return (0.0, fraction * _value_range(gold))
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _drop_histogram_edges(data):
|
| 435 |
+
columns, rows = data.get("columns"), data.get("rows")
|
| 436 |
+
if not isinstance(columns, list) or not isinstance(rows, list):
|
| 437 |
+
return data
|
| 438 |
+
keep = [i for i, column in enumerate(columns)
|
| 439 |
+
if not (isinstance(column, dict) and any(token in str(column.get("name", "")).lower() for token in HISTOGRAM_EDGE_TOKENS))]
|
| 440 |
+
if len(keep) == len(columns):
|
| 441 |
+
return data
|
| 442 |
+
trimmed_rows = [[row[i] for i in keep if i < len(row)] for row in rows if isinstance(row, (list, tuple))]
|
| 443 |
+
return {**data, "columns": [columns[i] for i in keep], "rows": trimmed_rows}
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def score_sample(pred, gold):
|
| 447 |
+
pred_data, gold_data = _data(pred), _data(gold)
|
| 448 |
+
if gold.get("chartType") == "histogram":
|
| 449 |
+
pred_data, gold_data = _drop_histogram_edges(pred_data), _drop_histogram_edges(gold_data)
|
| 450 |
+
pred_cells = data_cells(pred_data.get("columns", []), pred_data.get("rows", []))
|
| 451 |
+
gold_cells = data_cells(gold_data.get("columns", []), gold_data.get("rows", []))
|
| 452 |
+
tp = count_matches(pred_cells, gold_cells)
|
| 453 |
+
tp_at = {
|
| 454 |
+
level: count_matches(pred_cells, gold_cells, *chart_tolerance(gold, fraction))
|
| 455 |
+
for level, fraction in TOLERANCE_LEVELS.items()
|
| 456 |
+
}
|
| 457 |
+
gold_rows = gold_data.get("rows") if isinstance(gold_data.get("rows"), list) else []
|
| 458 |
+
pred_rows = pred_data.get("rows") if isinstance(pred_data.get("rows"), list) else []
|
| 459 |
+
shape_match = float(
|
| 460 |
+
len(pred_rows) == len(gold_rows)
|
| 461 |
+
and [_row_width(r) for r in pred_rows] == [_row_width(r) for r in gold_rows]
|
| 462 |
+
)
|
| 463 |
+
fields = {key: observe(pred, gold) for key, observe in OBSERVATION_FIELDS}
|
| 464 |
+
sets = {}
|
| 465 |
+
for key, pairs in SET_FIELDS:
|
| 466 |
+
gold_pairs, pred_pairs = pairs(gold), pairs(pred)
|
| 467 |
+
matched = len(gold_pairs & pred_pairs)
|
| 468 |
+
sets[key] = (matched, len(pred_pairs) - matched, len(gold_pairs) - matched)
|
| 469 |
+
return {
|
| 470 |
+
"tp": tp,
|
| 471 |
+
"fp": len(pred_cells) - tp,
|
| 472 |
+
"fn": len(gold_cells) - tp,
|
| 473 |
+
"tp_at": tp_at,
|
| 474 |
+
"shape_match": shape_match,
|
| 475 |
+
"chart_type": gold.get("chartType", "unknown"),
|
| 476 |
+
"fields": fields,
|
| 477 |
+
"sets": sets,
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def precision_recall_f1(tp, fp, fn):
|
| 482 |
+
precision = tp / (tp + fp) if (tp + fp) else 0.0
|
| 483 |
+
recall = tp / (tp + fn) if (tp + fn) else 0.0
|
| 484 |
+
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
|
| 485 |
+
return precision, recall, f1
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def chart_f1(row, level="strict"):
|
| 489 |
+
tp = row["tp"] if level == "strict" else row["tp_at"][level]
|
| 490 |
+
n_pred, n_gold = row["tp"] + row["fp"], row["tp"] + row["fn"]
|
| 491 |
+
return precision_recall_f1(tp, n_pred - tp, n_gold - tp)[2]
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def mean_chart_f1(rows, level="strict"):
|
| 495 |
+
return sum(chart_f1(row, level) for row in rows) / len(rows) if rows else 0.0
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def tolerant_means(rows, key="mean_chart_f1"):
|
| 499 |
+
return {f"{key}_{level}": mean_chart_f1(rows, level) for level in TOLERANCE_LEVELS}
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def aggregate_fields(rows):
|
| 503 |
+
stats = {}
|
| 504 |
+
for key, _ in OBSERVATION_FIELDS:
|
| 505 |
+
acc_n = correct = halluc_n = halluc_hits = 0
|
| 506 |
+
for row in rows:
|
| 507 |
+
for gold_present, pred_present, is_correct in row["fields"][key]:
|
| 508 |
+
if gold_present:
|
| 509 |
+
acc_n += 1
|
| 510 |
+
correct += int(is_correct)
|
| 511 |
+
else:
|
| 512 |
+
halluc_n += 1
|
| 513 |
+
halluc_hits += int(pred_present)
|
| 514 |
+
stats[key] = {
|
| 515 |
+
"acc": correct / acc_n if acc_n else 0.0,
|
| 516 |
+
"acc_n": acc_n,
|
| 517 |
+
"halluc": halluc_hits / halluc_n if halluc_n else None,
|
| 518 |
+
"halluc_n": halluc_n,
|
| 519 |
+
}
|
| 520 |
+
return stats
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def aggregate_sets(rows):
|
| 524 |
+
stats = {}
|
| 525 |
+
for key, _ in SET_FIELDS:
|
| 526 |
+
tp = sum(row["sets"][key][0] for row in rows)
|
| 527 |
+
fp = sum(row["sets"][key][1] for row in rows)
|
| 528 |
+
fn = sum(row["sets"][key][2] for row in rows)
|
| 529 |
+
precision, recall, f1 = precision_recall_f1(tp, fp, fn)
|
| 530 |
+
stats[key] = {"precision": precision, "recall": recall, "f1": f1, "tp": tp, "fp": fp, "fn": fn}
|
| 531 |
+
return stats
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def evaluate(dataset, predict, show=0):
|
| 535 |
+
rows = []
|
| 536 |
+
for i in range(len(dataset)):
|
| 537 |
+
example = dataset[i]
|
| 538 |
+
pred = extract_target(predict(example))
|
| 539 |
+
gold = json.loads(example["target"]) if isinstance(example["target"], str) else example["target"]
|
| 540 |
+
row = score_sample(pred, gold)
|
| 541 |
+
rows.append(row)
|
| 542 |
+
if i < show:
|
| 543 |
+
print("=" * 80)
|
| 544 |
+
print("id:", example.get("id"), "|", row["chart_type"], "|",
|
| 545 |
+
{k: row[k] for k in ("tp", "fp", "fn", "shape_match")})
|
| 546 |
+
print("--- predicted ---")
|
| 547 |
+
print(json.dumps(pred)[:600])
|
| 548 |
+
print("--- ground truth ---")
|
| 549 |
+
print(json.dumps(gold)[:600])
|
| 550 |
+
shape_match = sum(r["shape_match"] for r in rows) / len(rows) if rows else 0.0
|
| 551 |
+
return {
|
| 552 |
+
"mean_chart_f1": mean_chart_f1(rows),
|
| 553 |
+
**tolerant_means(rows),
|
| 554 |
+
"shape_match": shape_match,
|
| 555 |
+
"fields": aggregate_fields(rows),
|
| 556 |
+
"sets": aggregate_sets(rows),
|
| 557 |
+
"rows": rows,
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def scoring_view(dataset):
|
| 562 |
+
if hasattr(dataset, "remove_columns") and hasattr(dataset, "column_names"):
|
| 563 |
+
return dataset.remove_columns([column for column in dataset.column_names if column not in ("id", "target")])
|
| 564 |
+
return dataset
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def _target_lengths(dataset):
|
| 568 |
+
if hasattr(dataset, "select_columns"):
|
| 569 |
+
return [len(target) for target in dataset.select_columns(["target"])["target"]]
|
| 570 |
+
return [len(example["target"]) for example in dataset]
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def evaluate_batched(dataset, predict_batch, batch_size, show=0, log=print):
|
| 574 |
+
lengths = _target_lengths(dataset)
|
| 575 |
+
order = sorted(range(len(dataset)), key=lambda index: lengths[index])
|
| 576 |
+
predictions = {}
|
| 577 |
+
started = time.monotonic()
|
| 578 |
+
for start in range(0, len(order), batch_size):
|
| 579 |
+
batch = [dataset[index] for index in order[start:start + batch_size]]
|
| 580 |
+
for example, text in zip(batch, predict_batch(batch)):
|
| 581 |
+
predictions[example["id"]] = text
|
| 582 |
+
done = start + len(batch)
|
| 583 |
+
elapsed = time.monotonic() - started
|
| 584 |
+
log(f"eval {done}/{len(order)} charts | {elapsed:.0f}s | {60 * done / max(elapsed, 1e-9):.1f} charts/min")
|
| 585 |
+
return evaluate(scoring_view(dataset), lambda example: predictions[example["id"]], show=show)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def aggregate_by_chart_type(rows):
|
| 589 |
+
groups = defaultdict(list)
|
| 590 |
+
for row in rows:
|
| 591 |
+
groups[row["chart_type"]].append(row)
|
| 592 |
+
per_type = []
|
| 593 |
+
for chart_type, group in sorted(groups.items(), key=lambda kv: -len(kv[1])):
|
| 594 |
+
shape_match = sum(r["shape_match"] for r in group) / len(group)
|
| 595 |
+
per_type.append(
|
| 596 |
+
{
|
| 597 |
+
"chart_type": chart_type,
|
| 598 |
+
"n": len(group),
|
| 599 |
+
"mean_chart_f1": mean_chart_f1(group),
|
| 600 |
+
**tolerant_means(group),
|
| 601 |
+
"shape_match": shape_match,
|
| 602 |
+
"fields": aggregate_fields(group),
|
| 603 |
+
"sets": aggregate_sets(group),
|
| 604 |
+
}
|
| 605 |
+
)
|
| 606 |
+
return per_type
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def macro_metrics(per_type):
|
| 610 |
+
if not per_type:
|
| 611 |
+
return {"macro_mean_chart_f1": 0.0}
|
| 612 |
+
return {"macro_mean_chart_f1": sum(t["mean_chart_f1"] for t in per_type) / len(per_type)}
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def _flatten_fields(prefix, metrics):
|
| 616 |
+
flat = {}
|
| 617 |
+
for key, stat in metrics["fields"].items():
|
| 618 |
+
flat[f"{prefix}/{key}_acc"] = stat["acc"]
|
| 619 |
+
if stat["halluc"] is not None:
|
| 620 |
+
flat[f"{prefix}/{key}_halluc"] = stat["halluc"]
|
| 621 |
+
for key, stat in metrics["sets"].items():
|
| 622 |
+
flat[f"{prefix}/{key}_precision"] = stat["precision"]
|
| 623 |
+
flat[f"{prefix}/{key}_recall"] = stat["recall"]
|
| 624 |
+
flat[f"{prefix}/{key}_f1"] = stat["f1"]
|
| 625 |
+
return flat
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def scored_metrics(test_metrics, train_metrics, eval_prefix="test"):
|
| 629 |
+
test_macro = macro_metrics(aggregate_by_chart_type(test_metrics["rows"]))
|
| 630 |
+
train_macro = macro_metrics(aggregate_by_chart_type(train_metrics["rows"]))
|
| 631 |
+
scored = {
|
| 632 |
+
f"{eval_prefix}/mean_chart_f1": test_metrics["mean_chart_f1"],
|
| 633 |
+
f"{eval_prefix}/shape_match": test_metrics["shape_match"],
|
| 634 |
+
f"{eval_prefix}/macro_mean_chart_f1": test_macro["macro_mean_chart_f1"],
|
| 635 |
+
"train/mean_chart_f1": train_metrics["mean_chart_f1"],
|
| 636 |
+
"train/shape_match": train_metrics["shape_match"],
|
| 637 |
+
"train/macro_mean_chart_f1": train_macro["macro_mean_chart_f1"],
|
| 638 |
+
"overfitting/mean_chart_f1_gap": train_metrics["mean_chart_f1"] - test_metrics["mean_chart_f1"],
|
| 639 |
+
}
|
| 640 |
+
scored.update(_flatten_fields(eval_prefix, test_metrics))
|
| 641 |
+
scored.update(_flatten_fields("train", train_metrics))
|
| 642 |
+
return scored
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def summary_row(name, metrics):
|
| 647 |
+
fields, sets = metrics["fields"], metrics["sets"]
|
| 648 |
+
return {
|
| 649 |
+
"model": name,
|
| 650 |
+
"n": len(metrics["rows"]),
|
| 651 |
+
"mean_f1": metrics["mean_chart_f1"],
|
| 652 |
+
"mean_f1_tol3": metrics["mean_chart_f1_tol3"],
|
| 653 |
+
"mean_f1_tol5": metrics["mean_chart_f1_tol5"],
|
| 654 |
+
"shape": metrics["shape_match"],
|
| 655 |
+
"type_acc": fields["type"]["acc"],
|
| 656 |
+
"title_acc": fields["title"]["acc"],
|
| 657 |
+
"encoding_f1": sets["encoding"]["f1"],
|
| 658 |
+
"series_f1": sets["series"]["f1"],
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
import hashlib
|
| 662 |
+
import io
|
| 663 |
+
from PIL import Image
|
| 664 |
+
MAX_IMAGE_PIXELS = 602112
|
| 665 |
+
BENCHMARK_PROMPT = "Extract a chart image's structure and data as JSON. Return ONLY a JSON object with keys: title, chartType, data, valueRepresentation, encoding, axes, series, legend, dataLabels.\nchartType: bar, line, area, pie, scatter, bubble, histogram, box, violin, heatmap, treemap, funnel, radar, candlestick, step, stem, combo. title: text or null.\ndata: {columns:[{name, type(categorical|numeric|temporal), role(category|value|series|x|y|z|size|color), unit}], rows:[[...]]}.\nvalueRepresentation:{mode(absolute|percentage_of_total), format('0.0%','integer', null)}. encoding: column per used channel of x, y, y2, z, z2, color, size, category, value.\naxes:{x:{label, unit, scale(categorical|linear|logarithmic|temporal), min, max}, y:{...}, z:{...} for 3D, x2/y2:{...} for extra axes} or null for pie/sunburst/treemap/funnel/radar/rose; min/max are visible limits. series:[{name, field, axis?}]. legend:{visible, position, entries}. dataLabels:{visible, format}.\nUse visible data; null where unsupported. Pie, donut, treemap, and 100%-stacked charts use 'percentage_of_total'; others use 'absolute'. Keep visible limits and repeated observations. Floating bars use Start and End columns. 3D: keep x/y/z; floating bars encode upper/lower endpoints as z/z2 or y/y2.\nExtract this chart's structured data."
|
| 666 |
+
SCORER_HASH = '1782c0b90274e10082385f219e7fbc73e7e7bb2dc4eec02b59480519f72c52de'
|
| 667 |
+
def digest(value):
|
| 668 |
+
return hashlib.sha256(value).hexdigest()
|
| 669 |
+
|
| 670 |
+
def canonical_hash(value):
|
| 671 |
+
return digest(json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(',', ':')).encode())
|
| 672 |
+
|
| 673 |
+
def image_hash(image):
|
| 674 |
+
if isinstance(image, dict):
|
| 675 |
+
image = Image.open(io.BytesIO(image['bytes'])) if image.get('bytes') else Image.open(image['path'])
|
| 676 |
+
elif isinstance(image, bytes):
|
| 677 |
+
image = Image.open(io.BytesIO(image))
|
| 678 |
+
rgb = image.convert('RGB')
|
| 679 |
+
return digest(str(rgb.size).encode() + rgb.tobytes())
|
| 680 |
+
|
| 681 |
+
def input_hash(image, prompt):
|
| 682 |
+
return canonical_hash({'image': image_hash(image), 'max_pixels': MAX_IMAGE_PIXELS, 'prompt': prompt})
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _load_predictions(path):
|
| 687 |
+
predictions = {}
|
| 688 |
+
with open(path, encoding="utf-8") as handle:
|
| 689 |
+
for line in handle:
|
| 690 |
+
if line.strip():
|
| 691 |
+
record = json.loads(line)
|
| 692 |
+
predictions[record["id"]] = record
|
| 693 |
+
return predictions
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def main():
|
| 697 |
+
parser = argparse.ArgumentParser(description="Score chart-parsing predictions against the frozen benchmark.")
|
| 698 |
+
parser.add_argument("--benchmark-repo", default="nutrientdocs/chart-parsing-benchmark")
|
| 699 |
+
parser.add_argument("--predictions", required=True, help="JSONL of {id, text, input_hash} records")
|
| 700 |
+
parser.add_argument("--revision", default=None)
|
| 701 |
+
parser.add_argument("--out", required=True)
|
| 702 |
+
parser.add_argument("--name", required=True, help="entry name shown on the leaderboard")
|
| 703 |
+
parser.add_argument("--token", default=None)
|
| 704 |
+
args = parser.parse_args()
|
| 705 |
+
|
| 706 |
+
from datasets import load_dataset
|
| 707 |
+
|
| 708 |
+
from huggingface_hub import hf_hub_download
|
| 709 |
+
|
| 710 |
+
benchmark = load_dataset(args.benchmark_repo, revision=args.revision, split="test", token=args.token)
|
| 711 |
+
meta_path = hf_hub_download(args.benchmark_repo, "benchmark_meta.json", repo_type="dataset", revision=args.revision, token=args.token)
|
| 712 |
+
with open(meta_path) as handle:
|
| 713 |
+
meta = json.load(handle)
|
| 714 |
+
predictions = _load_predictions(args.predictions)
|
| 715 |
+
for example in benchmark:
|
| 716 |
+
prediction = predictions.get(example["id"])
|
| 717 |
+
if prediction is not None and prediction.get("input_hash") != input_hash(example["image"], BENCHMARK_PROMPT):
|
| 718 |
+
raise ValueError(f"Prediction input differs for {example['id']}; generate it again")
|
| 719 |
+
missing = [identifier for identifier in benchmark["id"] if identifier not in predictions]
|
| 720 |
+
metrics = evaluate(benchmark, lambda example: predictions.get(example["id"], {}).get("text", ""))
|
| 721 |
+
result = {
|
| 722 |
+
"summary": summary_row(args.name, metrics),
|
| 723 |
+
"per_chart_type": aggregate_by_chart_type(metrics["rows"]),
|
| 724 |
+
"fields": metrics["fields"],
|
| 725 |
+
"sets": metrics["sets"],
|
| 726 |
+
"missing_predictions": len(missing),
|
| 727 |
+
"benchmark_version": meta["version"],
|
| 728 |
+
"benchmark_content_hash": meta.get("content_hash"),
|
| 729 |
+
"scorer_hash": SCORER_HASH,
|
| 730 |
+
}
|
| 731 |
+
with open(args.out, "w", encoding="utf-8") as handle:
|
| 732 |
+
json.dump(result, handle, indent=2)
|
| 733 |
+
row = result["summary"]
|
| 734 |
+
print(
|
| 735 |
+
f"{args.name}: mean_f1 {row['mean_f1']:.3f} | tol3 {row['mean_f1_tol3']:.3f} "
|
| 736 |
+
f"| tol5 {row['mean_f1_tol5']:.3f} | shape {row['shape']:.3f} | missing {len(missing)}"
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
if __name__ == "__main__":
|
| 741 |
+
main()
|