File size: 29,473 Bytes
4d058f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
"""Reference scorer for the chart-parsing benchmark.

Usage:
    python score.py --benchmark-repo nutrientdocs/chart-parsing-benchmark --predictions preds.jsonl --out result.json --name my-model

`preds.jsonl` holds one JSON object per line: {"id": "<chart id>", "text": "<raw model output>"}.
The JSON object inside `text` is extracted and scored; anything around it is ignored.
Only `datasets` is required. Generated from utils/tables.py and training/evaluation.py of the
chart-parsing-model repository; do not edit by hand.
"""
import argparse


import json
import math

AXIS_CHANNELS = ("x", "y", "z")


def extract_target(text):
    if isinstance(text, dict):
        return text
    if not text:
        return {}
    depth = 0
    start = -1
    for index, char in enumerate(text):
        if char == "{":
            if depth == 0:
                start = index
            depth += 1
        elif char == "}" and depth > 0:
            depth -= 1
            if depth == 0 and start != -1:
                try:
                    return json.loads(text[start:index + 1])
                except json.JSONDecodeError:
                    start = -1
    return {}


def _column_names(columns):
    return [str(column.get("name")) if isinstance(column, dict) else str(column) for column in columns]


def _is_blank(value):
    return value is None or (isinstance(value, str) and value.strip() == "")


def _normalize_label(value):
    number = to_number(str(value))
    if number is None:
        return str(value).strip().lower()
    return str(int(number)) if number.is_integer() else repr(number)


def _label_column_positions(rows, width):
    positions = {0}
    for index in range(1, width):
        values = [row[index] for row in rows if index < len(row) and not _is_blank(row[index])]
        if values and all(to_number(str(value)) is None for value in values):
            positions.add(index)
    return positions


ANY_COLUMN = "*"


def _value_positions(rows, width, label_positions):
    positions = []
    for index in range(width):
        if index in label_positions:
            continue
        if any(index < len(row) and not _is_blank(row[index]) for row in rows):
            positions.append(index)
    return positions


def _rows_are_constant(rows, value_positions):
    for row in rows:
        values = {str(row[index]) for index in value_positions if index < len(row) and not _is_blank(row[index])}
        if len(values) > 1:
            return False
    return True


def data_cells(columns, rows):
    if not isinstance(columns, list) or not isinstance(rows, list):
        return {}
    rows = [row for row in rows if isinstance(row, (list, tuple)) and row]
    if not rows:
        return {}
    names = [name.strip().lower() for name in _column_names(columns)]
    width = max(len(row) for row in rows)
    spatial = any(isinstance(column, dict) and column.get("role") == "z" for column in columns)
    label_positions = _label_column_positions(rows, width)
    if spatial:
        label_positions |= {index for index,column in enumerate(columns) if isinstance(column,dict) and column.get("role") in ("x","y")}
    value_positions = _value_positions(rows, width, label_positions)
    collapse = len(value_positions) == 1 or _rows_are_constant(rows, value_positions)
    cells = {}
    occurrences = {}
    for row in rows:
        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)))
        occurrence = occurrences.get(identity,0)
        occurrences[identity] = occurrence+1
        if occurrence:
            identity += (("occurrence",occurrence),)
        row_columns = set()
        for index in value_positions:
            if index >= len(row) or _is_blank(row[index]):
                continue
            column = ANY_COLUMN if collapse else (names[index] if index < len(names) else f"col{index}")
            if column in row_columns:
                continue
            row_columns.add(column)
            key = (identity, column)
            cells[key] = str(row[index])
    return cells


def _row_cell_matches(predictions, golds, rel_tol, abs_tol):
    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]
    assigned = {}

    def match(gold, seen):
        for candidate in edges[gold]:
            if candidate in seen:
                continue
            seen.add(candidate)
            if candidate not in assigned or match(assigned[candidate],seen):
                assigned[candidate] = gold
                return True
        return False

    return sum(match(gold,set()) for gold in range(len(edges)))


