Datasets:
Upload 2 files
Browse filesFiles changed (2)
- scripts/build_dataset.pyAdded+384
- scripts/validate_dataset.pyAdded+50
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384#!/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 <raw-dir> <out-dir>
<raw-dir> 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/<slug>.json reference/<table>.json standards/<body>/<id>.json formulas/<family>.json
Writes <out-dir>/data/<table>.parquet, <out-dir>/jsonl/<table>.jsonl and <out-dir>/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 hashlibimport jsonimport osimport sysfrom pathlib import Path
import pyarrow as paimport 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 filebase_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 vectorscalculators, 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
# ---------------------------------------------------------------- formulasformulas = []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
# ---------------------------------------------------------------- unitsunits = []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 = 0for 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
# ---------------------------------------------------------------- glossaryglossary = []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 registerstd = 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 = 0for 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
# ---------------------------------------------------------------- correctionstables["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-Benchdef 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env python3"""Validate a built dataset folder: every Parquet file reads back with the same rows as its JSONL twin, checksums matchthe manifest, and the test vectors equal the site's validation corpus (validation.json) one for one.
python validate_dataset.py <dataset-dir> <raw-dir>"""import hashlibimport jsonimport sysfrom pathlib import Path
import pyarrow.parquet as pq
DS, RAW = Path(sys.argv[1]), Path(sys.argv[2])manifest = json.loads((DS / "manifest.json").read_text(encoding="utf-8"))problems = []
for f in manifest["files"]: p = DS / f["path"] if hashlib.sha256(p.read_bytes()).hexdigest() != f["sha256"]: problems.append(f"checksum {f['path']}") if p.suffix == ".parquet": t = pq.read_table(p) jl = [json.loads(line) for line in (DS / "jsonl" / f"{f['table']}.jsonl").read_text(encoding="utf-8").splitlines() if line] if t.num_rows != f["rows"] or len(jl) != f["rows"]: problems.append(f"rows {f['table']}: parquet {t.num_rows}, jsonl {len(jl)}, manifest {f['rows']}") # the first and last rows read back identically from both formats back = t.to_pylist() for i in {0, len(jl) - 1}: if back[i] != jl[i]: problems.append(f"row {i} of {f['table']} differs between parquet and jsonl") print(f"read back {f['path']}: {t.num_rows} rows, {t.num_columns} columns")
validation = json.loads((RAW / "validation.json").read_text(encoding="utf-8"))site = {}for c in validation["calculators"]: for pos, v in enumerate(c["vectors"]): site[f"{c['slug']}#{pos}"] = vvecs = [json.loads(line) for line in (DS / "jsonl" / "test_vectors.jsonl").read_text(encoding="utf-8").splitlines() if line]if len(site) != len(vecs) or len(site) != validation["vectorCount"]: problems.append(f"vector count: dataset {len(vecs)}, validation.json {len(site)} / {validation['vectorCount']}")for v in vecs: s = site.get(v["vector_id"]) if s is None or s["expected"] != v["expected"] or s["unit"] != v["unit"] or s["inputs"] != json.loads(v["inputs"]) or s.get("toleranceDecimalPlaces") != v["tolerance_decimal_places"]: problems.append(f"vector {v['vector_id']} differs from validation.json")print(f"test vectors vs validation.json: {len(vecs)} compared")bad_counts = [c for c in manifest["api_count_checks"] if not c["match"]]print("api count checks:", "all match" if not bad_counts else bad_counts)print("PROBLEMS:", problems if problems else "none")sys.exit(1 if problems or bad_counts else 0)scripts/build_dataset.pyAdded+384
scripts/validate_dataset.pyAdded+50