File size: 7,765 Bytes
448405f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build sample parquet files for the Hugging Face dataset viewer.

The full dataset is ~39k eval records (~1.4 GB) — far too large for the viewer
to load by globbing JSON. Instead we publish a small, flat *sample* parquet per
collection at ``viewer_parquets/<collection>/...`` which the README
``configs:`` block points at.

Source of truth is the **flat datastore** and its manifest:

    flat/latest_manifest.json  ->  entries_path (flat/manifests/<sha>/entries.jsonl)

Each manifest entry maps an eval object to its ``benchmark`` (collection) and a
content-addressed ``object_path`` (flat/objects/<aa>/<bb>/<uuid>.json). We group
entries by collection, sample up to ``MAX_ROWS`` objects per collection, and
flatten each eval record into one row per ``evaluation_result``.

Run with pyarrow available, e.g.:

    uv run --with pyarrow tools/build_viewer_parquets.py
"""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq

REPO_ROOT = Path(__file__).resolve().parent.parent
FLAT_DIR = REPO_ROOT / 'flat'
README = REPO_ROOT / 'README.md'

# Max rows per collection. These parquets are viewing samples only (not full
# splits), so we cap them small to keep the dataset viewer fast.
MAX_ROWS = 100

# Stable column order for the flattened table.
COLUMNS = [
    'evaluation_id',
    'schema_version',
    'retrieved_timestamp',
    'model_name',
    'model_developer',
    'model_id',
    'inference_platform',
    'source_name',
    'source_organization_name',
    'source_type',
    'evaluator_relationship',
    'eval_library_name',
    'eval_library_version',
    'evaluation_name',
    'dataset_name',
    'metric_id',
    'metric_name',
    'metric_kind',
    'metric_unit',
    'score_type',
    'lower_is_better',
    'min_score',
    'max_score',
    'score',
]

# Columns kept as bool; everything else is serialized to string for a stable
# viewer schema (scores/timestamps are mixed-type across collections).
BOOL_COLUMNS = {'lower_is_better'}


def _get(d: object, *keys: str) -> object:
    """Safely walk nested dicts, returning None on any miss."""
    cur = d
    for k in keys:
        if not isinstance(cur, dict):
            return None
        cur = cur.get(k)
    return cur


def flatten_record(rec: dict) -> list[dict]:
    """Flatten one eval JSON record into one row per evaluation_result."""
    base = {
        'evaluation_id': rec.get('evaluation_id'),
        'schema_version': rec.get('schema_version'),
        'retrieved_timestamp': rec.get('retrieved_timestamp'),
        'model_name': _get(rec, 'model_info', 'name'),
        'model_developer': _get(rec, 'model_info', 'developer'),
        'model_id': _get(rec, 'model_info', 'id'),
        'inference_platform': _get(rec, 'model_info', 'inference_platform'),
        'source_name': _get(rec, 'source_metadata', 'source_name'),
        'source_organization_name': _get(rec, 'source_metadata', 'source_organization_name'),
        'source_type': _get(rec, 'source_metadata', 'source_type'),
        'evaluator_relationship': _get(rec, 'source_metadata', 'evaluator_relationship'),
        'eval_library_name': _get(rec, 'eval_library', 'name'),
        'eval_library_version': _get(rec, 'eval_library', 'version'),
    }
    rows = []
    results = rec.get('evaluation_results')
    if not isinstance(results, list) or not results:
        results = [{}]
    for er in results:
        if not isinstance(er, dict):
            er = {}
        row = dict(base)
        row.update({
            'evaluation_name': er.get('evaluation_name'),
            'dataset_name': _get(er, 'source_data', 'dataset_name'),
            'metric_id': _get(er, 'metric_config', 'metric_id'),
            'metric_name': _get(er, 'metric_config', 'metric_name'),
            'metric_kind': _get(er, 'metric_config', 'metric_kind'),
            'metric_unit': _get(er, 'metric_config', 'metric_unit'),
            'score_type': _get(er, 'metric_config', 'score_type'),
            'lower_is_better': _get(er, 'metric_config', 'lower_is_better'),
            'min_score': _get(er, 'metric_config', 'min_score'),
            'max_score': _get(er, 'metric_config', 'max_score'),
            'score': _get(er, 'score_details', 'score'),
        })
        rows.append(row)
    return rows


def _cell(col: str, value: object) -> object:
    if value is None:
        return None
    if col in BOOL_COLUMNS:
        return bool(value)
    if isinstance(value, str):
        return value
    return json.dumps(value) if isinstance(value, (dict, list)) else str(value)


def _table(rows: list[dict]) -> pa.Table:
    schema = pa.schema([
        (c, pa.bool_() if c in BOOL_COLUMNS else pa.string()) for c in COLUMNS
    ])
    cols = {c: [_cell(c, r.get(c)) for r in rows] for c in COLUMNS}
    return pa.table(cols, schema=schema)


def load_manifest_entries() -> list[dict]:
    manifest = json.loads((FLAT_DIR / 'latest_manifest.json').read_text())
    entries_path = REPO_ROOT / manifest['entries_path']
    entries = []
    for line in entries_path.read_text().splitlines():
        line = line.strip()
        if line:
            entries.append(json.loads(line))
    return entries


def build_collection(object_paths: list[str], out_file: Path) -> int:
    rows: list[dict] = []
    for rel in object_paths:
        if len(rows) >= MAX_ROWS:
            break
        try:
            rec = json.loads((REPO_ROOT / rel).read_text())
        except (json.JSONDecodeError, OSError):
            continue
        if isinstance(rec, dict):
            rows.extend(flatten_record(rec))
    rows = rows[:MAX_ROWS]
    if not rows:
        rows = [{c: None for c in COLUMNS}]
    out_file.parent.mkdir(parents=True, exist_ok=True)
    pq.write_table(_table(rows), out_file)
    return len(rows)


def viewer_targets() -> list[tuple[str, Path]]:
    """Every viewer_parquets/<collection>/<file>.parquet path in the README."""
    pat = re.compile(r'path:\s*(viewer_parquets/([^/\s]+)/[^\s]+\.parquet)')
    seen: dict[str, tuple[str, Path]] = {}
    for m in pat.finditer(README.read_text()):
        rel, collection = m.group(1), m.group(2)
        seen[rel] = (collection, REPO_ROOT / rel)
    return list(seen.values())


def main() -> None:
    global MAX_ROWS
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--max-rows', type=int, default=MAX_ROWS)
    args = ap.parse_args()
    MAX_ROWS = args.max_rows

    entries = load_manifest_entries()
    # Group object paths by lowercased benchmark for case-insensitive matching
    # (README uses e.g. "mmlu-pro" while the manifest benchmark is "MMLU-Pro").
    by_collection: dict[str, list[str]] = {}
    for e in entries:
        bench = e.get('benchmark')
        obj = e.get('object_path')
        if isinstance(bench, str) and isinstance(obj, str):
            by_collection.setdefault(bench.lower(), []).append(obj)
    for paths in by_collection.values():
        paths.sort()

    targets = viewer_targets()
    print(f'Building {len(targets)} sample parquet(s) from flat manifest '
          f'({len(entries)} entries, max {MAX_ROWS} rows each)')
    missing = []
    for collection, out_file in targets:
        paths = by_collection.get(collection.lower())
        if not paths:
            missing.append(collection)
            print(f'  SKIP  {collection}: no manifest entries')
            continue
        n = build_collection(paths, out_file)
        print(f'  ok    {out_file.relative_to(REPO_ROOT)}  ({n} rows from {len(paths)} objects)')
    if missing:
        print(f'\nWARNING: {len(missing)} collections had no manifest entries: {missing}')


if __name__ == '__main__':
    main()