def _maximum_row_matches(weights):
    if not weights or not weights[0]:
        return 0
    width = max(len(weights),len(weights[0]))
    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)]
    row_potential,column_potential,assigned,previous = [[0]*(width+1) for _ in range(4)]
    for row in range(1,width+1):
        assigned[0] = row
        column = 0
        distances,used = [float('inf')]*(width+1),[False]*(width+1)
        while True:
            used[column] = True
            current_row = assigned[column]
            delta,next_column = float('inf'),0
            for candidate in range(1,width+1):
                if used[candidate]:
                    continue
                cost = costs[current_row-1][candidate-1]-row_potential[current_row]-column_potential[candidate]
                if cost < distances[candidate]:
                    distances[candidate],previous[candidate] = cost,column
                if distances[candidate] < delta:
                    delta,next_column = distances[candidate],candidate
            for candidate in range(width+1):
                if used[candidate]:
                    row_potential[assigned[candidate]] += delta
                    column_potential[candidate] -= delta
                else:
                    distances[candidate] -= delta
            column = next_column
            if assigned[column] == 0:
                break
        while column:
            prior = previous[column]
            assigned[column] = assigned[prior]
            column = prior
    return -sum(costs[assigned[column]-1][column-1] for column in range(1,width+1))


def count_matches(pred_cells, gold_cells, rel_tol=1e-3, abs_tol=1e-6):
    def groups(cells):
        grouped = {}
        for (identity,column),value in cells.items():
            base = tuple(part for part in identity if not isinstance(part,tuple))
            grouped.setdefault(base,{}).setdefault(identity,[]).append((column,value))
        return grouped

    predictions,golds = groups(pred_cells),groups(gold_cells)
    total = 0
    for identity,rows in golds.items():
        candidates = list(predictions.get(identity,{}).values())
        weights = [[_row_cell_matches(candidate,row,rel_tol,abs_tol) for candidate in candidates] for row in rows.values()]
        total += _maximum_row_matches(weights)
    return total


def to_number(text):
    cleaned = text.strip().replace(",", "").replace("\u2212", "-").rstrip("%").strip()
    try:
        return float(cleaned)
    except ValueError:
        return None


def values_match(a, b, rel_tol=1e-3, abs_tol=1e-6):
    left, right = to_number(a), to_number(b)
    if left is not None and right is not None:
        return math.isclose(left, right, rel_tol=rel_tol, abs_tol=abs_tol)
    return a.strip().lower() == b.strip().lower()



import json
import time
from collections import defaultdict


STRICT_TOLERANCE = (1e-3, 1e-6)
TOLERANCE_LEVELS = {"tol3": 0.03, "tol5": 0.05}
SHARE_POINTS_SCALE = 100.0
SHARE_CHART_TYPES = {"treemap"}
HISTOGRAM_EDGE_TOKENS = ("start", "end")


def _norm(value):
    return value.strip().lower() if isinstance(value, str) else value


def _present(value):
    if value is None:
        return False
    if isinstance(value, str):
        return value.strip() != ""
    return True


def _to_float(value):
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _exact_eq(pred, gold):
    return pred == gold


def _text_eq(pred, gold):
    return _norm(pred) == _norm(gold)


def _num_eq(pred, gold):
    left, right = _to_float(pred), _to_float(gold)
    return left is not None and values_match(str(left), str(right))


def _mapping(target, key):
    value = target.get(key) if isinstance(target, dict) else None
    return value if isinstance(value, dict) else {}


def _axis(target, channel):
    axis = _mapping(target, "axes").get(channel)
    return axis if isinstance(axis, dict) else {}


def _value_representation(target, key):
    return _mapping(target, "valueRepresentation").get(key)


SCALAR_FIELDS = (
    ("type", lambda t: t.get("chartType"), _exact_eq),
    ("title", lambda t: t.get("title"), _text_eq),
    ("value_mode", lambda t: _value_representation(t, "mode"), _exact_eq),
    ("value_format", lambda t: _value_representation(t, "format"), _text_eq),
    ("x_label", lambda t: _axis(t, "x").get("label"), _text_eq),
    ("y_label", lambda t: _axis(t, "y").get("label"), _text_eq),
    ("z_label", lambda t: _axis(t, "z").get("label"), _text_eq),
    ("x_scale", lambda t: _axis(t, "x").get("scale"), _exact_eq),
    ("y_scale", lambda t: _axis(t, "y").get("scale"), _exact_eq),
    ("z_scale", lambda t: _axis(t, "z").get("scale"), _exact_eq),
    ("legend_visible", lambda t: _mapping(t, "legend").get("visible"), _exact_eq),
    ("datalabels_visible", lambda t: _mapping(t, "dataLabels").get("visible"), _exact_eq),
)


def _scalar_observe(getter, eq):
    def observe(pred, gold):
        gold_value, pred_value = getter(gold), getter(pred)
        gold_present, pred_present = _present(gold_value), _present(pred_value)
        correct = gold_present and pred_present and eq(pred_value, gold_value)
        return [(gold_present, pred_present, correct)]

    return observe


