#!/usr/bin/env python3 """Deterministic generator for the NativePort Web-Access API Benchmarks dataset. Reads a NativePort ``evals.json`` snapshot and writes four artifacts: data/metric_rows.jsonl tidy/long form, one record per provider x capability x metric data/benchmarks.csv the same tidy rows as CSV, value for value identical data/benchmarks.jsonl one record per provider x capability evaluation, metrics nested data/summary.json computed snapshot facts (every count is derived, never typed) Both Hugging Face configs declared in README.md front matter are backed by JSONL (``metric_rows`` -> data/metric_rows.jsonl, ``evaluations`` -> data/benchmarks.jsonl). The Hub resolves a single packaged builder for a whole repository from the declared config data files and applies it to every config, so a repository that mixes CSV and JSONL across configs has the wrong parser applied to one of them. ``data/benchmarks.csv`` therefore stays a plain downloadable artifact and backs no config. The tidy CSV and the tidy JSONL are emitted from one row builder, so the two cannot drift. Design rules ------------ * Standard library only. * Deterministic: identical input bytes produce identical output bytes. No wall-clock timestamps are recorded; the snapshot is identified by ``latest_run`` plus the SHA-256 of the source file. * Numeric values are preserved exactly. The source is parsed with ``parse_float=str`` and ``parse_int=str`` so the original token text is kept, and every number is only emitted after verifying that the JSON serialisation of the parsed value is character-for-character identical to that token. A snapshot that cannot satisfy this (for example a token written as ``1.10``) aborts the build instead of silently rounding. * Only defensible benchmark and provenance fields are copied. Commercial and routing fields present in the source (pricing, latency prose, marketing summaries, choose_if / avoid_if, gateway routes, auth strings, catalog tier) are excluded. Usage ----- python3 scripts/build_dataset.py --input /path/to/evals.json --output-dir data """ from __future__ import annotations import argparse import csv import hashlib import json import sys from pathlib import Path GENERATOR_VERSION = "1.0.0" DATASET_NAME = "NativePort Web-Access API Benchmarks" DATASET_ID = "nativeport/web-access-api-benchmarks" METHODOLOGY_URL = "https://nativeport.ai/methodology/" LEADERBOARDS_URL = "https://nativeport.ai/leaderboards/" # The source states, and the methodology page confirms, that per-capability metrics # fold into a composite scored out of 10. It is recorded per row so a consumer never # has to assume the scale. COMPOSITE_SCALE_MAX = 10 # Output file names. The tidy view is published twice from one row builder: as JSONL, # which backs the `metric_rows` config, and as CSV, which is a downloadable artifact # only. See HUB_CONFIG_DATA_FILES below for why the config cannot point at the CSV. METRIC_ROWS_JSONL_NAME = "metric_rows.jsonl" CSV_NAME = "benchmarks.csv" EVALUATIONS_JSONL_NAME = "benchmarks.jsonl" SUMMARY_NAME = "summary.json" # The Hugging Face configs declared in README.md front matter, and the file backing # each one. Both must be JSONL. The Hub resolves one packaged builder for the entire # repository from the declared config data files and applies it to every config; mixing # formats therefore parses one config with the other's reader. `data/benchmarks.csv` is # deliberately absent from this mapping: it ships as a documented download, not as # config data. HUB_CONFIG_DATA_FILES = { "metric_rows": f"data/{METRIC_ROWS_JSONL_NAME}", "evaluations": f"data/{EVALUATIONS_JSONL_NAME}", } DOWNLOADABLE_ONLY_ARTIFACTS = [f"data/{CSV_NAME}"] # Field order of the tidy view. The CSV header and the keys of every record in # data/metric_rows.jsonl are this list, in this order. TIDY_FIELDS = [ "evaluation_id", "provider_id", "provider_name", "provider_group", "provider_category", "capability_id", "capability_label", "metric_key", "metric_label", "metric_raw", "metric_display", "metric_index", "composite_score", "composite_scale_max", "rank", "rank_of", "is_capability_top", "measured_date", "note", "provider_page_url", "run_id", "source_url", "snapshot_sha256", ] class BuildError(Exception): """Raised when the snapshot cannot be converted faithfully.""" # --------------------------------------------------------------------------- # # exact numeric handling # --------------------------------------------------------------------------- # def json_number_text(value): """Return the exact text ``json.dumps`` will emit for this number.""" return json.dumps(value) def exact_number(token, path): """Convert a source numeric token to (text, value) without losing precision. ``token`` is the untouched text from the snapshot. The returned ``text`` is that same token, used verbatim in the CSV; the returned ``value`` is the parsed number used in JSON output. The build aborts unless the two are provably identical. """ if not isinstance(token, str): raise BuildError(f"{path}: expected a numeric token, got {type(token).__name__}") try: if "." in token or "e" in token or "E" in token: value = float(token) else: value = int(token) except ValueError as exc: raise BuildError(f"{path}: not a number: {token!r}") from exc rendered = json_number_text(value) if rendered != token: raise BuildError( f"{path}: cannot round-trip {token!r} exactly (would be written as " f"{rendered!r}). Refusing to emit an altered numeric value." ) return token, value def require(condition, message): if not condition: raise BuildError(message) def text_field(container, key, path): value = container.get(key) require(isinstance(value, str), f"{path}.{key}: expected a string") return value def https_url(container, key, path): value = text_field(container, key, path) require(value.startswith("https://"), f"{path}.{key}: expected an https URL, got {value!r}") return value # --------------------------------------------------------------------------- # # extraction # --------------------------------------------------------------------------- # def load_snapshot(input_path): raw_bytes = input_path.read_bytes() snapshot_sha256 = hashlib.sha256(raw_bytes).hexdigest() document = json.loads(raw_bytes.decode("utf-8"), parse_float=str, parse_int=str) require(isinstance(document, dict), "snapshot root must be a JSON object") return document, snapshot_sha256, len(raw_bytes) def extract_evaluations(document, snapshot_sha256): """Return the evaluation records in a stable order. Ordering key is (capability_id, rank, provider_id): leaderboard order within each capability, which is both meaningful and independent of source dict iteration. """ source_url = https_url(document, "source", "$") latest_run = text_field(document, "latest_run", "$") schema_version_text, schema_version = exact_number( document.get("schema_version"), "$.schema_version" ) del schema_version_text verbs = document.get("verbs") require(isinstance(verbs, dict), "$.verbs must be an object") providers = document.get("providers") require(isinstance(providers, dict), "$.providers must be an object") run = document.get("run") if isinstance(document.get("run"), dict) else {} run_id = run.get("name") if isinstance(run.get("name"), str) else latest_run evaluations = [] seen_keys = set() for provider_id in providers: provider = providers[provider_id] path = f"$.providers.{provider_id}" require(isinstance(provider, dict), f"{path}: expected an object") evals = provider.get("evals") if not evals: continue require(isinstance(evals, list), f"{path}.evals: expected a list") provider_name = text_field(provider, "name", path) provider_group = text_field(provider, "group", path) provider_category = text_field(provider, "category", path) provider_page_url = https_url(provider, "page", path) for position, entry in enumerate(evals): entry_path = f"{path}.evals[{position}]" require(isinstance(entry, dict), f"{entry_path}: expected an object") capability_id = text_field(entry, "verb", entry_path) require( capability_id in verbs, f"{entry_path}.verb: {capability_id!r} is absent from $.verbs", ) capability = verbs[capability_id] capability_label = text_field(entry, "label", entry_path) require( capability_label == capability.get("label"), f"{entry_path}.label: {capability_label!r} disagrees with " f"$.verbs.{capability_id}.label", ) capability_description = text_field( capability, "description", f"$.verbs.{capability_id}" ) evaluation_id = f"{provider_id}:{capability_id}" require( evaluation_id not in seen_keys, f"{entry_path}: duplicate evaluation key {evaluation_id!r}", ) seen_keys.add(evaluation_id) composite_text, composite_value = exact_number( entry.get("composite"), f"{entry_path}.composite" ) rank_text, rank_value = exact_number(entry.get("rank"), f"{entry_path}.rank") of_text, of_value = exact_number(entry.get("of"), f"{entry_path}.of") require( isinstance(rank_value, int) and isinstance(of_value, int), f"{entry_path}: rank and of must be integers", ) require( 1 <= rank_value <= of_value, f"{entry_path}: rank {rank_value} outside 1..{of_value}", ) require( 0 <= composite_value <= COMPOSITE_SCALE_MAX, f"{entry_path}: composite {composite_value} outside 0..{COMPOSITE_SCALE_MAX}", ) top = entry.get("top") require(isinstance(top, bool), f"{entry_path}.top: expected a boolean") require( top == (rank_value == 1), f"{entry_path}.top: {top} disagrees with rank {rank_value}", ) measured_date = text_field(entry, "measured", entry_path) note = text_field(entry, "note", entry_path) metrics_source = entry.get("metrics") require( isinstance(metrics_source, list) and metrics_source, f"{entry_path}.metrics: expected a non-empty list", ) metrics = [] metric_keys = set() for metric_index, metric in enumerate(metrics_source): metric_path = f"{entry_path}.metrics[{metric_index}]" require(isinstance(metric, dict), f"{metric_path}: expected an object") metric_key = text_field(metric, "key", metric_path) require( metric_key not in metric_keys, f"{metric_path}: duplicate metric key {metric_key!r}", ) metric_keys.add(metric_key) raw_text, raw_value = exact_number(metric.get("raw"), f"{metric_path}.raw") metrics.append( { "metric_index": metric_index, "metric_key": metric_key, "metric_label": text_field(metric, "label", metric_path), "raw_value": raw_value, "raw_text": raw_text, "display_value": text_field(metric, "value", metric_path), } ) evaluations.append( { "evaluation_id": evaluation_id, "provider_id": provider_id, "provider_name": provider_name, "provider_group": provider_group, "provider_category": provider_category, "capability_id": capability_id, "capability_label": capability_label, "capability_description": capability_description, "composite_score": composite_value, "composite_text": composite_text, "composite_scale_max": COMPOSITE_SCALE_MAX, "rank": rank_value, "rank_text": rank_text, "rank_of": of_value, "rank_of_text": of_text, "is_capability_top": top, "measured_date": measured_date, "note": note, "metrics": metrics, "provider_page_url": provider_page_url, "run_id": run_id, "source_url": source_url, "source_schema_version": schema_version, "snapshot_sha256": snapshot_sha256, } ) evaluations.sort(key=lambda row: (row["capability_id"], row["rank"], row["provider_id"])) meta = { "source_url": source_url, "latest_run": latest_run, "run_id": run_id, "schema_version": schema_version, "catalog_provider_count": len(providers), "run": run, } return evaluations, meta # --------------------------------------------------------------------------- # # writers # --------------------------------------------------------------------------- # def tidy_record(evaluation, metric): """One tidy metric row, typed, with keys in ``TIDY_FIELDS`` order. This is the single definition of the tidy view. ``write_metric_rows_jsonl`` writes these values as JSON; ``write_csv`` writes the same values rendered as text by ``csv_cell``. Neither view can gain, lose or reorder a field without the other. """ record = { "evaluation_id": evaluation["evaluation_id"], "provider_id": evaluation["provider_id"], "provider_name": evaluation["provider_name"], "provider_group": evaluation["provider_group"], "provider_category": evaluation["provider_category"], "capability_id": evaluation["capability_id"], "capability_label": evaluation["capability_label"], "metric_key": metric["metric_key"], "metric_label": metric["metric_label"], "metric_raw": metric["raw_value"], "metric_display": metric["display_value"], "metric_index": metric["metric_index"], "composite_score": evaluation["composite_score"], "composite_scale_max": evaluation["composite_scale_max"], "rank": evaluation["rank"], "rank_of": evaluation["rank_of"], "is_capability_top": evaluation["is_capability_top"], "measured_date": evaluation["measured_date"], "note": evaluation["note"], "provider_page_url": evaluation["provider_page_url"], "run_id": evaluation["run_id"], "source_url": evaluation["source_url"], "snapshot_sha256": evaluation["snapshot_sha256"], } require( list(record) == TIDY_FIELDS, "tidy record fields drifted from TIDY_FIELDS: " f"{[f for f in record if f not in TIDY_FIELDS]} / " f"{[f for f in TIDY_FIELDS if f not in record]}", ) return record def tidy_records(evaluations): for evaluation in evaluations: for metric in evaluation["metrics"]: yield tidy_record(evaluation, metric) def csv_cell(value): """Render one tidy value as CSV text. Numbers go through ``json_number_text``, the same serialiser the JSONL writer uses, so a measurement reads identically in both files. ``exact_number`` has already proved that this text is the source token character for character. """ if isinstance(value, bool): return "true" if value else "false" if isinstance(value, (int, float)): return json_number_text(value) return value def write_csv(evaluations, path): rows = 0 with path.open("w", encoding="utf-8", newline="") as handle: writer = csv.writer(handle, lineterminator="\n", quoting=csv.QUOTE_MINIMAL) writer.writerow(TIDY_FIELDS) for record in tidy_records(evaluations): writer.writerow([csv_cell(value) for value in record.values()]) rows += 1 return rows def write_metric_rows_jsonl(evaluations, path): """The tidy view as JSONL, one record per metric row. This is what the ``metric_rows`` Hugging Face config loads. It carries the same fields as the CSV in the same order, with numbers as JSON numbers and ``is_capability_top`` as a JSON boolean. """ rows = 0 with path.open("w", encoding="utf-8", newline="") as handle: for record in tidy_records(evaluations): handle.write(json.dumps(record, ensure_ascii=False)) handle.write("\n") rows += 1 return rows def jsonl_record(evaluation): """Public shape of one evaluation record. Key order is fixed for determinism.""" return { "evaluation_id": evaluation["evaluation_id"], "provider_id": evaluation["provider_id"], "provider_name": evaluation["provider_name"], "provider_group": evaluation["provider_group"], "provider_category": evaluation["provider_category"], "capability_id": evaluation["capability_id"], "capability_label": evaluation["capability_label"], "capability_description": evaluation["capability_description"], "composite_score": evaluation["composite_score"], "composite_scale_max": evaluation["composite_scale_max"], "rank": evaluation["rank"], "rank_of": evaluation["rank_of"], "is_capability_top": evaluation["is_capability_top"], "measured_date": evaluation["measured_date"], "note": evaluation["note"], "metric_count": len(evaluation["metrics"]), "metrics": [ { "metric_index": metric["metric_index"], "metric_key": metric["metric_key"], "metric_label": metric["metric_label"], "raw_value": metric["raw_value"], "display_value": metric["display_value"], } for metric in evaluation["metrics"] ], "provider_page_url": evaluation["provider_page_url"], "run_id": evaluation["run_id"], "source_url": evaluation["source_url"], "source_schema_version": evaluation["source_schema_version"], "snapshot_sha256": evaluation["snapshot_sha256"], } def write_jsonl(evaluations, path): with path.open("w", encoding="utf-8", newline="") as handle: for evaluation in evaluations: handle.write(json.dumps(jsonl_record(evaluation), ensure_ascii=False)) handle.write("\n") return len(evaluations) def sha256_of(path): return hashlib.sha256(path.read_bytes()).hexdigest() def build_summary(evaluations, meta, artifacts, source_bytes): """Every figure here is computed from the extracted rows. ``artifacts`` maps each written data file to (path, record count). """ (metric_rows_path, metric_rows) = artifacts["metric_rows_jsonl"] (csv_path, csv_rows) = artifacts["csv"] (jsonl_path, jsonl_records) = artifacts["evaluations_jsonl"] provider_ids = sorted({e["provider_id"] for e in evaluations}) capability_ids = sorted({e["capability_id"] for e in evaluations}) measured_dates = sorted({e["measured_date"] for e in evaluations}) metric_row_count = sum(len(e["metrics"]) for e in evaluations) capabilities = [] for capability_id in capability_ids: rows = [e for e in evaluations if e["capability_id"] == capability_id] metric_keys = sorted({m["metric_key"] for r in rows for m in r["metrics"]}) rank_of_values = sorted({r["rank_of"] for r in rows}) capabilities.append( { "capability_id": capability_id, "capability_label": rows[0]["capability_label"], "capability_description": rows[0]["capability_description"], "evaluation_count": len(rows), "rank_of_values": rank_of_values, "rank_of_matches_evaluation_count": rank_of_values == [len(rows)], "provider_ids": sorted(r["provider_id"] for r in rows), "metric_keys": metric_keys, "metric_row_count": sum(len(r["metrics"]) for r in rows), "composite_score_min": min(r["composite_score"] for r in rows), "composite_score_max": max(r["composite_score"] for r in rows), } ) providers = [] for provider_id in provider_ids: rows = [e for e in evaluations if e["provider_id"] == provider_id] providers.append( { "provider_id": provider_id, "provider_name": rows[0]["provider_name"], "provider_group": rows[0]["provider_group"], "evaluation_count": len(rows), "capability_ids": sorted(r["capability_id"] for r in rows), } ) metric_keys = [] for metric_key in sorted({m["metric_key"] for e in evaluations for m in e["metrics"]}): occurrences = [ (e, m) for e in evaluations for m in e["metrics"] if m["metric_key"] == metric_key ] metric_keys.append( { "metric_key": metric_key, "metric_labels": sorted({m["metric_label"] for _, m in occurrences}), "occurrence_count": len(occurrences), "capability_ids": sorted({e["capability_id"] for e, _ in occurrences}), } ) run = meta["run"] source_reported = { "scored_providers": run.get("scored_providers"), "scorecards": run.get("scorecards"), "capabilities": run.get("capabilities"), "catalog_providers": run.get("catalog_providers"), } def as_int(value): return int(value) if isinstance(value, str) and value.isdigit() else value source_reported = {key: as_int(value) for key, value in source_reported.items()} unscored_pairs = run.get("unscored_pairs") unscored_pair_count = len(unscored_pairs) if isinstance(unscored_pairs, list) else 0 return { "dataset_name": DATASET_NAME, "intended_dataset_id": DATASET_ID, "generator": "scripts/build_dataset.py", "generator_version": GENERATOR_VERSION, "source_url": meta["source_url"], "methodology_url": METHODOLOGY_URL, "leaderboards_url": LEADERBOARDS_URL, "source_schema_version": meta["schema_version"], "source_bytes": source_bytes, "snapshot_sha256": evaluations[0]["snapshot_sha256"] if evaluations else None, "latest_run": meta["latest_run"], "run_id": meta["run_id"], "provider_count_represented": len(provider_ids), "provider_count_in_source_catalog": meta["catalog_provider_count"], "provider_count_in_catalog_without_evaluations": ( meta["catalog_provider_count"] - len(provider_ids) ), "evaluation_count": len(evaluations), "capability_count": len(capability_ids), "metric_row_count": metric_row_count, "unscored_pair_count_in_source": unscored_pair_count, "measured_date_min": measured_dates[0] if measured_dates else None, "measured_date_max": measured_dates[-1] if measured_dates else None, "measured_dates": measured_dates, "composite_scale_max": COMPOSITE_SCALE_MAX, "source_reported_run_totals": source_reported, "cross_check": { "scored_providers_matches": source_reported.get("scored_providers") == len(provider_ids), "scorecards_matches": source_reported.get("scorecards") == len(evaluations), "capabilities_matches": source_reported.get("capabilities") == len(capability_ids), "catalog_providers_matches": source_reported.get("catalog_providers") == meta["catalog_provider_count"], }, "capabilities": capabilities, "providers": providers, "metric_keys": metric_keys, "hub_config_data_files": dict(HUB_CONFIG_DATA_FILES), "hub_config_data_file_format": sorted( {Path(relative).suffix.lstrip(".") for relative in HUB_CONFIG_DATA_FILES.values()} ), "downloadable_only_artifacts": list(DOWNLOADABLE_ONLY_ARTIFACTS), "outputs": { metric_rows_path.name: { "kind": "jsonl", "records": metric_rows, "fields": len(TIDY_FIELDS), "field_names": list(TIDY_FIELDS), "bytes": metric_rows_path.stat().st_size, "sha256": sha256_of(metric_rows_path), }, csv_path.name: { "kind": "csv", "data_rows": csv_rows, "columns": len(TIDY_FIELDS), "column_names": list(TIDY_FIELDS), "mirrors": metric_rows_path.name, "bytes": csv_path.stat().st_size, "sha256": sha256_of(csv_path), }, jsonl_path.name: { "kind": "jsonl", "records": jsonl_records, "bytes": jsonl_path.stat().st_size, "sha256": sha256_of(jsonl_path), }, }, } def write_summary(summary, path): with path.open("w", encoding="utf-8", newline="") as handle: json.dump(summary, handle, ensure_ascii=False, indent=2, sort_keys=False) handle.write("\n") # --------------------------------------------------------------------------- # # entry point # --------------------------------------------------------------------------- # def build(input_path, output_dir): input_path = Path(input_path) output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) document, snapshot_sha256, source_bytes = load_snapshot(input_path) evaluations, meta = extract_evaluations(document, snapshot_sha256) require(evaluations, "no evaluations found in the snapshot") metric_rows_path = output_dir / METRIC_ROWS_JSONL_NAME csv_path = output_dir / CSV_NAME jsonl_path = output_dir / EVALUATIONS_JSONL_NAME summary_path = output_dir / SUMMARY_NAME metric_rows = write_metric_rows_jsonl(evaluations, metric_rows_path) csv_rows = write_csv(evaluations, csv_path) jsonl_records = write_jsonl(evaluations, jsonl_path) require( metric_rows == csv_rows, f"tidy views disagree: {metric_rows} JSONL records vs {csv_rows} CSV rows", ) summary = build_summary( evaluations, meta, { "metric_rows_jsonl": (metric_rows_path, metric_rows), "csv": (csv_path, csv_rows), "evaluations_jsonl": (jsonl_path, jsonl_records), }, source_bytes, ) write_summary(summary, summary_path) return summary def default_output_dir(): return Path(__file__).resolve().parent.parent / "data" def main(argv=None): parser = argparse.ArgumentParser( description="Build the NativePort Web-Access API Benchmarks dataset files." ) parser.add_argument( "--input", required=True, help="Path to a NativePort evals.json snapshot.", ) parser.add_argument( "--output-dir", default=str(default_output_dir()), help=( f"Directory to write {METRIC_ROWS_JSONL_NAME}, {CSV_NAME}, " f"{EVALUATIONS_JSONL_NAME} and {SUMMARY_NAME} into." ), ) args = parser.parse_args(argv) try: summary = build(args.input, args.output_dir) except BuildError as exc: print(f"build failed: {exc}", file=sys.stderr) return 1 outputs = summary["outputs"] print(f"source {summary['source_url']}") print(f"snapshot sha256 {summary['snapshot_sha256']}") print(f"latest run {summary['latest_run']}") print( "counts providers={} capabilities={} evaluations={} metric_rows={}".format( summary["provider_count_represented"], summary["capability_count"], summary["evaluation_count"], summary["metric_row_count"], ) ) for name in sorted(outputs): entry = outputs[name] size = entry.get("data_rows", entry.get("records")) print(f"wrote {name} ({size} rows, {entry['bytes']} bytes) {entry['sha256']}") print(f"wrote {SUMMARY_NAME}") for config_name in sorted(summary["hub_config_data_files"]): print(f"hub config {config_name} -> {summary['hub_config_data_files'][config_name]}") return 0 if __name__ == "__main__": raise SystemExit(main())