#!/usr/bin/env python3 """Build the Craft Quantities open dataset (v1.9.0, 2026-11-30) from the PUBLISHED CC BY 4.0 files. python build_dataset.py holds verbatim copies of https://craftquantities.com/api/v1/ and /formulas/ files: index.json calculators.json validation.json units.json glossary.json corrections.json standards.json calculators/.json reference/.json standards//.json formulas/.json Writes /data/
.parquet, /jsonl/
.jsonl and /manifest.json. Needs pyarrow. No network. Editorial decisions (see README.md): * the labour production-rates table is LEFT OUT (rule-of-thumb person-hours, mostly uncited: not ground truth); * the AISC-derived steel-section rows are KEPT, because the site publishes them under CC BY with the source on every row; the per-row source travels with them and `derived_from_aisc` marks them. """ import hashlib import json import os import sys from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq VERSION = "1.9.0" DATE = "2026-11-30" SOURCE_COMMIT = "a87df7c" EXCLUDED_TABLES = {"production-rates": "Labour production rates: rule-of-thumb person-hour bands, most rows cite no checked source. Not ground truth, so not in this dataset."} AISC_MARK = "AISC Shapes Database" RAW = Path(sys.argv[1]) OUT = Path(sys.argv[2]) def load(rel): with open(RAW / rel, encoding="utf-8") as fh: return json.load(fh) def js(value): """A value of mixed or nested type, kept exactly, as a JSON string.""" return None if value is None else json.dumps(value, ensure_ascii=False, separators=(",", ":")) def num(value): return None if value is None else float(value) index = load("index.json") catalogue = load("calculators.json") units_doc = load("units.json") base_unit = {d["dimension"]: d["baseUnit"] for d in units_doc["dimensions"]} # the base unit's printed symbol ("m2" -> "m²"), from the same file base_symbol = {d["dimension"]: next((u.get("symbol") or u["id"] for u in d["units"] if u["id"] == d["baseUnit"]), d["baseUnit"]) for d in units_doc["dimensions"]} tables = {} schemas = {} # ---------------------------------------------------------------- calculators, inputs, test vectors calculators, inputs, vectors = [], [], [] calc_files = {} for row in catalogue["calculators"]: c = load(f"calculators/{row['slug']}.json") calc_files[row["slug"]] = c calculators.append({ "slug": c["slug"], "title": c["title"], "category": c["category"], "description": c["description"], "url": c["url"], "api_url": c["json"], "calculator_version": c["citation"]["version"], "last_verified": c["lastVerified"], "input_count": c["inputCount"], "test_case_count": c["testCaseCount"], "source_count": c["sourceCount"], "sources": [{"label": s["label"], "url": s.get("url")} for s in c["sources"]], "input_ids": [i["id"] for i in c["inputs"]], "used_by_takeoffs": [a["id"] for a in c.get("usedByAssemblies", [])], "translations": [{"locale": k, "url": v} for k, v in sorted((c.get("translations") or {}).items())], "citation": c["citation"]["formats"]["plain"], }) for pos, i in enumerate(c["inputs"]): inputs.append({ "slug": c["slug"], "position": pos, "input_id": i["id"], "label": i["label"], "type": i["type"], "dimension": i.get("dimension"), "base_unit": base_unit.get(i["dimension"]) if i.get("dimension") else None, "base_unit_symbol": base_symbol.get(i["dimension"]) if i.get("dimension") else None, "default_value": js(i.get("defaultValue")), "min": num(i.get("min")), "max": num(i.get("max")), "step": num(i.get("step")), "is_money": bool(i.get("money", False)), "options": js(i.get("options")), "options_by_system": js(i.get("optionsBySystem")), "help": i.get("help"), }) for pos, v in enumerate(c["testCases"]): tdp = v.get("toleranceDecimalPlaces") vectors.append({ "vector_id": f"{c['slug']}#{pos}", "slug": c["slug"], "position": pos, "name": v["name"], "inputs": js(v["inputs"]), "expected": float(v["expected"]), "unit": v["unit"], "tolerance_decimal_places": num(tdp), "abs_tolerance": 0.5 * 10 ** -(2 if tdp is None else tdp), "confidence": v.get("confidence"), "basis": v.get("basis"), "source_index": v.get("sourceIndex"), "includes_allowance": v.get("includesAllowance"), "steps": js(v.get("steps")), }) tables["calculators"], tables["calculator_inputs"], tables["test_vectors"] = calculators, inputs, vectors # ---------------------------------------------------------------- formulas formulas = [] fidx = load("formulas/index.json") for fam in fidx["families"]: f = load(f"formulas/{fam['id']}.json") for x in f["formulas"]: formulas.append({ "family_id": f["id"], "family_title": f["title"], "formula_id": x["id"], "name": x.get("name"), "gives": x.get("gives"), "equation": x["equation"], "expression": x.get("expression"), "mathml": x.get("mathml"), "output": js(x.get("output")), "inputs": js(x.get("inputs")), "calculators": [k["slug"] for k in x.get("calculators", [])], "test_vectors": js(x.get("testVectors")), "url": fam["url"], }) tables["formulas"] = formulas # ---------------------------------------------------------------- units units = [] for d in units_doc["dimensions"]: for u in d["units"]: units.append({ "dimension": d["dimension"], "base_unit": d["baseUnit"], "unit_id": u["id"], "label": u.get("label"), "symbol": u.get("symbol"), "system": u.get("system"), "to_base": float(u["toBase"]), "offset_to_base": float(u.get("offsetToBase", 0)), }) tables["units"] = units # ---------------------------------------------------------------- reference tables (sources per row) ref_tables, ref_rows, ref_cells = [], [], [] ref_total_rows_published = 0 for name in sorted(os.listdir(RAW / "reference")): t = load(f"reference/{name}") ref_total_rows_published += len(t["rows"]) if t["id"] in EXCLUDED_TABLES: continue cols = {c["key"]: c for c in t["columns"]} ref_tables.append({ "table_id": t["id"], "family": t["family"], "title": t["title"], "page": t["page"], "summary": t.get("summary"), "excludes": t.get("excludes"), "columns": js(t["columns"]), "row_count": len(t["rows"]), "used_by": [u["slug"] for u in t.get("usedBy", [])], "citation": t["citation"]["formats"]["plain"] if isinstance(t.get("citation"), dict) and "formats" in t["citation"] else js(t.get("citation")), }) for r in t["rows"]: src = r.get("source") or {} aisc = AISC_MARK in (src.get("text") or "") ref_rows.append({ "table_id": t["id"], "row_id": r["id"], "cells": js(r["cells"]), "source_kind": src.get("kind"), "source_text": src.get("text"), "derived_from_aisc": aisc, "note": r.get("note"), "used_by": [u["slug"] for u in r.get("usedBy", [])], "unattached_reason": r.get("unattachedReason"), }) for key, cell in r["cells"].items(): col = cols.get(key, {}) ref_cells.append({ "table_id": t["id"], "row_id": r["id"], "column_key": key, "column_label": col.get("label"), "column_unit": col.get("unit"), "kind": cell["kind"], "value": num(cell.get("value")), "low": num(cell.get("low")), "typical": num(cell.get("typical")), "high": num(cell.get("high")), "precision": num(cell.get("precision")), "text": cell.get("text"), "source_kind": src.get("kind"), "source_text": src.get("text"), }) tables["reference_tables"], tables["reference_rows"], tables["reference_cells"] = ref_tables, ref_rows, ref_cells # ---------------------------------------------------------------- glossary glossary = [] for g in load("glossary.json")["concepts"]: glossary.append({ "slug": g["slug"], "concept": g["concept"], "family": g.get("family"), "definition": g.get("definition"), "url": g.get("url"), "names": [{"market": n["market"], "term": n["term"], "also_called": n.get("alsoCalled") or [], "exactness": n.get("exactness"), "note": n.get("note")} for n in g.get("names", [])], "standards": [{"market": s.get("market"), "standard": s.get("standard"), "covers": s.get("covers")} for s in g.get("standards", [])], "calculators": [k["slug"] for k in g.get("calculators", [])], "confusions": js(g.get("confusions")), "related": js(g.get("related")), }) tables["glossary"] = glossary # ---------------------------------------------------------------- standards register std = load("standards.json") tables["standards_codes"] = [{ "code_id": c["id"], "body": c["body"], "title": c["title"], "abbreviations": c.get("abbreviations") or [], "governs": c.get("governs"), "region": c.get("region"), "published_editions": c.get("publishedEditions") or [], "cycle": c.get("cycle"), } for c in std["codes"]] tables["standards_bodies"] = [{"body_id": b["id"], "abbreviation": b.get("abbreviation"), "name": b["name"], "role": b.get("role")} for b in std["bodies"]] citations = [] standard_pages = 0 for body in sorted(os.listdir(RAW / "standards")): for name in sorted(os.listdir(RAW / "standards" / body)): p = load(f"standards/{body}/{name}") standard_pages += 1 for section, calcs in (p.get("sections") or {}).items(): for k in calcs: citations.append({"body": p["body"], "standard_id": p["id"], "standard_title": p["title"], "section": section, "calculator_slug": k["slug"], "page": p["page"]}) tables["standards_citations"] = citations # ---------------------------------------------------------------- corrections tables["corrections"] = [{ "correction_id": c["id"], "found": c.get("found"), "found_by": c.get("foundBy"), "title": c.get("title"), "wrong": c.get("wrong"), "correct": c.get("correct"), "prevention": c.get("prevention"), "prevented_by": js(c.get("preventedBy")), "affected": js(c.get("affected")), "url": c.get("url"), } for c in load("corrections.json")["corrections"]] # ---------------------------------------------------------------- CraftQuantities-Bench def fmt(x): if isinstance(x, float) and x.is_integer(): x = int(x) return str(x) def describe_value(spec, value): if spec is None: return fmt(value), None if spec["type"] == "select": opts = spec.get("options") or [] if not opts and spec.get("optionsBySystem"): opts = spec["optionsBySystem"].get("metric") or next(iter(spec["optionsBySystem"].values())) label = next((o["label"] for o in opts if str(o["value"]) == str(value)), None) return (f'"{value}" ({label})' if label and label != str(value) else f'"{value}"'), None if spec.get("dimension"): unit = base_symbol.get(spec["dimension"]) return f"{fmt(value)} {unit}" if unit else fmt(value), unit return fmt(value), None bench = [] for v in vectors: c = calc_files[v["slug"]] specs = {i["id"]: i for i in c["inputs"]} given = json.loads(v["inputs"]) described, lines = [], [] for i in c["inputs"]: from_caller = i["id"] in given value = given[i["id"]] if from_caller else i.get("defaultValue") shown, unit = describe_value(i, value) described.append({"id": i["id"], "label": i["label"], "value": js(value), "unit": unit, "from": "vector" if from_caller else "default"}) lines.append(f"- {i['label']} [{i['id']}]: {shown}" + ("" if from_caller else " (the calculator's default)")) method = "\n".join(f"- {s['label']}" for s in c["sources"]) question = ( f"Craft Quantities calculator: {c['title']}.\n{c['description']}\n\n" f"Inputs (a dimensioned value is given in its dimension's base unit, printed after it; volume is in litres):\n" + "\n".join(lines) + "\n\n" f"Method notes from the calculator's sources:\n{method}\n\n" f"What is the calculator's headline result for these inputs, in {v['unit']}? Answer with one number in {v['unit']}." ) bench.append({ "id": v["vector_id"], "slug": v["slug"], "calculator_title": c["title"], "category": c["category"], "vector_name": v["name"], "question": question, "inputs": v["inputs"], "inputs_described": described, "expected_value": v["expected"], "expected_unit": v["unit"], "tolerance_decimal_places": v["tolerance_decimal_places"], "abs_tolerance": v["abs_tolerance"], "basis": v["basis"], "confidence": v["confidence"], "calculator_url": c["url"], }) tables["bench"] = bench # ---------------------------------------------------------------- write (OUT / "data").mkdir(parents=True, exist_ok=True) (OUT / "jsonl").mkdir(parents=True, exist_ok=True) def sha256(path): h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() files = [] for name, rows in tables.items(): jl = OUT / "jsonl" / f"{name}.jsonl" with open(jl, "w", encoding="utf-8", newline="\n") as fh: for r in rows: fh.write(json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n") pt = OUT / "data" / f"{name}.parquet" pq.write_table(pa.Table.from_pylist(rows), pt, compression="zstd") for p in (jl, pt): files.append({"path": p.relative_to(OUT).as_posix(), "table": name, "rows": len(rows), "bytes": p.stat().st_size, "sha256": sha256(p)}) counts = index["counts"] excluded_rows = ref_total_rows_published - len(ref_rows) checks = [ ("calculators", counts["calculators"], len(calculators)), ("test vectors (validationVectors)", counts["validationVectors"], len(vectors)), ("bench items = test vectors", counts["validationVectors"], len(bench)), ("reference tables published", counts["referenceTables"], len(ref_tables) + len(EXCLUDED_TABLES)), ("reference rows published", counts["referenceRows"], ref_total_rows_published), ("reference rows shipped + excluded", counts["referenceRows"], len(ref_rows) + excluded_rows), ("glossary concepts", counts["glossaryConcepts"], len(glossary)), ("corrections", counts["corrections"], len(tables["corrections"])), ("code families", counts["codeFamilies"], len(tables["standards_codes"])), ("standards bodies", counts["standardsBodies"], len(tables["standards_bodies"])), ("standard pages", counts["standardPages"], standard_pages), ("unit dimensions", counts["dimensions"], len(units_doc["dimensions"])), ("formulas (formulas/index.json)", sum(len(f["formulas"]) for f in fidx["families"]), len(formulas)), ] manifest = { "name": "Craft Quantities open data", "benchmark": "CraftQuantities-Bench", "version": VERSION, "date": DATE, "engine_version": VERSION, "site_commit": SOURCE_COMMIT, "source": "https://craftquantities.com/api/v1/ and https://craftquantities.com/formulas/", "licence": "CC BY 4.0", "licence_url": "https://creativecommons.org/licenses/by/4.0/", "attribution": "Craft Quantities — craftquantities.com", "excluded": [{"table": k, "rows": excluded_rows, "reason": r} for k, r in EXCLUDED_TABLES.items()], "aisc_derived_rows": sum(1 for r in ref_rows if r["derived_from_aisc"]), "counts": {k: len(v) for k, v in tables.items()}, "api_count_checks": [{"what": w, "api": a, "dataset": d, "match": a == d} for w, a, d in checks], "files": files, } with open(OUT / "manifest.json", "w", encoding="utf-8", newline="\n") as fh: json.dump(manifest, fh, ensure_ascii=False, indent=2) fh.write("\n") bad = [c for c in manifest["api_count_checks"] if not c["match"]] print(json.dumps(manifest["counts"])) print("count checks:", "ALL MATCH" if not bad else f"MISMATCH {bad}") sys.exit(1 if bad else 0)