def _axis_names(pred, gold):
    return set(AXIS_CHANNELS) | set(_mapping(pred, "axes")) | set(_mapping(gold, "axes"))


def _observe_secondary_axis(attr, eq):
    def observe(pred, gold):
        observations = []
        for channel in sorted(_axis_names(pred,gold) - set(AXIS_CHANNELS)):
            gold_value,pred_value = _axis(gold,channel).get(attr),_axis(pred,channel).get(attr)
            gold_present,pred_present = _present(gold_value),_present(pred_value)
            observations.append((gold_present,pred_present,gold_present and pred_present and eq(pred_value,gold_value)))
        return observations

    return observe


def _observe_axis_bounds(pred, gold):
    observations = []
    for channel in sorted(_axis_names(pred,gold)):
        gold_axis, pred_axis = _axis(gold, channel), _axis(pred, channel)
        for key in ("min", "max"):
            gold_value, pred_value = gold_axis.get(key), pred_axis.get(key)
            gold_present, pred_present = gold_value is not None, pred_value is not None
            correct = gold_present and pred_present and _num_eq(pred_value, gold_value)
            observations.append((gold_present, pred_present, correct))
    return observations


def _row_width(row):
    return len(row) if isinstance(row, (list, tuple)) else -1


def _columns_by_name(target):
    data = _data(target)
    source = data.get("columns")
    columns = {}
    for column in source if isinstance(source, list) else []:
        if isinstance(column, dict) and column.get("name") is not None:
            columns[_norm(column["name"])] = column
    return columns


def _observe_column_attr(attr, eq):
    def observe(pred, gold):
        gold_columns, pred_columns = _columns_by_name(gold), _columns_by_name(pred)
        observations = []
        for name, gold_column in gold_columns.items():
            gold_value = gold_column.get(attr)
            pred_column = pred_columns.get(name)
            pred_value = pred_column.get(attr) if pred_column else None
            gold_present, pred_present = _present(gold_value), _present(pred_value)
            correct = gold_present and pred_present and eq(pred_value, gold_value)
            observations.append((gold_present, pred_present, correct))
        return observations

    return observe


OBSERVATION_FIELDS = (
    tuple((key, _scalar_observe(getter, eq)) for key, getter, eq in SCALAR_FIELDS)
    + (
        ("axis_bound", _observe_axis_bounds),
        ("secondary_axis_label", _observe_secondary_axis("label", _text_eq)),
        ("secondary_axis_scale", _observe_secondary_axis("scale", _exact_eq)),
        ("column_type", _observe_column_attr("type", _exact_eq)),
        ("column_role", _observe_column_attr("role", _exact_eq)),
        ("column_unit", _observe_column_attr("unit", _text_eq)),
    )
)


def _key(value):
    if isinstance(value, str):
        return _norm(value)
    if value is None or isinstance(value, (int, float, bool)):
        return value
    return str(value)


def _encoding_pairs(target):
    encoding = target.get("encoding")
    if not isinstance(encoding, dict):
        return set()
    return {(str(channel), _key(field)) for channel, field in encoding.items() if _present(field)}


def _series_pairs(target):
    series = target.get("series")
    if not isinstance(series, list):
        return set()
    pairs = set()
    for entry in series:
        if isinstance(entry, dict):
            pairs.add((_key(entry.get("name")), _key(entry.get("field"))))
    return pairs


def _series_axis_pairs(target):
    series = target.get("series") if isinstance(target, dict) else None
    if not isinstance(series, list):
        return set()
    return {(_key(entry.get('field')), _key(entry['axis'])) for entry in series if isinstance(entry, dict) and entry.get('axis')}


SET_FIELDS = (
    ("encoding", _encoding_pairs),
    ("series", _series_pairs),
    ("series_axis", _series_axis_pairs),
)


def _data(target):
    data = target.get("data") if isinstance(target, dict) else None
    return data if isinstance(data, dict) else {"columns": [], "rows": []}


def _value_range(gold):
    data = _data(gold)
    columns = data.get("columns", [])
    spatial = any(isinstance(column,dict) and column.get("role") == "z" for column in columns)
    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)))
    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)]
    values = [value for value in values if value is not None]
    if not values:
        return 1.0
    return (max(values) - min(values)) or max(abs(value) for value in values) or 1.0


