diff --git a/docs/benchmarks/cadgenbench.md b/docs/benchmarks/cadgenbench.md new file mode 100644 index 0000000..c28188f --- /dev/null +++ b/docs/benchmarks/cadgenbench.md @@ -0,0 +1,414 @@ +# Measuring ShapeItUp on CADGenBench + +**Status:** Investigation · **Date:** 2026-10-22 · **Nothing was submitted to the leaderboard.** + +ShapeItUp presents itself as AI-agent-grade CAD but has no published benchmark +numbers. This note covers what it would take to put it on +[CADGenBench](https://huggingface.co/spaces/HuggingAI4Engineering/CADGenBench), +what runs locally today, and the first local results. + +## TL;DR + +- **Generation (49 of 81 fixtures) works today.** ShapeItUp's STEP export passes + the official validity gate. The runner in [`scripts/cadgenbench/`](../../scripts/cadgenbench/) + fetches fixtures, drives Claude + the ShapeItUp MCP server, and scores the output + with the official `cadgenbench` scorer. The `claude -p` step is wired up but + not yet verified end to end ([§4.3](#43-what-was-verified-end-to-end)). +- **Editing (32 of 81) is blocked.** ShapeItUp cannot import a STEP file. Because + the leaderboard score is a plain mean over all 81 fixtures, a generation-only + submission can reach at most 49/81 = **0.605**, even with perfect parts. +- **Local scores are proxies, not leaderboard numbers.** The ground truth is in a + private dataset that only the leaderboard Space reads. The runner scores against + the best public candidate for each fixture instead, and calibrates that proxy + against submissions whose official scores are known (see [§4](#4-local-results)). +- **The brief's competitor numbers are out of date.** See [§1.5](#15-where-the-leaderboard-stands). + The best validated row now scores **0.830** (build123d-mcp 0.3.85 + Claude Opus + 5.5, max effort), and the top unvalidated row scores 0.848. + +- **First local numbers: 2 fixtures, both valid, mean proxy CAD score 0.889** + (105: 0.964, 121: 0.814). build123d-mcp + Opus 5.5 (max) scores 0.902 on the + same fixtures and proxy, and Godela 0.969. So ShapeItUp sits just behind the + validated leader on shape accuracy, from a two-fixture sample with no + variance estimate. **These runs were driven by a Claude subagent inside the + investigating session, not by `claude -p`**, because the `claude` CLI on this + Mac is not logged in ([§4.2](#42-shapeitup-on-two-fixtures)). +- **The proxy is trustworthy on the shape axis.** Scored against it, the two + validated rows reproduce their official shape scores within ±0.004 on 8 of 8 + points. Fixture 149 is an exception: the official alignment appears to fail + there for both leaders. + +--- + +## 1. What CADGenBench is + +Sources: [github.com/huggingface/cadgenbench](https://github.com/huggingface/cadgenbench) +at `33304cf` (the scorer source is identical to `8ae1432`, the commit the +leaderboard's eval image pins), the +[inputs dataset card](https://huggingface.co/datasets/HuggingAI4Engineering/cadgenbench-data), +the [submissions dataset](https://huggingface.co/datasets/HuggingAI4Engineering/cadgenbench-submissions) +at revision `7e005a6`, and the leaderboard Space's own `submit.py` and the +`cadgenbench-eval-gpu` Dockerfile. + +### 1.1 Tasks and inputs + +81 fixtures form a single evaluation set with no train/test split. The part +geometry comes from Mecado. + +| Task | Fixtures | Input | Expected output | +|---|---|---|---| +| Generation | 49 (`101`–`150`) | `description.yaml` (always "Reproduce the geometry as accurately as possible from the drawing") + one A2 engineering drawing `input.png` (3072×2118; three fixtures add `input2.png`) with orthographic views, a section, a detail view and isometrics | `output.step` | +| Editing | 32 (`201`–`250`) | `input.step` (the starting solid), a one-sentence `edit_description.txt` such as *"bring their walls … inward by 6mm"*, a trusted mesh sidecar, and four renders | `output.step` | + +The output contract is identical for both tasks: one STEP (or BREP) per fixture. +The benchmark does not care which tool made the file. + +### 1.2 Scoring + +1. **Validity gate (hard).** The STEP must pass `BRepCheck_Analyzer`, every shell + must be closed, and the tessellation must be a closed, orientable 2-manifold. + Files over 50 MB are rejected unread. Any failure means `cad_score = 0`. +2. The candidate is **aligned rigidly** to the ground truth (rotation and + translation only, never scale). The aligner tries the 24 octahedral PCA poses + with ICP. The docs recommend a canonical pose: bbox centre at the origin, + with extents ordered so that X ≥ Y ≥ Z. +3. Three metrics, each in [0, 1]: + - **Shape similarity:** the mean of surface-distance F1 and volume IoU. + - **Interface match:** authored keep-in and keep-out sub-volumes ("jigs") for + mating features such as bolt patterns, bores and slots. Each mating group + scores as its worst feature. + - **Topology match:** Betti numbers (bodies, through-holes, voids), with the + per-axis scores multiplied together. +4. **Generation:** `cad_score = 0.4·shape + 0.4·interface + 0.2·topology`. An axis + that is missing (for example, no jigs) drops out and the remaining weights + are renormalised. + **Editing:** shape is renormalised against the no-op (`input.step` unchanged) + and then `0.6·shape + 0.3·interface + 0.1·topology`. Submitting the no-op + therefore caps at 0.4. +5. **Aggregate:** a plain mean over all 81 fixtures, with missing outputs counted + as 0. Checked against a published row: build123d-mcp r2's 81 per-sample + scores average to exactly its 0.8298 headline. + +### 1.3 How submissions are run and validated + +- **Upload:** a zip with one `/output.step` per fixture plus a root + `meta.json` (`submitter_name`, `submission_name`, `agent_url`, `notes`, + `agree_to_publish`). It goes through the Space's Submit tab, behind a Hugging + Face login. +- **Evaluation:** an HF Job on `a10g-large` with a 30-minute timeout, running + the `cadgenbench-eval-gpu` image (`cadgenbench@8ae1432`, `pyvista==0.48.4`). + The original zip, the per-sample `result.json` and the HTML report are + published to the submissions dataset. +- **Validation tiers:** every row publishes as **unvalidated**. Moving to + **validated** is a manual methodology review: you email the maintainers + (address in `docs/benchmark/validation.md`) with your evidence. 25 of 756 + rows are validated today. +- **What tool-augmented entries provide**, using build123d-mcp + ([pzfreo/cadgenbench-build123d](https://github.com/pzfreo/cadgenbench-build123d)) + as the model: a public harness pinned by commit as `agent_url`, generic + per-task prompts with no fixture-specific content, a dev/test fixture split + for prompt tuning, an exact MCP server version, the model and reasoning effort + disclosed in `notes`, and per-fixture session logs committed for audit. The + agent is `claude -p` with `--mcp-config --strict-mcp-config` and a curated + `--allowedTools` list of 17–20 MCP tools, plus `Read` and `Bash` for zooming + into the drawing. +- **There is no local scoring against the real ground truth.** The submissions + log shows build123d-mcp using the Space itself as a scorer: dozens of smoke + and partial submissions (`…-SMOKE10`, `…-sample6-r1`) appear as public rows. + +### 1.4 Licences + +| Asset | Licence | Consequence for us | +|---|---|---| +| Benchmark code and scorer | Apache-2.0 | Free to run and adapt. | +| Inputs dataset | ODC-BY 1.0. The card calls it "a benchmark input set, not a training corpus". Every drawing also carries "Copyright © Mecado Inc. 2026 / © Hugging Face, Inc. 2026 All rights reserved" | Use for evaluation, with attribution. **Do not commit drawings or STEP inputs to this repo**: the runner downloads them at run time. Do not train on them. | +| Submissions dataset (other entrants' STEP files and scores) | CC-BY-4.0 | Usable as proxy ground truth, with attribution. Not committed here either. | +| Ground truth | Private | Only the Space reads it. | + +### 1.5 Where the leaderboard stands + +From the submissions dataset at revision `7e005a6` (22 Oct 2026; 756 rows from +140 submitters): + +| Row | Overall | Generation | Editing | Tier | +|---|---:|---:|---:|---| +| deeprd-v2 | 0.848 | 0.893 | 0.779 | unvalidated | +| Arikan Siemens NX MCP + Opus 5.5 | 0.835 | 0.865 | 0.790 | unvalidated | +| **build123d-mcp 0.3.85 + Opus 5.5 (max) r2** | **0.830** | **0.869** | **0.770** | **validated** | +| **Godela** | **0.811** | **0.845** | **0.760** | **validated** | +| build123d-mcp 0.3.81 + Opus 5 (xhigh) r6 | 0.639 | 0.596 | 0.706 | validated (7 Aug) | +| HF baseline, build123d + Claude Opus 4.8 | 0.345 | 0.274 | 0.454 | validated | + +The figures in the brief are **generation** scores, not overall scores. +build123d-mcp's "59.6%" is the 0.596 generation score of its 7 August run (overall +0.639). Godela's "84.5%" is its generation score (overall 0.811). Since then, +build123d-mcp has moved to 0.830 overall and 0.869 on generation. + +--- + +## 2. Requirements against ShapeItUp + +| Benchmark needs | ShapeItUp today | Gap | +|---|---|---| +| Read a dimensioned drawing | Done by the agent, not the tool: Claude reads the PNG, and `sips` crops let it zoom into small callouts | None | +| Build an accurate solid from many features | Replicad sketches, extrude/revolve/loft/sweep, booleans, fillets, shells, and the stdlib; `get_api_reference` | Nothing blocking on the two drawings tried. Accuracy was limited by ambiguous callouts, inspection (gap 3) and two opaque WASM boolean failures (§4.2) | +| Check dimensions while building | `get_render_status` / `verify_shape` (bbox; volume only through `export_shape { bom: true }`, see §4.2), `describe_geometry` (faces, edges), `render_preview` + `get_preview` (4-view PNG) | No **cross-section** view or clip plane over MCP. `render_preview` has none, although the browser viewer does | +| Pass the validity gate | `BRepCheck_Analyzer` and a shell count run on every render (`core/src/validate.ts`); a test plate exported by ShapeItUp passed the official gate | No **gate-equivalent check**: free-edge (watertight) test, closed/manifold/orientable mesh test at the scorer's deflection, 50 MB size check | +| Export STEP to a given path | `export_shape { format: "step", outputPath }` | None | +| Headless, scriptable runs | The MCP server runs standalone in Node, and `claude -p --mcp-config` drives it | Isolation is by convention. The server resolves relative paths against whichever VS Code window last wrote a heartbeat, so the runner gives it a private `$HOME` | +| **Import `input.step` (editing)** | Replicad has `importSTEP(blob)`, but it is **async**, and the executor calls `main()` synchronously. The sandbox also has no file access | **Missing.** This blocks all 32 editing fixtures | +| Locate the faces an edit names ("walls of the four pockets") | `describe_geometry` and `preview_finder` work on any executed shape | No **feature recognition** (holes, hole patterns, pockets, bosses). build123d-mcp's editing gains came from recognisers | +| Apply local edits (offset or move faces, remove a feature) | Booleans, fillets, shells | No face-level edit ops. The bundled OpenCascade WASM lacks `BRepAlgoAPI_Defeaturing` and `ShapeFix_Shape`. It does have `BRepOffsetAPI_MakeThickSolid`, `BRepOffsetAPI_MakeOffsetShape` and `BRepBuilderAPI_Sewing` | + +### Gaps, sized + +| # | Gap | Unblocks | Rough size | +|---|---|---|---| +| 1 | **STEP import.** Add an esbuild `binary` loader for `.step`/`.stp` in `shared/bundle-spec.ts`, so `import part from "./input.step"` inlines the bytes on every host (VS Code, serve, MCP). Then add a **synchronous** stdlib `importStep(bytes)`. Replicad's `importSTEP` is async only because of `await blob.arrayBuffer()`; the `FS.writeFile` → `STEPControl_Reader` → `cast` body is synchronous, so the helper is about 20 lines. Add tests and skill docs. | Editing task (32 fixtures, up to 0.395 of the aggregate) | **S, about 1 day** | +| 2 | **Gate-parity check tool.** A `check_validity` tool, or a `verify_shape` check, that mirrors `cadgenbench/common/validity.py`: BRepCheck, no free edges, closed/manifold/orientable mesh at the scorer's deflection, file size. | Cheap insurance against score-zero fixtures | **S, about 1 day** | +| 3 | **Inspection over MCP.** A clip plane on `render_preview`, or a `cross_section` tool that reports loops and area at a given plane, and a working `cameraAngle` (single enlarged views, bottom view) in the headless renderer. | Generation fidelity on stepped, cored and two-sided parts | **S–M, 1–2 days** | +| 4 | **Face-level edit helpers.** Offset or move selected faces with `MakeOffsetShape`/`MakeThickSolid`, and remove or fill a pocket with booleans, since defeaturing is not in the WASM build. | Editing quality beyond the no-op | **M, 2–4 days**. A custom OpenCascade WASM build with defeaturing would be L | +| 5 | **Feature recognition.** Holes, hole patterns, pockets and bosses on imported solids, built on `describe_geometry` data. | Editing quality | **M–L, 3–5 days** | +| 6 | **Full-run tooling.** Retries, resume, and a packager that writes the 81-folder zip and `meta.json` (the runner stops before packaging on purpose). | An actual submission | **S, under 1 day** | + +Gap 1 alone moves the generation-only ceiling from 0.605 to a full 81-fixture +score. Gaps 4–5 decide how far editing climbs above the 0.4 no-op floor. + +--- + +## 3. The local runner + +[`scripts/cadgenbench/`](../../scripts/cadgenbench/) contains: + +- `setup.sh` builds a Python 3.12 venv with the official scorer, pinned to the + leaderboard's eval image: `cadgenbench@8ae1432`, `pyvista==0.48.4`, and every + dependency resolved with `--exclude-newer 2026-06-27`. **The date pin matters.** + An unpinned install gets build123d 0.13 / OCP 8, whose `Bnd_Box` binding breaks + `analyze_step`, so every candidate, valid or not, fails the gate. +- `cgb.py fetch ` downloads the fixture inputs and builds the **proxy ground + truth**: the best publicly scored candidate for each fixture. It is used only + if its official score is at least 0.95, and its provenance goes into + `gt//proxy.json`. Editing fixtures are skipped. +- `cgb.py run --run ` runs `claude -p` in a fresh work dir per fixture. + It uses this checkout's MCP server (`packages/mcp-server/dist`) with a private + `$HOME`, `--strict-mcp-config`, an allow-list of 17 ShapeItUp tools plus `Read` + and `Bash(sips:*)`, and `--permission-mode dontAsk`. It records cost, turns, + tool calls and wall time to `agent.json`. +- `cgb.py score ` runs `cadgenbench evaluate` against the proxy and writes + a `summary.md`. That file shows the proxy score, shape, F1, IoU and topology + next to the official scores of the two validated reference rows on the same + fixtures. +- `cgb.py calibrate ` scores a public submission's files + against the proxy, so its proxy and official scores sit side by side. +- `prompt_generation.md` is the generic generation prompt. It contains no + fixture-specific content. + +Everything goes to `$CGB_HOME` (default `~/.cache/shapeitup-cadgenbench`), +outside the repo. Nothing in the runner uploads anything. + +```bash +scripts/cadgenbench/setup.sh +PY=~/.cache/shapeitup-cadgenbench/venv/bin/python +pnpm build:mcp +$PY scripts/cadgenbench/cgb.py fetch 105 117 121 145 149 +$PY scripts/cadgenbench/cgb.py run --run opus55-r1 --effort xhigh 105 117 121 145 149 +$PY scripts/cadgenbench/cgb.py score opus55-r1 +``` + +**What the proxy measures.** It measures shape similarity and topology against +another entrant's near-perfect part (official 0.990–0.999 on these fixtures). It +cannot measure interface match: the jigs are private. The proxy CAD score is +therefore `(0.4·shape + 0.2·topology) / 0.6`, against a reference that is itself +slightly off. Use it to rank attempts against each other and against the +calibration rows, never as a leaderboard number. + +--- + +## 4. Local results + +All runs were on 22 Oct 2026 on an Apple-silicon Mac, with fixtures 105, 117, +121, 145 and 149 and proxy ground truth from `deeprd` (official 0.990–0.999 on +these five). The five span easy (105: median public score 0.79) to hard (145: +median 0.23). + +### 4.1 Does the proxy track the official scorer? + +The two validated reference rows were scored against the proxy with +`cgb.py calibrate`. Their official per-axis numbers come from the public +per-submission reports on the Space. + +| Fixture | build123d-mcp shape, proxy / official | Godela shape, proxy / official | build123d-mcp CAD, proxy / official | Godela CAD, proxy / official | +|---|---|---|---|---| +| 105 | 0.962 / 0.961 | 0.983 / 0.982 | 0.975 / 0.985 | 0.988 / 0.993 | +| 117 | 0.903 / 0.901 | 0.978 / 0.974 | 0.936 / 0.943 | 0.985 / 0.976 | +| 121 | 0.744 / 0.742 | 0.925 / 0.926 | 0.829 / 0.883 | 0.950 / 0.949 | +| 145 | 0.966 / 0.969 | 0.960 / 0.961 | 0.977 / 0.965 | 0.974 / 0.961 | +| 149 | 0.919 / **0.495** | 0.990 / **0.501** | 0.946 / **0.425** | 0.993 / **0.429** | + +- **On 105–145, the proxy's shape axis matches the official one to within + ±0.004 on all 8 points.** Topology matched exactly everywhere (Betti numbers + are identical). The proxy CAD score differs from the official one only by the + missing interface term: −0.054 to +0.013, and it never reorders the two + systems. +- **149 is a scorer outlier, not a proxy error.** Godela's part agrees with + deeprd's 0.992 part to surface F1 0.984 and IoU 0.996, and the bounding boxes + agree to 0.6 mm. Yet officially it scores IoU 0.697, F1 0.305 and interface + 0.071, and build123d-mcp's part fails the same way. Volume IoU that low + between near-identical solids points to the official alignment settling on a + wrong pose against the private ground truth. Whatever the cause, the proxy + cannot reproduce it. **Proxy means below therefore exclude 149, and 149 is + reported on its own.** This may be worth raising upstream, but that is the + user's call (see §6). + +### 4.2 ShapeItUp on two fixtures + +> **How these runs were driven. Read this before the numbers.** They did **not** +> go through `cgb.py run` / `claude -p`: the `claude` CLI on this Mac is not +> logged in, and `cgb.py run` stops at authentication (its MCP wiring was +> checked up to that point; see §4.3). Instead, each fixture ran as a Claude +> Code **subagent inside the investigating session**: Claude Opus 5.5 at the +> session's default effort. It got the same rendered `prompt_generation.md` and +> the same tool limits (`Read`, `sips` crops, `mcp__shapeitup__*` only). The +> MCP server was the **session's** ShapeItUp server, a local build from +> 2026-09-23 (about 1.29.x), not this branch's 1.30.1. Each run produced one +> `output.step`, scored with `cgb.py score` exactly like any other run. Two +> fixtures, one attempt each: there is no variance estimate. + +| Fixture | Status | Proxy CAD | Shape (F1 / IoU) | Topology | Agent time | Tool calls | build123d-mcp, proxy / official | Godela, proxy / official | +|---|---|---|---|---|---|---|---|---| +| 105 | valid | **0.964** | 0.946 (0.899 / 0.993) | 1.000 (9 of 9 through-holes) | 13.7 min | 69 | 0.975 / 0.985 | 0.988 / 0.993 | +| 121 | valid | **0.814** | 0.721 (0.491 / 0.951) | 1.000 (17 of 17) | 15.3 min | 62 | 0.829 / 0.883 | 0.950 / 0.949 | +| **Mean** | 2 of 2 valid | **0.889** | 0.834 | 1.000 | 14.5 min | 66 | 0.902 / 0.934 | 0.969 / 0.971 | + +The comparison worth trusting is ShapeItUp's proxy score against the other +two systems' **proxy** scores. They are the same measurement, and §4.1 shows +the proxy's shape axis tracks the official one within ±0.004. + +- **ShapeItUp + Opus 5.5 lands just below build123d-mcp + Opus 5.5 (max + effort) and clearly below Godela** on both fixtures: shape 0.946 vs 0.962 + and 0.983 on 105, and 0.721 vs 0.744 and 0.925 on 121. Both parts are valid, + and the topology is exact on both. +- **What separates them is surface accuracy, not gross form.** IoU is high + everywhere (0.951–0.993). Surface F1 is what drops: 0.491 on 121. The + scorer's tolerance for F1 is 0.5% of the part diagonal, 2.15 mm on 121. The agent's notes match this. It measured the hub + outer diameter off the pixels because it was undimensioned, resolved two + conflicting callouts by choice, and left out the R1 fillets, edge rounds and + boss shapes. +- **No official-score estimate is possible without the interface axis.** If + ShapeItUp's mating features fit as well as build123d-mcp's did (interface + 1.000 / 0.965), the official scores would be about 0.98 / 0.87. If they + missed entirely, about 0.58 / 0.49. Two fixtures say nothing about the + 49-fixture mean either way. +- Agent cost: about 203k and 209k tokens per fixture as reported by the + harness, with no dollar figure (subagent runs are not metered per call). + `cgb.py run` records `total_cost_usd` from `claude -p` once it can run. + +**What the agents reported about ShapeItUp** (fixtures 105 and 121, checked +against this branch where noted): + +- The `get_api_reference` finders section documents `.or(fn)`, but Replicad + has no `or`; it has `.either([fns])`. *Confirmed* in `mcp-server/src/tools.ts`. + `.and(fn)` works only because `core/src/stdlib/finder-patch.ts` patches it, + and nothing patches `.or`. The agent's `try`/`catch` + `console.warn` hid the + failure, because script console output never reaches the tool result. + *Confirmed*: nothing captures it; it goes to the MCP server's stderr. Yet an + engine error hint (`mcp-server/src/engine.ts:2175`) tells agents to "Add + `console.log`". +- `get_render_status` / `verify_shape` / `modify_shape` returned no volume + (both agents). The description of `get_render_status` promises one, but the + default `"bbox"` stats path omits it, and only `export_shape { bom: true }` + (`partStats: "full"`) measures it. *Consistent with the code.* +- Opaque WASM failures. On 105, cutting cavity + recess, then holes + ports, as + two successive booleans threw `OCCT exception (pointer …)`; one fused cut + worked. On 121, the first `create_shape` failed with "memory access out of + bounds" in `_3DShape.cut`, and the identical code then ran cleanly. Both + fixtures shared one long-lived MCP process, so leftover WASM state is a + suspect. Not reproduced here. +- `render_preview` ignores `cameraAngle` and always draws the 4-pane view. + *Confirmed, and deliberate* (comment at `mcp-server/src/tools.ts:4902`). But + it means there is no bottom view and no enlarged single view, which made the + hub side of 121 hard to check. This belongs with gap 3. +- `modify_shape` with no edits returned the previous timestamp and status + (121). Not checked. +- A spurious `Import "sim" will always be undefined` warning on every render. + That warning is **already fixed on this branch** (v1.30.1, `adbf995`); the + stale session build still had it. + +### 4.3 What was verified end to end + +| Step | Status | +|---|---| +| `setup.sh` (pinned scorer env) | ran; build123d 0.11.0, OCP 7.9.3, open3d 0.19.0 | +| `cgb.py fetch` (inputs + proxy GT, editing skipped) | ran on 105, 117, 121, 145, 149 (+ 201 skipped) | +| ShapeItUp STEP through the official validity gate | passed: a test plate via `sanity_check_submission.py`, and both agent outputs via `evaluate` | +| `cgb.py run` | runs to `claude -p` start-up: MCP server `connected`, exactly 17 ShapeItUp tools + `Read` + `Bash` in context. **Stops at "OAuth session expired"** because the CLI is not logged in | +| `cgb.py score` / `calibrate` | ran on 3 runs (2 calibration rows, 1 ShapeItUp run) | + +To finish the end-to-end check once the CLI is logged in (about $5–10): + +```bash +claude auth login +$PY scripts/cadgenbench/cgb.py run --run cli-smoke --effort xhigh 105 +$PY scripts/cadgenbench/cgb.py score cli-smoke +``` + +--- + +## 5. What a full submission would cost + +Measured reference point: the build123d-mcp author's own comparison reports +**about $725 API-equivalent for 79 fixtures with Claude Opus 5 at xhigh effort** +(about $9.20 per fixture), at Opus 5's $5 / $25 per million tokens. Claude Opus +5.5 costs $4 / $20, so the same token volume would be about $7.30 per fixture. +Max effort and retries push this up. + +| Scope | Agent time (4 fixtures in parallel) | API spend, Opus 5.5 (xhigh–max) | Local proxy scoring | Leaderboard scoring | +|---|---|---|---|---| +| 5-fixture smoke (this note) | about 30 min sequential | about $35–60 | about 10 min | n/a | +| 49 generation fixtures | 3–5 h | about $360–550 | about 20 min (4 workers) | free (HF Jobs, ≤30 min) | +| All 81 fixtures (needs STEP import) | 5–8 h | about $590–900 | editing needs a proxy `edit_baseline.json` computed locally (not built yet) | free | +| A validated-tier entry | + one repeat run, for variance | 2× the above | — | free | + +Agent time assumes 13–20 minutes per fixture, which is what §4.2 measured. Add +20–30% for retries: the build123d-mcp history shows several full re-runs +before each headline result. On a Claude subscription instead of an API key, +the dollar cost becomes quota, and long sweeps hit session limits. That is why +the build123d harness carries quota-resume logic. + +What is required before anything goes public: + +1. **The user's approval to submit.** Uploading publishes a row, the zip, every + STEP file, and an HTML report under the submitter's name. +2. **A Hugging Face login** for the Space's Submit tab, and a `meta.json` that + names the system (model, effort, ShapeItUp version, harness commit). +3. **A `claude` CLI login** on the machine that runs `cgb.py run`. On this Mac + `claude auth status` reports `loggedIn: false`, which is why §4.2 ran + through a subagent instead. +4. For the **validated** tier: a public harness at a pinned commit, plus logs, + sent to the maintainers for review. + +--- + +## 6. Recommendations + +1. **Implement STEP import first (gap 1, about 1 day).** It is the only thing + standing between ShapeItUp and a full 81-fixture submission. Without it, + the best possible aggregate is 0.605, which would sit far down a table where + 0.83 is the validated top. +2. **Then add the gate-parity check and better inspection (gaps 2–3, 2–3 days)**, + and run all 49 generation fixtures locally against the proxy. That costs + about $360–550 at Opus 5.5 and gives a stable number to compare against the + reference rows' official generation scores. +3. **Fix the tool friction the agent hit (under a day):** make finder `.or(fn)` + work, either by patching it like `.and` or by documenting `.either([...])`; + report volume from `get_render_status` as its description promises; and + make `console.warn` output from a shape script reach the tool result. +4. **Emit the canonical pose** (bbox centred, X ≥ Y ≥ Z) in the prompt or in a + stdlib helper. Fixture 149 shows how much the official alignment can cost + a correct part. +5. **Submit only after 1–2, and only with the user's go-ahead.** A first upload + can be generation plus editing at the no-op floor, if that is disclosed in + `notes`, but a real editing attempt (gaps 4–5) is what would make the number + competitive. +6. **Things not done here that need the user's decision:** uploading anything to + the Space, emailing the maintainers about validation, and reporting the + fixture-149 alignment anomaly upstream. diff --git a/scripts/cadgenbench/cgb.py b/scripts/cadgenbench/cgb.py new file mode 100755 index 0000000..af6583c --- /dev/null +++ b/scripts/cadgenbench/cgb.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python3 +"""Local CADGenBench runner for ShapeItUp. + +Drives Claude Code + the ShapeItUp MCP server on CADGenBench generation +fixtures, then scores the STEP outputs with the official `cadgenbench` scorer. + +The official ground truth is private, so local scores use a PROXY ground +truth: for each fixture, the best publicly scored candidate in the +leaderboard's submissions dataset (CC-BY-4.0). The proxy has no interface +jigs, so the scorer's interface axis drops out and its weight is redistributed +over shape (0.4) and topology (0.2). Read docs/benchmarks/cadgenbench.md +before quoting any number from here. + + scripts/cadgenbench/setup.sh # once: scorer venv + PY=~/.cache/shapeitup-cadgenbench/venv/bin/python + $PY scripts/cadgenbench/cgb.py fetch 105 117 # inputs + proxy GT + $PY scripts/cadgenbench/cgb.py run --run r1 105 117 + $PY scripts/cadgenbench/cgb.py score r1 + $PY scripts/cadgenbench/cgb.py calibrate 105 117 + +Needs `pnpm build:mcp` first (the runner uses this checkout's MCP server). +Nothing here uploads anything: submitting to the leaderboard is a manual step. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import zipfile +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parent.parent +CGB_HOME = Path(os.environ.get("CGB_HOME", Path.home() / ".cache" / "shapeitup-cadgenbench")) +DATA = CGB_HOME / "data" # laid out as CADGENBENCH_DATA_DIR expects: inputs/ + gt/ +RESULTS = CGB_HOME / "results" +WORK = CGB_HOME / "work" + +DATA_REPO = "HuggingAI4Engineering/cadgenbench-data" +SUBMISSIONS_REPO = "HuggingAI4Engineering/cadgenbench-submissions" + +# Public, manually validated rows shown next to every local result. Their +# scores are OFFICIAL (real GT, interface axis included), so they are context, +# not a like-for-like comparison: use `calibrate` for that. +REFERENCES = { + "build123d-mcp+Opus5.5": "pzfreo_build123d-mcp-0-3-85-mcp-server-claude-o_20260924-101549", + "Godela": "godela_godela_20260915-045120", +} + +# Fixtures where the official score disagrees with the proxy for reasons the +# proxy cannot see. 149: Godela's and build123d-mcp's parts match the 0.992 +# proxy to IoU ~0.99, but score IoU ~0.70 officially (see the report, §4.1). +SCORER_OUTLIERS = {"149"} + +SHAPEITUP_TOOLS = [ + "create_shape", "modify_shape", "read_shape", "open_shape", "list_shapes", + "delete_shape", "validate_syntax", "preview_shape", "tune_params", + "get_api_reference", "render_preview", "get_preview", "get_render_status", + "preview_finder", "verify_shape", "describe_geometry", "export_shape", +] +# Assembly, viewer and simulation tools: irrelevant to a single-part drawing, +# so they are removed from the agent's context rather than merely unapproved. +SHAPEITUP_HIDDEN = [ + "check_collisions", "check_stack", "clear_params", "close_viewer", + "list_installed_apps", "open_viewer", "run_simulation", "set_render_mode", + "setup_shape_project", "sweep_check", "toggle_dimensions", "validate_joints", +] + + +# -------------------------------------------------------------------------- +# fetch +# -------------------------------------------------------------------------- + + +def cmd_fetch(args: argparse.Namespace) -> int: + from huggingface_hub import HfApi, snapshot_download + + api = HfApi() + data_rev = api.dataset_info(DATA_REPO).sha + sub_rev = api.dataset_info(SUBMISSIONS_REPO).sha + snap = Path(snapshot_download( + DATA_REPO, repo_type="dataset", revision=data_rev, + allow_patterns=[f"{s}/*" for s in args.samples], + )) + rows = _download_leaderboard(sub_rev) + + for sample in args.samples: + src = snap / sample + if not (src / "description.yaml").exists(): + print(f"{sample}: not in {DATA_REPO}", file=sys.stderr) + continue + if _task_type(src) == "editing": + print(f"{sample}: editing fixture, skipped (ShapeItUp cannot import STEP yet)") + continue + dst = DATA / "inputs" / sample + shutil.rmtree(dst, ignore_errors=True) + shutil.copytree(src, dst) + + best = _best_public_candidate(rows, sample) + if best is None or best["cad_score"] < args.min_proxy_score: + got = "none" if best is None else f"{best['cad_score']:.3f}" + print(f"{sample}: best public candidate {got} < {args.min_proxy_score}; no proxy GT, cannot score") + continue + gt = DATA / "gt" / sample + gt.mkdir(parents=True, exist_ok=True) + _extract_candidate(best["submission_id"], sample, gt / "ground_truth.step", sub_rev) + (gt / "proxy.json").write_text(json.dumps({ + "proxy_for": "private ground truth (HuggingAI4Engineering/cadgenbench-data-gt)", + "source_submission": best["submission_id"], + "source_submission_name": best["submission_name"], + "source_official_cad_score": best["cad_score"], + "submissions_revision": sub_rev, + "license": "CC-BY-4.0 (cadgenbench-submissions)", + }, indent=2)) + print(f"{sample}: inputs + proxy GT from {best['submission_name']!r} (official {best['cad_score']:.3f})") + + (DATA / "revisions.json").write_text(json.dumps( + {"data": data_rev, "submissions": sub_rev, "fetched_at": _now()}, indent=2, + )) + return 0 + + +def _download_leaderboard(revision: str) -> list[dict]: + from huggingface_hub import hf_hub_download + + path = hf_hub_download(SUBMISSIONS_REPO, "results.jsonl", repo_type="dataset", revision=revision) + DATA.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, DATA / "results.jsonl") + return _leaderboard() + + +def _leaderboard() -> list[dict]: + path = DATA / "results.jsonl" + if not path.exists(): + sys.exit("No leaderboard snapshot; run `cgb.py fetch` first.") + return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + + +def _best_public_candidate(rows: list[dict], sample: str) -> dict | None: + best = None + for row in rows: + if row.get("status") != "completed": + continue + entry = (row.get("per_sample_scores") or {}).get(sample) or {} + score = entry.get("cad_score") + if entry.get("status") != "valid" or score is None: + continue + if best is None or score > best["cad_score"]: + best = {"submission_id": row["submission_id"], + "submission_name": row["submission_name"], "cad_score": score} + return best + + +def _extract_candidate(submission_id: str, sample: str, dest: Path, revision: str) -> None: + from huggingface_hub import hf_hub_download + + zpath = hf_hub_download( + SUBMISSIONS_REPO, f"submissions/{submission_id}.zip", + repo_type="dataset", revision=revision, + ) + pattern = re.compile(rf"(^|/){re.escape(sample)}/output\.(step|stp)$") + with zipfile.ZipFile(zpath) as z: + names = [n for n in z.namelist() if pattern.search(n)] + if not names: + raise FileNotFoundError(f"{sample}/output.step not in {submission_id}.zip") + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(z.read(names[0])) + + +# -------------------------------------------------------------------------- +# run +# -------------------------------------------------------------------------- + + +def cmd_run(args: argparse.Namespace) -> int: + server = REPO / "packages" / "mcp-server" / "dist" / "index.js" + if not server.exists(): + sys.exit(f"{server} missing; run `pnpm build:mcp` first.") + claude = shutil.which("claude") + if not claude: + sys.exit("`claude` (Claude Code) is not on PATH.") + + run_dir = RESULTS / args.run + run_dir.mkdir(parents=True, exist_ok=True) + template = (HERE / "prompt_generation.md").read_text() + meta = { + "run": args.run, + "model": args.model, + "effort": args.effort, + "timeout_min": args.timeout_min, + "budget_min": args.budget_min, + "shapeitup_commit": _git("rev-parse", "HEAD"), + "shapeitup_dirty": bool(_git("status", "--porcelain")), + "mcp_server_version": json.loads((REPO / "packages/mcp-server/package.json").read_text())["version"], + "claude_version": subprocess.run([claude, "--version"], capture_output=True, text=True).stdout.strip(), + "credential_source": "anthropic-api-key" if os.environ.get("ANTHROPIC_API_KEY") else "claude-subscription", + "prompt_sha256": hashlib.sha256(template.encode()).hexdigest(), + "started_at": _now(), + "samples": args.samples, + } + (run_dir / "run_meta.json").write_text(json.dumps(meta, indent=2)) + + def one(sample: str) -> None: + try: + _run_fixture(sample, args, claude, server, template, run_dir) + except Exception as exc: # one fixture never aborts the sweep + print(f"{sample}: runner error {type(exc).__name__}: {exc}", file=sys.stderr) + + with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as ex: + list(ex.map(one, args.samples)) + return 0 + + +def _run_fixture(sample, args, claude, server, template, run_dir) -> None: + inputs = DATA / "inputs" / sample + if not (inputs / "description.yaml").exists(): + print(f"{sample}: no inputs; run `cgb.py fetch {sample}` first", file=sys.stderr) + return + desc = _description(inputs) + if desc.get("task_type") == "editing": + print(f"{sample}: editing fixture, skipped") + return + + work = WORK / args.run / sample + shutil.rmtree(work, ignore_errors=True) + work.mkdir(parents=True) + images = [f for f in desc.get("input_files", ["input.png"]) if f.endswith(".png")] + for name in images: + shutil.copyfile(inputs / name, work / name) + + # The MCP server picks its storage dir (and the VS Code workspace that + # relative paths resolve against) from $HOME. A private HOME keeps a + # benchmark agent from writing into whatever VS Code window is open. + home = work / ".home" + home.mkdir() + (work / "mcp.json").write_text(json.dumps({"mcpServers": {"shapeitup": { + "command": shutil.which("node") or "node", + "args": [str(server)], + "env": {"HOME": str(home)}, + }}}, indent=2)) + + output = work / "output.step" + prompt = (template + .replace("{DESCRIPTION}", str(desc.get("description", "")).strip()) + .replace("{WORKDIR}", str(work)) + .replace("{IMAGES}", ", ".join(f"`{n}`" for n in images)) + .replace("{OUTPUT}", str(output)) + .replace("{BUDGET_MIN}", str(args.budget_min))) + (work / "prompt.txt").write_text(prompt) + + cmd = [ + claude, "-p", prompt, + "--model", args.model, + "--output-format", "stream-json", "--verbose", + "--mcp-config", str(work / "mcp.json"), "--strict-mcp-config", + "--tools", "Read,Bash", + "--allowedTools", "Read", "Bash(sips:*)", *[f"mcp__shapeitup__{t}" for t in SHAPEITUP_TOOLS], + "--disallowedTools", *[f"mcp__shapeitup__{t}" for t in SHAPEITUP_HIDDEN], + "--permission-mode", "dontAsk", + "--setting-sources", "local", + "--disable-slash-commands", + "--no-session-persistence", + ] + if args.effort: + cmd += ["--effort", args.effort] + # Load the MCP tool schemas up front instead of behind ToolSearch: the + # toolset is fixed, and deferral only costs the agent lookup turns. + env = {**os.environ, "ENABLE_TOOL_SEARCH": "false"} + + print(f"{sample}: started ({work})", flush=True) + t0 = time.monotonic() + timed_out = False + with open(work / "stream.jsonl", "w") as out, open(work / "stderr.txt", "w") as err: + proc = subprocess.Popen(cmd, cwd=work, env=env, stdout=out, stderr=err, start_new_session=True) + try: + proc.wait(timeout=args.timeout_min * 60) + except subprocess.TimeoutExpired: + timed_out = True + _kill_group(proc) + wall_s = time.monotonic() - t0 + + stats = _stream_stats(work / "stream.jsonl") + dest = run_dir / sample + shutil.rmtree(dest, ignore_errors=True) + (dest / "agent").mkdir(parents=True) + if output.exists(): + shutil.copyfile(output, dest / "output.step") + for f in [*work.glob("*.shape.ts"), work / "prompt.txt", work / "stream.jsonl"]: + shutil.copyfile(f, dest / "agent" / f.name) + agent = {"sample": sample, "exit_code": proc.returncode, "timed_out": timed_out, + "wall_s": round(wall_s, 1), "has_output": output.exists(), **stats} + (dest / "agent.json").write_text(json.dumps(agent, indent=2)) + cost = f"${stats['cost_usd']:.2f}" if stats.get("cost_usd") is not None else "$?" + print(f"{sample}: done in {wall_s / 60:.1f} min, {stats.get('num_turns')} turns, {cost}, " + f"output={'yes' if output.exists() else 'NO'}{' (timed out)' if timed_out else ''}", flush=True) + + +def _kill_group(proc: subprocess.Popen) -> None: + for sig, grace in ((signal.SIGTERM, 15), (signal.SIGKILL, 5)): + try: + os.killpg(proc.pid, sig) + except ProcessLookupError: + return + try: + proc.wait(timeout=grace) + return + except subprocess.TimeoutExpired: + continue + + +def _stream_stats(path: Path) -> dict: + """Cost, turns and tool-call counts from a `claude -p` stream-json log.""" + tools: Counter[str] = Counter() + result: dict = {} + for line in path.read_text().splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if event.get("type") == "assistant": + for block in event.get("message", {}).get("content", []): + if block.get("type") == "tool_use": + tools[block.get("name", "?").removeprefix("mcp__shapeitup__")] += 1 + elif event.get("type") == "result": + result = event + usage = result.get("usage") or {} + return { + "result_subtype": result.get("subtype"), + "is_error": result.get("is_error"), + "num_turns": result.get("num_turns"), + "duration_ms": result.get("duration_ms"), + "cost_usd": result.get("total_cost_usd"), + "usage": {k: usage.get(k) for k in ( + "input_tokens", "output_tokens", + "cache_creation_input_tokens", "cache_read_input_tokens", + )}, + "tool_calls": dict(tools.most_common()), + } + + +# -------------------------------------------------------------------------- +# score / calibrate +# -------------------------------------------------------------------------- + + +def cmd_score(args: argparse.Namespace) -> int: + run_dir = RESULTS / args.run + if not run_dir.is_dir(): + sys.exit(f"No run at {run_dir}") + env = {**os.environ, "CADGENBENCH_DATA_DIR": str(DATA)} + env.pop("CADGENBENCH_DATA_REPO", None) + env.pop("CADGENBENCH_DATA_GT_REPO", None) + scorer = Path(sys.executable).parent / "cadgenbench" + proc = subprocess.run( + [str(scorer), "evaluate", str(run_dir), "--workers", str(args.workers)], env=env, + ) + table = _summary(run_dir) + (run_dir / "summary.md").write_text(table) + print() + print(table) + return proc.returncode + + +def cmd_calibrate(args: argparse.Namespace) -> int: + """Score a public submission's candidates against the proxy GT. + + Puts proxy scores next to the official ones for the same files, which is + the only way to tell how far the proxy drifts from the real leaderboard. + """ + rows = {r["submission_id"]: r for r in _leaderboard()} + row = rows.get(args.submission) + if row is None: + sys.exit(f"{args.submission} not in the leaderboard snapshot") + revision = json.loads((DATA / "revisions.json").read_text())["submissions"] + run = args.run or "ref-" + re.sub(r"[^a-z0-9]+", "-", row["submission_name"].lower()).strip("-")[:48] + run_dir = RESULTS / run + for sample in args.samples: + dest = run_dir / sample + shutil.rmtree(dest, ignore_errors=True) + _extract_candidate(args.submission, sample, dest / "output.step", revision) + (run_dir / "ref.json").write_text(json.dumps({ + "submission_id": args.submission, + "submission_name": row["submission_name"], + "official": {s: (row["per_sample_scores"] or {}).get(s, {}).get("cad_score") for s in args.samples}, + }, indent=2)) + print(f"Calibration run: {run_dir}") + return cmd_score(argparse.Namespace(run=run, workers=args.workers)) + + +def _summary(run_dir: Path) -> str: + rows = {r["submission_id"]: r for r in _leaderboard()} + ref = json.loads((run_dir / "ref.json").read_text()) if (run_dir / "ref.json").exists() else None + head = ["sample", "status", "proxy CAD", "shape", "F1", "IoU", "topo"] + head += ["official (same file)"] if ref else ["agent $", "min", "turns"] + head += [f"{name} (official)" for name in REFERENCES] + lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] + proxy_scores, official_scores, clean_scores = [], [], [] + + for fixture in sorted(d for d in run_dir.iterdir() if d.is_dir()): + result = _read_json(fixture / "result.json") + gt_metrics = result.get("gt_metrics") or {} + topo = (result.get("topology_metrics") or {}).get("score") + cad = result.get("cad_score") + status = result.get("status", "not scored") + if status == "invalid": + reasons = (result.get("validation") or {}).get("topology_errors") or [] + status = "invalid: " + "; ".join(map(str, reasons))[:80] + if cad is not None: + proxy_scores.append(cad) + if fixture.name not in SCORER_OUTLIERS: + clean_scores.append(cad) + name = fixture.name + (" †" if fixture.name in SCORER_OUTLIERS else "") + cells = [name, status, _f(cad), + _f(gt_metrics.get("shape_similarity_score")), + _f(gt_metrics.get("shape_surface_distance_f1")), + _f(gt_metrics.get("shape_volume_iou")), _f(topo)] + if ref: + official = ref["official"].get(fixture.name) + if official is not None: + official_scores.append(official) + cells.append(_f(official)) + else: + agent = _read_json(fixture / "agent.json") + cells += [_f(agent.get("cost_usd"), 2), _f((agent.get("wall_s") or 0) / 60, 1), + _f(agent.get("num_turns"), 0)] + for sid in REFERENCES.values(): + entry = ((rows.get(sid) or {}).get("per_sample_scores") or {}).get(fixture.name) or {} + cells.append(_f(entry.get("cad_score"))) + lines.append("| " + " | ".join(cells) + " |") + + n = len(proxy_scores) + lines.append("") + lines.append(f"Mean proxy CAD score over {n} scored fixtures: {_f(sum(proxy_scores) / n if n else None)}" + " (missing/invalid count as 0).") + if len(clean_scores) != n: + lines.append(f"Excluding † scorer outliers ({len(clean_scores)} fixtures): " + f"{_f(sum(clean_scores) / len(clean_scores) if clean_scores else None)}.") + if ref and official_scores: + lines.append(f"Mean official CAD score of the same files: {_f(sum(official_scores) / len(official_scores))}.") + lines.append("Proxy CAD = (0.4*shape + 0.2*topology) / 0.6 against the best public candidate; " + "the official score also weighs interface match 0.4 against the private GT.") + return "\n".join(lines) + "\n" + + +# -------------------------------------------------------------------------- +# helpers +# -------------------------------------------------------------------------- + + +def _description(fixture_dir: Path) -> dict: + import yaml + + return yaml.safe_load((fixture_dir / "description.yaml").read_text()) or {} + + +def _task_type(fixture_dir: Path) -> str: + return str(_description(fixture_dir).get("task_type") or "generation") + + +def _read_json(path: Path) -> dict: + try: + return json.loads(path.read_text()) + except (OSError, json.JSONDecodeError): + return {} + + +def _f(value, digits: int = 3) -> str: + return "" if value is None else f"{value:.{digits}f}" + + +def _git(*argv: str) -> str: + return subprocess.run(["git", *argv], cwd=REPO, capture_output=True, text=True).stdout.strip() + + +def _now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="cmd", required=True) + + p = sub.add_parser("fetch", help="Download fixture inputs and build proxy ground truth.") + p.add_argument("samples", nargs="+") + p.add_argument("--min-proxy-score", type=float, default=0.95, + help="Only use a public candidate as proxy GT if its official CAD score is at least this.") + p.set_defaults(fn=cmd_fetch) + + p = sub.add_parser("run", help="Run Claude + ShapeItUp MCP on generation fixtures.") + p.add_argument("samples", nargs="+") + p.add_argument("--run", required=True, help="Run name; results go to $CGB_HOME/results/.") + p.add_argument("--model", default="claude-opus-5-5") + p.add_argument("--effort", default=None, help="low|medium|high|xhigh|max (Claude Code --effort).") + p.add_argument("--jobs", type=int, default=2, help="Fixtures run in parallel.") + p.add_argument("--budget-min", type=int, default=20, help="Soft time budget stated in the prompt.") + p.add_argument("--timeout-min", type=int, default=40, help="Hard kill per fixture.") + p.set_defaults(fn=cmd_run) + + p = sub.add_parser("score", help="Score a run with the official scorer against the proxy GT.") + p.add_argument("run") + p.add_argument("--workers", type=int, default=4) + p.set_defaults(fn=cmd_score) + + p = sub.add_parser("calibrate", help="Score a public submission against the proxy GT.") + p.add_argument("submission", help="submission_id from the leaderboard's results.jsonl") + p.add_argument("samples", nargs="+") + p.add_argument("--run", default=None) + p.add_argument("--workers", type=int, default=4) + p.set_defaults(fn=cmd_calibrate) + + args = parser.parse_args() + return args.fn(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cadgenbench/prompt_generation.md b/scripts/cadgenbench/prompt_generation.md new file mode 100644 index 0000000..295eb76 --- /dev/null +++ b/scripts/cadgenbench/prompt_generation.md @@ -0,0 +1,28 @@ +You are a CAD engineer. Use the ShapeItUp MCP tools (Replicad / OpenCascade, TypeScript `.shape.ts` scripts) to reproduce a mechanical part from an engineering drawing as one 3D solid, and export it as STEP. + +## Task + +{DESCRIPTION} + +The drawing is in your working directory `{WORKDIR}`: {IMAGES}. Read it with the Read tool. All dimensions are in millimetres. Read the printed dimensions and callouts; do not scale lengths off the pixels. To read small text, you may crop a region with `sips` and Read the crop, for example: +`sips -c --cropOffset input.png --out crop_1.png` + +## How it is scored + +- A hard validity gate first: the STEP must be one well-formed, watertight B-rep that meshes into a closed manifold. An invalid file scores zero. +- Then shape similarity (surface distance F1 and volume IoU), topology (number of bodies, through-holes and internal voids), and the position and size of mating features (bolt holes, bores, slots). +- The grader aligns your part to the reference by rotation and translation only. It never rescales, so absolute size must be exact. +- Recommended pose: bounding-box centre at the origin, longest extent along X, then Y, shortest along Z. + +Priorities, in order: exact absolute size; the right number and position of holes, bores, pockets and bosses; the overall form, including curves and wall thickness from section views; fillets and chamfers last. + +## Working approach + +1. Read the drawing and write a dimension table as text: overall envelope, every diameter, the through-thickness profile from the section view, and the count and position of every feature. Put these values in `export const params = {...}` and build every feature from them. +2. Create the script with `create_shape`, always passing `directory: "{WORKDIR}"`. Call `get_api_reference` when you are unsure of a Replicad call rather than guessing. +3. After every geometry change, check the result: `get_render_status` or `verify_shape` for the bounding box and volume, `describe_geometry` for faces, and `render_preview` then `get_preview` to compare the four views against the drawing. +4. Export a valid checkpoint early, then keep refining and re-export: + `export_shape` with `format: "step"` and `outputPath: "{OUTPUT}"`. +5. Return ONE solid from `main()`, not an array of parts. Fuse touching bodies into one shape. + +You have a soft budget of about {BUDGET_MIN} minutes. Use it to refine fidelity; do not stop at the first valid solid. Before you finish, make sure the last export at `{OUTPUT}` is your best valid part. diff --git a/scripts/cadgenbench/setup.sh b/scripts/cadgenbench/setup.sh new file mode 100755 index 0000000..69e738f --- /dev/null +++ b/scripts/cadgenbench/setup.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Creates the Python env for the official CADGenBench scorer. +# +# Pinned to what the leaderboard's eval image runs: cadgenbench at 8ae1432 and +# dependencies resolved as of that image's build date (2026-06-27). Without the +# date pin, uv picks build123d 0.13 / OCP 8, whose Bnd_Box binding breaks +# analyze_step ("Unable to convert function return value ... Bnd_Box::Limits"), +# so every candidate fails the validity gate. +# +# Everything lands in $CGB_HOME (default ~/.cache/shapeitup-cadgenbench). +set -euo pipefail + +CGB_HOME="${CGB_HOME:-$HOME/.cache/shapeitup-cadgenbench}" +CADGENBENCH_SHA=8ae143221935ecece1d3d4b5141f3afa4e915988 +EVAL_IMAGE_DATE=2026-06-27T09:44:20Z + +mkdir -p "$CGB_HOME" + +UV="$(command -v uv || true)" +if [ -z "$UV" ]; then + python3 -m venv "$CGB_HOME/uvboot" + "$CGB_HOME/uvboot/bin/pip" install -q uv + UV="$CGB_HOME/uvboot/bin/uv" +fi + +"$UV" venv -q --allow-existing -p 3.12 "$CGB_HOME/venv" +"$UV" pip install -q -p "$CGB_HOME/venv/bin/python" \ + --exclude-newer "$EVAL_IMAGE_DATE" \ + "cadgenbench @ git+https://github.com/huggingface/cadgenbench.git@$CADGENBENCH_SHA" \ + "pyvista==0.48.4" + +echo "Scorer ready. Run the benchmark with:" +echo " $CGB_HOME/venv/bin/python scripts/cadgenbench/cgb.py --help"