def _stores_shares(gold):
    return _value_representation(gold, "mode") == "percentage_of_total" or gold.get("chartType") in SHARE_CHART_TYPES


def chart_tolerance(gold, fraction):
    if fraction is None or (gold.get("dataLabels") or {}).get("visible"):
        return STRICT_TOLERANCE
    if _stores_shares(gold):
        return (0.0, fraction * SHARE_POINTS_SCALE)
    return (0.0, fraction * _value_range(gold))


def _drop_histogram_edges(data):
    columns, rows = data.get("columns"), data.get("rows")
    if not isinstance(columns, list) or not isinstance(rows, list):
        return data
    keep = [i for i, column in enumerate(columns)
            if not (isinstance(column, dict) and any(token in str(column.get("name", "")).lower() for token in HISTOGRAM_EDGE_TOKENS))]
    if len(keep) == len(columns):
        return data
    trimmed_rows = [[row[i] for i in keep if i < len(row)] for row in rows if isinstance(row, (list, tuple))]
    return {**data, "columns": [columns[i] for i in keep], "rows": trimmed_rows}


def score_sample(pred, gold):
    pred_data, gold_data = _data(pred), _data(gold)
    if gold.get("chartType") == "histogram":
        pred_data, gold_data = _drop_histogram_edges(pred_data), _drop_histogram_edges(gold_data)
    pred_cells = data_cells(pred_data.get("columns", []), pred_data.get("rows", []))
    gold_cells = data_cells(gold_data.get("columns", []), gold_data.get("rows", []))
    tp = count_matches(pred_cells, gold_cells)
    tp_at = {
        level: count_matches(pred_cells, gold_cells, *chart_tolerance(gold, fraction))
        for level, fraction in TOLERANCE_LEVELS.items()
    }
    gold_rows = gold_data.get("rows") if isinstance(gold_data.get("rows"), list) else []
    pred_rows = pred_data.get("rows") if isinstance(pred_data.get("rows"), list) else []
    shape_match = float(
        len(pred_rows) == len(gold_rows)
        and [_row_width(r) for r in pred_rows] == [_row_width(r) for r in gold_rows]
    )
    fields = {key: observe(pred, gold) for key, observe in OBSERVATION_FIELDS}
    sets = {}
    for key, pairs in SET_FIELDS:
        gold_pairs, pred_pairs = pairs(gold), pairs(pred)
        matched = len(gold_pairs & pred_pairs)
        sets[key] = (matched, len(pred_pairs) - matched, len(gold_pairs) - matched)
    return {
        "tp": tp,
        "fp": len(pred_cells) - tp,
        "fn": len(gold_cells) - tp,
        "tp_at": tp_at,
        "shape_match": shape_match,
        "chart_type": gold.get("chartType", "unknown"),
        "fields": fields,
        "sets": sets,
    }


def precision_recall_f1(tp, fp, fn):
    precision = tp / (tp + fp) if (tp + fp) else 0.0
    recall = tp / (tp + fn) if (tp + fn) else 0.0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
    return precision, recall, f1


def chart_f1(row, level="strict"):
    tp = row["tp"] if level == "strict" else row["tp_at"][level]
    n_pred, n_gold = row["tp"] + row["fp"], row["tp"] + row["fn"]
    return precision_recall_f1(tp, n_pred - tp, n_gold - tp)[2]


def mean_chart_f1(rows, level="strict"):
    return sum(chart_f1(row, level) for row in rows) / len(rows) if rows else 0.0


def tolerant_means(rows, key="mean_chart_f1"):
    return {f"{key}_{level}": mean_chart_f1(rows, level) for level in TOLERANCE_LEVELS}


def aggregate_fields(rows):
    stats = {}
    for key, _ in OBSERVATION_FIELDS:
        acc_n = correct = halluc_n = halluc_hits = 0
        for row in rows:
            for gold_present, pred_present, is_correct in row["fields"][key]:
                if gold_present:
                    acc_n += 1
                    correct += int(is_correct)
                else:
                    halluc_n += 1
                    halluc_hits += int(pred_present)
        stats[key] = {
            "acc": correct / acc_n if acc_n else 0.0,
            "acc_n": acc_n,
            "halluc": halluc_hits / halluc_n if halluc_n else None,
            "halluc_n": halluc_n,
        }
    return stats


def aggregate_sets(rows):
    stats = {}
    for key, _ in SET_FIELDS:
        tp = sum(row["sets"][key][0] for row in rows)
        fp = sum(row["sets"][key][1] for row in rows)
        fn = sum(row["sets"][key][2] for row in rows)
        precision, recall, f1 = precision_recall_f1(tp, fp, fn)
        stats[key] = {"precision": precision, "recall": recall, "f1": f1, "tp": tp, "fp": fp, "fn": fn}
    return stats


def evaluate(dataset, predict, show=0):
    rows = []
    for i in range(len(dataset)):
        example = dataset[i]
        pred = extract_target(predict(example))
        gold = json.loads(example["target"]) if isinstance(example["target"], str) else example["target"]
        row = score_sample(pred, gold)
        rows.append(row)
        if i < show:
            print("=" * 80)
            print("id:", example.get("id"), "|", row["chart_type"], "|",
                  {k: row[k] for k in ("tp", "fp", "fn", "shape_match")})
            print("--- predicted ---")
            print(json.dumps(pred)[:600])
            print("--- ground truth ---")
            print(json.dumps(gold)[:600])
    shape_match = sum(r["shape_match"] for r in rows) / len(rows) if rows else 0.0
    return {
        "mean_chart_f1": mean_chart_f1(rows),
        **tolerant_means(rows),
        "shape_match": shape_match,
        "fields": aggregate_fields(rows),
        "sets": aggregate_sets(rows),
        "rows": rows,
    }


def scoring_view(dataset):
    if hasattr(dataset, "remove_columns") and hasattr(dataset, "column_names"):
        return dataset.remove_columns([column for column in dataset.column_names if column not in ("id", "target")])
    return dataset


def _target_lengths(dataset):
    if hasattr(dataset, "select_columns"):
        return [len(target) for target in dataset.select_columns(["target"])["target"]]
    return [len(example["target"]) for example in dataset]


def evaluate_batched(dataset, predict_batch, batch_size, show=0, log=print):
    lengths = _target_lengths(dataset)
    order = sorted(range(len(dataset)), key=lambda index: lengths[index])
    predictions = {}
    started = time.monotonic()
    for start in range(0, len(order), batch_size):
        batch = [dataset[index] for index in order[start:start + batch_size]]
        for example, text in zip(batch, predict_batch(batch)):
            predictions[example["id"]] = text
        done = start + len(batch)
        elapsed = time.monotonic() - started
        log(f"eval {done}/{len(order)} charts | {elapsed:.0f}s | {60 * done / max(elapsed, 1e-9):.1f} charts/min")
    return evaluate(scoring_view(dataset), lambda example: predictions[example["id"]], show=show)


def aggregate_by_chart_type(rows):
    groups = defaultdict(list)
    for row in rows:
        groups[row["chart_type"]].append(row)
    per_type = []
    for chart_type, group in sorted(groups.items(), key=lambda kv: -len(kv[1])):
        shape_match = sum(r["shape_match"] for r in group) / len(group)
        per_type.append(
            {
                "chart_type": chart_type,
                "n": len(group),
                "mean_chart_f1": mean_chart_f1(group),
                **tolerant_means(group),
                "shape_match": shape_match,
                "fields": aggregate_fields(group),
                "sets": aggregate_sets(group),
            }
        )
    return per_type


def macro_metrics(per_type):
    if not per_type:
        return {"macro_mean_chart_f1": 0.0}
    return {"macro_mean_chart_f1": sum(t["mean_chart_f1"] for t in per_type) / len(per_type)}


def _flatten_fields(prefix, metrics):
    flat = {}
    for key, stat in metrics["fields"].items():
        flat[f"{prefix}/{key}_acc"] = stat["acc"]
        if stat["halluc"] is not None:
            flat[f"{prefix}/{key}_halluc"] = stat["halluc"]
    for key, stat in metrics["sets"].items():
        flat[f"{prefix}/{key}_precision"] = stat["precision"]
        flat[f"{prefix}/{key}_recall"] = stat["recall"]
        flat[f"{prefix}/{key}_f1"] = stat["f1"]
    return flat


def scored_metrics(test_metrics, train_metrics, eval_prefix="test"):
    test_macro = macro_metrics(aggregate_by_chart_type(test_metrics["rows"]))
    train_macro = macro_metrics(aggregate_by_chart_type(train_metrics["rows"]))
    scored = {
        f"{eval_prefix}/mean_chart_f1": test_metrics["mean_chart_f1"],
        f"{eval_prefix}/shape_match": test_metrics["shape_match"],
        f"{eval_prefix}/macro_mean_chart_f1": test_macro["macro_mean_chart_f1"],
        "train/mean_chart_f1": train_metrics["mean_chart_f1"],
        "train/shape_match": train_metrics["shape_match"],
        "train/macro_mean_chart_f1": train_macro["macro_mean_chart_f1"],
        "overfitting/mean_chart_f1_gap": train_metrics["mean_chart_f1"] - test_metrics["mean_chart_f1"],
    }
    scored.update(_flatten_fields(eval_prefix, test_metrics))
    scored.update(_flatten_fields("train", train_metrics))
    return scored



def summary_row(name, metrics):
    fields, sets = metrics["fields"], metrics["sets"]
    return {
        "model": name,
        "n": len(metrics["rows"]),
        "mean_f1": metrics["mean_chart_f1"],
        "mean_f1_tol3": metrics["mean_chart_f1_tol3"],
        "mean_f1_tol5": metrics["mean_chart_f1_tol5"],
        "shape": metrics["shape_match"],
        "type_acc": fields["type"]["acc"],
        "title_acc": fields["title"]["acc"],
        "encoding_f1": sets["encoding"]["f1"],
        "series_f1": sets["series"]["f1"],
    }

import hashlib
import io
from PIL import Image
MAX_IMAGE_PIXELS = 602112
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."
SCORER_HASH = '1782c0b90274e10082385f219e7fbc73e7e7bb2dc4eec02b59480519f72c52de'
def digest(value):
    return hashlib.sha256(value).hexdigest()

def canonical_hash(value):
    return digest(json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(',', ':')).encode())

def image_hash(image):
    if isinstance(image, dict):
        image = Image.open(io.BytesIO(image['bytes'])) if image.get('bytes') else Image.open(image['path'])
    elif isinstance(image, bytes):
        image = Image.open(io.BytesIO(image))
    rgb = image.convert('RGB')
    return digest(str(rgb.size).encode() + rgb.tobytes())

def input_hash(image, prompt):
    return canonical_hash({'image': image_hash(image), 'max_pixels': MAX_IMAGE_PIXELS, 'prompt': prompt})



def _load_predictions(path):
    predictions = {}
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            if line.strip():
                record = json.loads(line)
                predictions[record["id"]] = record
    return predictions


def main():
    parser = argparse.ArgumentParser(description="Score chart-parsing predictions against the frozen benchmark.")
    parser.add_argument("--benchmark-repo", default="nutrientdocs/chart-parsing-benchmark")
    parser.add_argument("--predictions", required=True, help="JSONL of {id, text, input_hash} records")
    parser.add_argument("--revision", default=None)
    parser.add_argument("--out", required=True)
    parser.add_argument("--name", required=True, help="entry name shown on the leaderboard")
    parser.add_argument("--token", default=None)
    args = parser.parse_args()

    from datasets import load_dataset

    from huggingface_hub import hf_hub_download

    benchmark = load_dataset(args.benchmark_repo, revision=args.revision, split="test", token=args.token)
    meta_path = hf_hub_download(args.benchmark_repo, "benchmark_meta.json", repo_type="dataset", revision=args.revision, token=args.token)
    with open(meta_path) as handle:
        meta = json.load(handle)
    predictions = _load_predictions(args.predictions)
    for example in benchmark:
        prediction = predictions.get(example["id"])
        if prediction is not None and prediction.get("input_hash") != input_hash(example["image"], BENCHMARK_PROMPT):
            raise ValueError(f"Prediction input differs for {example['id']}; generate it again")
    missing = [identifier for identifier in benchmark["id"] if identifier not in predictions]
    metrics = evaluate(benchmark, lambda example: predictions.get(example["id"], {}).get("text", ""))
    result = {
        "summary": summary_row(args.name, metrics),
        "per_chart_type": aggregate_by_chart_type(metrics["rows"]),
        "fields": metrics["fields"],
        "sets": metrics["sets"],
        "missing_predictions": len(missing),
        "benchmark_version": meta["version"],
        "benchmark_content_hash": meta.get("content_hash"),
        "scorer_hash": SCORER_HASH,
    }
    with open(args.out, "w", encoding="utf-8") as handle:
        json.dump(result, handle, indent=2)
    row = result["summary"]
    print(
        f"{args.name}: mean_f1 {row['mean_f1']:.3f} | tol3 {row['mean_f1_tol3']:.3f} "
        f"| tol5 {row['mean_f1_tol5']:.3f} | shape {row['shape']:.3f} | missing {len(missing)}"
    )


if __name__ == "__main__":
    main()