{"id":47715763,"url":"https://github.com/proecheng/cad-spec-gen","last_synced_at":"2026-05-17T10:02:51.823Z","repository":{"id":346083085,"uuid":"1188426222","full_name":"proecheng/cad-spec-gen","owner":"proecheng","description":"CAD pipeline AI skill: design doc → structured spec → CadQuery codegen → GB/T 2D drawings + 3D renders + photorealistic images (4 AI backends)","archived":false,"fork":false,"pushed_at":"2026-04-22T11:52:04.000Z","size":383489,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-22T13:31:24.362Z","etag":null,"topics":["ai-skill","blender","cad","cadquery","claude-code","mechanical-design","pipeline","python"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/proecheng.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-03-22T03:53:18.000Z","updated_at":"2026-04-22T11:52:05.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/proecheng/cad-spec-gen","commit_stats":null,"previous_names":["proecheng/cad-spec-gen"],"tags_count":29,"template":false,"template_full_name":null,"purl":"pkg:github/proecheng/cad-spec-gen","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/proecheng%2Fcad-spec-gen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/proecheng%2Fcad-spec-gen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/proecheng%2Fcad-spec-gen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/proecheng%2Fcad-spec-gen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/proecheng","download_url":"https://codeload.github.com/proecheng/cad-spec-gen/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/proecheng%2Fcad-spec-gen/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32301330,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-26T09:34:17.070Z","status":"ssl_error","status_checked_at":"2026-04-26T09:34:00.993Z","response_time":129,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-skill","blender","cad","cadquery","claude-code","mechanical-design","pipeline","python"],"created_at":"2026-04-02T18:56:03.201Z","updated_at":"2026-05-14T03:04:55.007Z","avatar_url":"https://github.com/proecheng.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CAD Spec Generator — Universal AI Skill for CAD Pipelines\n\n\u003e **From Markdown to machining-ready drawings and photorealistic renders — powered by any LLM.**\n\nA **cross-platform AI skill** for the complete CAD pipeline. Works with Claude Code, GPT-4, GLM-4, Qwen, LangChain, AutoGen, Dify — or any LLM with shell execution. One skill gives your AI agent the ability to: extract specs from design docs, generate GB/T-compliant 2D drawings, produce geometrically accurate 3D renders, and create photorealistic presentation images.\n\n**Latest: v2.24.0** — Model-library invocation loop release covering stable model-project paths, read-only SW export planning, hash-bound user STEP imports, and geometry-quality reporting through codegen. See [`CHANGELOG.md`](CHANGELOG.md).\n\n**v2.9.1** — End-to-end regression-hardening release, shipped after a full real-document pipeline test on the GISBOT end-effector design doc. Four skill bugs fixed: (1) `check_env.py` now reads `blender_path` from `pipeline_config.json` so Level 4 RENDER is detected correctly when Blender isn't on `PATH`; (2) `assembly_validator.py` GATE-3.5 no longer crashes on `parse_envelopes()` v2.9 dict return — new `_envelope_dims()` adapter tolerates both tuple and dict shapes; (3) `cad_pipeline.py enhance --backend engineering` now accepted in argparse choices (was silently falling through to gemini); (4) **new `engineering_enhancer.py`** — fully implements the zero-AI backend long documented in `pipeline_config.json` (Blender PBR PNG → PIL sharpness/contrast/saturation → JPG). See [`RELEASE_v2.9.1.md`](RELEASE_v2.9.1.md).\n\n**v2.9.0** — Section-header walker (`cad_spec_section_walker.py`) with 4-tier hybrid matching (structured pattern / CJK+ASCII subsequence / Jaccard + Tier 0 regression guard) attributes `模块包络尺寸` markers to the correct BOM assembly. Six-step granularity enforcement chain prevents station-level envelopes from silently sizing individual purchased parts. Vendor STEP auto-synthesizer warms `~/.cad-spec-gen/step_cache/` on first use so fresh projects route Maxon/LEMO/ATI rows to real geometry without hand-crafted YAML. `cad_pipeline.py --out-dir` flag + subsystem-configurable walker kwargs (`trigger_terms`, `station_patterns`, `axis_label_default`) make the pipeline work on non-GISBOT subsystems. See [`RELEASE_v2.9.0.md`](RELEASE_v2.9.0.md) and [`docs/PARTS_LIBRARY.md`](docs/PARTS_LIBRARY.md) for the full picture.\n\n## Installation\n\n### From PyPI (Recommended)\n\n```bash\npip install cad-spec-gen\ncad-skill-setup\n```\n\nThe interactive wizard guides you through:\n1. Language selection (中文 / English)\n2. Environment detection (Python, CadQuery, ezdxf, Blender, etc.)\n3. Optional dependency installation\n4. Blender configuration\n5. Pipeline config generation\n6. Skill file registration\n\nNon-interactive mode: `cad-skill-setup --lang en --target . --skip-deps`\n\nCodex registration:\n\n```bash\n# Install project tools and generate Codex SKILL.md files under ~/.agents/skills\ncad-skill-setup --lang zh --target . --skip-deps --agent codex\n\n# Install both Claude Code slash commands and Codex skills\ncad-skill-setup --lang zh --target . --skip-deps --agent both\n```\n\nCheck environment: `cad-skill-check`\n\nAfter Claude installation, type `/cad-help` in Claude Code to get started. After Codex installation, start a new Codex session so it can discover `~/.agents/skills/cad-*/SKILL.md`, then ask for CAD spec/codegen/rendering work in natural language.\n\n**Manual skill registration** (if not using `cad-skill-setup`):\n- **Project-level**: `.claude/commands/*.md` (legacy) — auto-discovered in project dir\n- **Codex global**: `~/.agents/skills/\u003cname\u003e/SKILL.md` — generated by `cad-skill-setup --agent codex|both`\n- **Claude global (optional)**: Copy to `~/.claude/skills/\u003cname\u003e/SKILL.md` with YAML frontmatter for all-project access\n\n### Update\n\n```bash\npip install --upgrade cad-spec-gen\ncad-skill-setup --update\n```\n\n### Other Platforms\n\n| Platform | How to Install |\n|----------|---------------|\n| **Any LLM + Shell** | Paste [`system_prompt.md`](system_prompt.md) as system message |\n| **GPT-4 / Assistants** | Upload `system_prompt.md` + enable Code Interpreter ([guide](adapters/openai/README.md)) |\n| **LangChain / AutoGen** | `from adapters.langchain.tools import cad_tools` ([guide](adapters/langchain/README.md)) |\n| **Dify / Coze** | Import `system_prompt.md` to knowledge base ([guide](adapters/dify/README.md)) |\n\nAll tools are **plain Python CLI scripts** — no framework lock-in, no vendor dependency.\n\n```\nDesign Document (.md)\n    ↓ cad_spec_gen.py --review — mechanical / assembly / material / completeness checks\nDESIGN_REVIEW.md (issues \u0026 recommendations, user iterates or proceeds)\n    ↓ cad_spec_gen.py — extract 9 categories of structured data\nCAD_SPEC.md (single source of truth for all downstream CAD work)\n    ↓ codegen/gen_*.py — Jinja2 templates → CadQuery scaffolds\nparams.py + build_all.py + station_*.py + std_*.py + assembly.py (per-part offsets + station transforms, generic part number support)\n    ↓ CadQuery parametric modeling\nSTEP + STD-STEP (standard parts) + DXF (GB/T 2D drawings) + GLB\n    ↓ render_dxf.py — auto DXF→PNG engineering drawing previews (if script exists)\nDXF PNG previews (for design review)\n    ↓ Blender Cycles rendering (GPU auto-detect, CPU fallback)\nN-view PNG — 100% geometry-accurate, cross-view consistent (default 5, configurable)\n    ↓ AI enhancement (reskin only, geometry locked) — 4 backends: gemini | fal | comfyui | engineering\n       python cad_pipeline.py enhance --subsystem \u003cname\u003e [--dir \u003cdir\u003e] [--backend \u003cbackend\u003e]\nPhotorealistic PNG — presentation / defense / business plan ready\n    ↓ Enhancement acceptance — manifest-bound delivery status\n       python cad_pipeline.py enhance-check --subsystem \u003cname\u003e --dir \u003crender_dir\u003e\nENHANCEMENT_REPORT.json — accepted / preview / blocked\n    ↓ python cad_pipeline.py annotate — PIL-based component labels (CN/EN)\nLabeled PNG — with leader lines and component names\n```\n\n## Why This Tool?\n\n| Pain Point | How We Solve It |\n|------------|----------------|\n| Design docs have scattered parameters, tolerances, BOM across 600+ lines | **One command** extracts all 9 data categories into a single structured spec |\n| Design docs may have engineering errors (stress, fit, material) | **Design review** checks mechanics, assembly, materials, completeness before CAD |\n| Pure text-to-image AI gets ~42% geometry accuracy | **Hybrid pipeline**: Blender renders exact geometry first, AI only \"reskins\" the surface |\n| \"What should I do next?\" is hard to answer in a complex pipeline | **Natural-language assistant** scans your project artifacts and recommends the next action |\n| Cross-view consistency is poor with AI-generated images | **Blender-first** approach locks geometry across all views; AI inherits consistency |\n| 2D drawings don't follow national standards | **GB/T compliant**: first-angle projection, FangSong font, 12-layer DXF with 0.5mm line widths |\n| Hard to integrate with other LLMs (GPT, GLM, Qwen...) | **LLM-agnostic**: pure Python CLI + `system_prompt.md` + platform adapters |\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────────────────┐\n│  Platform Adapters  (pick one, or use system_prompt.md)   │\n│  ├── .claude/commands/ → Claude Code slash commands        │\n│  ├── ~/.agents/skills/ → Codex SKILL.md files              │\n│  ├── openai/       → Function Calling JSON schema         │\n│  ├── langchain/    → LangChain/AutoGen Tool wrapper       │\n│  └── dify/         → Knowledge base import guide          │\n├──────────────────────────────────────────────────────────┤\n│  Universal Skill Layer                                    │\n│  ├── skill.json         → machine-readable skill manifest │\n│  ├── system_prompt.md   → paste into any LLM              │\n│  └── skill_cad_help.md  → 16-intent knowledge base        │\n├──────────────────────────────────────────────────────────┤\n│  Tool Layer  (pure Python CLI, no LLM dependency)         │\n│  ├── cad_pipeline.py    → unified 6-phase orchestrator    │\n│  ├── cad_spec_gen.py    → spec extraction                 │\n│  ├── cad_spec_reviewer.py → design review (4 categories)  │\n│  ├── codegen/gen_*.py   → Jinja2 code generation          │\n│  ├── bom_parser.py      → BOM parsing                     │\n│  └── config/templates/  → subsystem configs + Jinja2 .j2  │\n└──────────────────────────────────────────────────────────┘\n```\n\n## Pipeline Architecture\n\n```\n┌────────────────────────────────────────────────────────────────┐\n│                   CAD Hybrid Rendering Pipeline                 │\n│                                                                 │\n│  1. DESIGN REVIEW (optional, recommended)                         │\n│     Design doc (.md) → cad_spec_gen.py --review                   │\n│     → DESIGN_REVIEW.md (A.mechanical / B.assembly incl. B5-B8    │\n│       floating parts \u0026 connection checks / C.material / D.gaps)  │\n│     User: \"继续审查\" / \"自动补全\" (--auto-fill) / \"下一步\"          │\n│  ✋ [GATE-1] CRITICAL issues block SPEC phase until confirmed     │\n│                                                                 │\n│  2. SPEC EXTRACTION (this repo)                                   │\n│     Design doc (.md) → cad_spec_gen.py → CAD_SPEC.md            │\n│     9 sections: params, tolerances, fasteners, connections,     │\n│     BOM tree, assembly pose, visual IDs, render plan, gaps      │\n│     v2.3: auto-extracts per-part feature list (holes/slots)     │\n│     by cross-referencing §2/§3/§4/§8 (extract_part_features)   │\n│     v2.9: §6.4 envelope attribution via stateful SectionWalker  │\n│     (cad_spec_section_walker.py) — 4-tier hybrid matching       │\n│     (Tier 0 part_no regression guard + Tier 1 structured        │\n│     pattern + Tier 2 CJK+ASCII subsequence + Tier 3 Jaccard)    │\n│     with 2-phase dispatch. Per-instance kwargs (trigger_terms / │\n│     station_patterns / axis_label_default) make it work across  │\n│     non-GISBOT subsystems. Canonical (X,Y,Z) axis rewrite +     │\n│     machine-readable reason codes → §6.4.1 UNMATCHED subsection.│\n│                                                                 │\n│  3. CODE GENERATION (Jinja2)                                      │\n│     CAD_SPEC.md → codegen/gen_*.py → params.py + build_all.py   │\n│     + station_*.py scaffolds + std_*.py (standard parts)         │\n│     + assembly.py (per-part offsets + station radial transforms)  │\n│     Templates: templates/*.j2 (scaffold mode, never overwrites) │\n│     ⚠ Scaffolds are incomplete: params.py needs correct naming,  │\n│     build_all.py needs valid module refs, assembly.py needs       │\n│     hand-written mate logic. Complete before Phase 4.             │\n│     v2.21.2: parts_library.yaml routes purchased parts through   │\n│     user/project STEP, shared STEP cache, SW Toolbox,             │\n│     bd_warehouse / PartCAD adapters before jinja_primitive        │\n│     terminal fallback. v2.8.1: extends:default registry          │\n│     inheritance + per-build resolver coverage report.            │\n│     v2.8.2: F1+F3 disc_arms flange (full-thickness arms +        │\n│     chamfer/fillet) + GLB consolidator (per-face → per-part).    │\n│     v2.9: six-step granularity enforcement chain — walker →      │\n│     parse_envelopes → PartQuery.spec_envelope_granularity →      │\n│     JinjaPrimitiveAdapter REJECTS station_constraint envelopes,  │\n│     falling through to lookup_std_part_dims instead of sizing    │\n│     individual purchased parts as the full station bounding box. │\n│     Vendor STEP auto-synthesizer (adapters/parts/                │\n│     vendor_synthesizer.py) warms ~/.cad-spec-gen/step_cache/     │\n│     on first use. geometry_report.json records A-E quality and   │\n│     flags remaining D/E simplified placeholders for upgrade.     │\n│  ✋ [GATE-2] TODO scan — exit code 2 if unfilled TODO: markers   │\n│                                                                 │\n│  4. PARAMETRIC MODELING                                         │\n│  ✋ [GATE-3] orientation_check.py — asserts bounding-box axes    │\n│     CadQuery scripts → STEP + GLB + DXF                        │\n│     - 3D: assemblies with precise mate constraints              │\n│     - 2D: GB/T A3 drawings, 3-view + section views              │\n│     v2.3: position dims, orthogonal dim angles, A-A section     │\n│     hatch (holes excluded), dynamic tech notes placement        │\n│                                                                 │\n│  5. 3D RENDERING (Blender Cycles, GPU auto-detect)                │\n│     GLB → N-view PNG (geometry 100% accurate, default 5 views)  │\n│     15 PBR material presets · spherical camera system            │\n│     Default views: front-iso / rear / side / exploded / ortho   │\n│     Views are config-driven: render_config.json camera section   │\n│                                                                 │\n│  6. AI ENHANCEMENT (optional) — 4 backends                      │\n│     PNG → photorealistic JPG (reskin only, geometry locked)     │\n│     Backends: gemini (~$0.02/img, cloud, soft geometry lock)    │\n│               fal (fal.ai Flux ControlNet, ~$0.20/img, hard    │\n│                    depth+canny lock) [NEW in v2.3]              │\n│               comfyui (local GPU ControlNet, free, hard lock)   │\n│               engineering (Blender PBR direct→JPG, free,        │\n│                    perfect geometry, no AI) [NEW in v2.3]       │\n│     Auto-detect: FAL_KEY→fal, ComfyUI→comfyui, gemini→gemini,  │\n│                  else→engineering                                │\n│     Fallback: fal→gemini→engineering (batch-locked on downgrade)│\n│     CLI: --backend gemini|fal|comfyui|engineering               │\n│     v2.3: unified MATERIAL_PRESETS appearance (single source    │\n│     of truth for both Blender PBR + AI prompt), view-aware      │\n│     material emphasis (Fresnel/specular per camera angle),      │\n│     material_type→preset auto-fallback from params.py           │\n│     Material bridging: bom_id→component→material auto-lookup    │\n│                                                                 │\n│  Output:  PNG → engineering review / machining reference        │\n│           JPG → presentations / proposals / business plans      │\n└────────────────────────────────────────────────────────────────┘\n```\n\n## Quality Gates\n\nThree mandatory checkpoints block the pipeline on failure:\n\n| Gate | Phase | Check | Exit code |\n|------|-------|-------|-----------|\n| Gate 1 — CRITICAL review | SPEC | `cad_spec_reviewer.py` finds CRITICAL issues | non-0, user must confirm |\n| Gate 2 — TODO scan | CODEGEN | Generated scaffold files contain unfilled `TODO:` markers | 2, prints file:line list |\n| Gate 3 — Orientation check | BUILD (pre) | `orientation_check.py` asserts bounding-box principal axes match design doc | non-0; bypass with `--skip-orientation` |\n\nGate 3 is skipped if `orientation_check.py` does not exist in the subsystem directory (non-mandatory for new subsystems).\n\n## Key Features\n\n### Spec Extraction (`cad_spec_gen.py`)\n- **9-section structured output**: parameters, tolerances, fasteners, connection matrix, BOM tree, assembly pose, visual IDs, render plan, completeness report\n- **Design review mode** (`--review`): mechanical stress (A1-A3), assembly fit \u0026 connection graph (B1-B8), material compatibility (C1-C3), completeness gaps (D1+) → `DESIGN_REVIEW.md`\n- **User-driven iteration**: 3 options — \"继续审查\" (iterate) / \"自动补全\" (`--auto-fill`, computes missing torques/Ra/units) / \"下一步\" (proceed)\n- **Idempotent**: MD5-based skip — won't regenerate if source unchanged\n- **Auto-defaults**: standard bolt torques (8.8 grade), surface Ra by material type\n- **Derived calculations**: total cost, part count, BOM completeness %\n- **Configurable**: subsystem mapping via JSON config, no hardcoded paths\n- **Generic part numbers**: supports any prefix format (GIS-EE-xxx, SLP-xxx, ACME-xxx) — not limited to GIS\n- **Flat BOM support**: subsystems without sub-assembly hierarchy are handled correctly\n\n### Interactive Help (16 Intents)\n- **Natural language** — no need to memorize CLI syntax, just ask in plain language\n- **16 intents**: environment check, config validation, next-step recommendation, materials, camera, exploded view, rendering, AI enhancement, troubleshooting, file structure, status, cross-model integration, parts/BOM, CAD spec, design review\n- **Smart \"what's next?\"** — scans project artifacts (STEP/DXF/GLB/PNG/JPG) and recommends the highest-priority next action\n\n### 2D Engineering Drawings\n- **GB/T national standard**: first-angle projection, A3 sheet, title block\n- **12-layer DXF** system with 0.5mm line widths per GB/T 17450\n- **FangSong font**, 3.5mm annotation height\n- Section views (A-A cut lines), datum triangles, default Ra callouts\n\n### 3D Rendering\n- **Blender Cycles** with GPU auto-detect (OptiX \u003e CUDA \u003e HIP \u003e OneAPI \u003e CPU fallback) — also works on remote desktops without GPU\n- **5 standard views** (default, configurable per subsystem): V1 front-iso, V2 rear-oblique, V3 side-elevation, V4 exploded, V5 ortho-front\n- **15 PBR material presets**: brushed aluminum, PEEK, carbon fiber, rubber, glass, etc.\n- **Exploded views**: radial / axial / custom explosion with assembly lines\n- **Config-driven**: `render_config.json` controls materials, cameras, explosion rules\n- **Material bridging**: `resolve_bom_materials()` auto-derives PBR materials from BOM part IDs via bom_id→component→material lookup chain; auto-creates missing entries with consistency validation\n\n### AI Enhancement (Hybrid Rendering) — 4 Backends\n- **Four backends**: gemini (cloud AI, ~$0.02/img), fal (fal.ai Flux ControlNet, ~$0.20/img), comfyui (local GPU ControlNet, free), engineering (Blender PBR direct, free)\n- **Auto-detect**: checks FAL_KEY → ComfyUI server → Gemini config → falls back to engineering\n- **Fallback chain**: fal → gemini → engineering (batch-locked after downgrade to ensure consistency)\n- **Geometry-locked**: Blender PNG provides exact geometry; AI only changes surface appearance\n- **Standard parts**: real STEP / SW Toolbox / parametric library models are preferred; simplified CadQuery shapes are terminal fallback and are reported through `geometry_report.json`\n- **Cross-view consistent**: all 5 views share the same 3D source\n- **Dual output**: PNG for engineering, JPG for presentation\n- **Prompt templates**: auto-generated from render config variables\n- **CLI**: `--backend gemini|fal|comfyui|engineering` on both `enhance` and `full` commands\n\n## Quick Start\n\n\u003e **Two reference subsystems included**: End Effector (GIS-EE, radial layout, 24 parts) and Lifting Platform (SLP, vertical linear actuator, 32 parts). Adapt paths for your own subsystem.\n\n```bash\n# Scaffold a new subsystem (generates render_config.json, params.py, design doc template)\npython cad_pipeline.py init --subsystem robot_arm --name-cn 机器人臂 --prefix RA\n# → output/robot_arm/render_config.json, output/robot_arm/params.py, docs/design/XX-robot_arm.md\n\n# One-click full pipeline (all 6 phases)\npython cad_pipeline.py full --subsystem end_effector \\\n    --design-doc docs/design/04-末端执行机构设计.md --timestamp\n\n# Or step-by-step:\n\n# Phase 1: Design review + spec (recommended first)\npython cad_pipeline.py spec --design-doc docs/design/04-末端执行机构设计.md --auto-fill\n# → cad/end_effector/DESIGN_REVIEW.md + CAD_SPEC.md\n\n# Phase 2: Generate CadQuery scaffolds\npython cad_pipeline.py codegen --subsystem end_effector\n# → params.py, build_all.py, station_*.py, std_*.py, assembly.py\n\n# Phase 3-4: Build + render\npython cad_pipeline.py build --subsystem end_effector\npython cad_pipeline.py render --subsystem end_effector --timestamp\n# Note: view script selection is automatic from render_config.json `type` field\n# (type=exploded → render_exploded.py, type=section → render_section.py, etc.)\n\n# Phase 5-6: AI enhance + annotate (optional)\n# enhance auto-reads render_manifest.json (only current-session renders); use --dir to override\npython cad_pipeline.py enhance --subsystem end_effector\npython cad_pipeline.py enhance-check --subsystem end_effector --dir cad/output/renders/end_effector/\u003crun_id\u003e\npython cad_pipeline.py annotate --subsystem end_effector --lang cn,en\n\n# Check pipeline status\npython cad_pipeline.py status\n\n# Check environment\npython cad_pipeline.py env-check\n```\n\n### 多轮渐进确认（v2.31.0+）\n\n不必一次说全 KPI；起手只说大方向，系统主动追问：\n\n```bash\n# 第一步：起手（不全也 ok）\n$ python cad_pipeline.py project-guide --product-goal \"做升降平台\"\n# → status=needs_kpi_confirmation；状态已记到 ./PROJECT_GOAL_STATE.json\n# → 提示：cad-spec-gen project-guide --resume --answer load_kg=50\n\n# 第二步：续答任一项（可重复）\n$ python cad_pipeline.py project-guide --resume --answer load_kg=50\n$ python cad_pipeline.py project-guide --resume --answer stroke_mm=800\n$ python cad_pipeline.py project-guide --resume --answer platform_size_mm=600x600\n\n# 全齐自动删 state + ready_for_cad_spec\n```\n\n也可一次答多个 KPI：\n\n```bash\n$ python cad_pipeline.py project-guide --resume --answer load_kg=50 --answer stroke_mm=800\n```\n\n`./PROJECT_GOAL_STATE.json` 是 project-local 状态文件（已加 .gitignore）。\n\n### AI Enhancement Quick Start\n\nAfter Blender renders your PNGs, enhance them to photorealistic images via the pipeline.\nFour backends are supported: **gemini** (cloud AI, ~$0.02/img), **fal** (fal.ai Flux ControlNet, ~$0.20/img, hard geometry lock), **comfyui** (local GPU ControlNet, free, hard lock), and **engineering** (Blender PBR direct, free, perfect geometry, no AI).\n\n**v2.1 — Multi-view consistency (Gemini):** four-layer defense ensures each view keeps its correct camera angle after enhancement: auto-computed azimuth/elevation written into prompt, source image placed first (locks composition), V1 result used as material anchor for V2–VN, source PNG sent at full resolution (≤4 MB uncompressed).\n\n**First-time Gemini setup** — configure your API proxy:\n```bash\npython gemini_gen.py --config\n# Prompts for: API Key, API Base URL (your proxy), model name, output dir\n# Saved to: ~/.claude/gemini_image_config.json\n```\n\n```bash\n# Auto-detect best backend (FAL_KEY→fal, ComfyUI→comfyui, gemini→gemini, else→engineering)\npython cad_pipeline.py enhance --subsystem \u003cname\u003e\n\n# Specify custom output directory (also reads manifest from that dir)\npython cad_pipeline.py enhance --dir /path/to/renders\n\n# Force a specific backend\npython cad_pipeline.py enhance --subsystem \u003cname\u003e --backend fal\npython cad_pipeline.py enhance --subsystem \u003cname\u003e --backend gemini\npython cad_pipeline.py enhance --subsystem \u003cname\u003e --backend comfyui\npython cad_pipeline.py enhance --subsystem \u003cname\u003e --backend engineering\n\n# Backend also works on full pipeline\npython cad_pipeline.py full --subsystem \u003cname\u003e --backend fal\n\n# Override Gemini model temporarily\npython cad_pipeline.py enhance --dir /path/to/renders --model nano_banana_pro\n\n# Check ComfyUI environment manually before first use\npython comfyui_env_check.py\n```\n\nThe enhance step automatically:\n- Reads `render_manifest.json` from `--dir` or default renders dir to process only latest render files\n- Auto-enriches prompt data from `params.py` via `prompt_data_builder.py` (materials, assembly description, constraints)\n- **gemini** (v2.1): geometry and viewpoint locked via prompt — auto-computed camera angle (azimuth/elevation), source image first, V1-anchor reference, full-res PNG input\n- **fal**: fal.ai Flux ControlNet — hard depth+canny geometry lock, cloud-based, ~$0.20/image\n- **comfyui**: local GPU ControlNet depth+canny to hard-lock geometry; requires local GPU\n- **engineering**: Blender PBR rendered directly to JPG — no AI, free, perfect geometry fidelity\n- Auto-detect priority: `FAL_KEY` env var → ComfyUI server running → Gemini config → engineering fallback\n- Fallback chain: if fal fails mid-batch → downgrade to gemini → engineering (batch-locked after downgrade)\n- Skips `*_enhanced.*` files to prevent re-processing\n\nSwitch backend permanently in `pipeline_config.json`:\n```json\n\"enhance\": { \"backend\": \"fal\" }\n```\n\nOutput: `\u003crender_dir\u003e/\u003cVN\u003e_\u003cname\u003e_\u003ctimestamp\u003e_enhanced.png` per view, photorealistic studio quality.\n\nRun acceptance before delivery:\n\n```bash\npython cad_pipeline.py enhance-check --subsystem \u003cname\u003e --dir \u003crender_dir\u003e\n```\n\n`enhance-check` reads the explicit render directory's `render_manifest.json`, requires every manifest view to have exactly one same-directory `*_enhanced.*` image, compares source/enhanced shape and basic image QA, and writes `ENHANCEMENT_REPORT.json` with `accepted`, `preview`, or `blocked`. It does not scan directories for newest files and rejects enhanced images outside the bound render directory.\n\n### Component Label Annotation\n\nAfter AI enhancement, add component labels (Chinese/English) via PIL:\n\n```bash\n# Annotate all views in Chinese (auto-reads manifest)\npython cad_pipeline.py annotate --subsystem \u003cname\u003e --lang cn\n\n# Annotate from a specific directory\npython cad_pipeline.py annotate --dir /path/to/renders --lang cn,en\n```\n\nLabels are defined in `render_config.json`:\n- `components` section: maps IDs to CN/EN names + BOM IDs (from design doc §X.8 BOM)\n- `labels` section: per-view coordinates for **visible** components only (occluded = not labeled)\n- Coordinates at 1920×1080 reference (configurable via `reference_resolution`), auto-scaled to actual image size\n\n### 一条命令跑完 photo3d 验收闭环（v2.28.0+）\n\n```bash\n# 第一步：预览（不执行；看下一步要跑什么）\npython cad_pipeline.py photo3d-handoff --subsystem lifting_platform --with-jury\n\n# 第二步：加 --confirm 实跑（触发 enhance + check + jury 自动验收 + enhance-review）\npython cad_pipeline.py photo3d-handoff --subsystem lifting_platform --with-jury --confirm\n```\n\n详细 flag 矩阵 / 故障恢复 / CI 集成示例见 `docs/cad-jury-config.md`。\n\n## Adding a New Subsystem\n\n### Option A: One-command scaffold (recommended)\n\n```bash\npython cad_pipeline.py init --subsystem \u003cyour_subsystem\u003e --name-cn \u003c中文名\u003e --prefix \u003cPREFIX\u003e\n```\n\nGenerates three files automatically:\n- `output/\u003cyour_subsystem\u003e/render_config.json` — camera views (V1-V5), materials, CN/EN component names\n- `output/\u003cyour_subsystem\u003e/params.py` — dimension skeleton\n- `docs/design/XX-\u003cyour_subsystem\u003e.md` — design doc template\n\nThen edit each file and run the full pipeline:\n```bash\npython cad_pipeline.py full --subsystem \u003cyour_subsystem\u003e --design-doc docs/design/XX-\u003cyour_subsystem\u003e.md\n```\n\n### Option B: Manual setup\n\n1. **Create directory and config**:\n   ```bash\n   mkdir cad/\u003cyour_subsystem\u003e/\n   cp templates/render_config_template.json cad/\u003cyour_subsystem\u003e/render_config.json\n   ```\n   Edit `render_config.json` — fill in subsystem info, materials, camera views, and components.\n\n2. **Auto-generate scaffolds** (if design doc exists):\n   ```bash\n   python cad_pipeline.py spec --design-doc docs/design/NN-*.md\n   python cad_pipeline.py codegen --subsystem \u003cyour_subsystem\u003e\n   ```\n\n3. **Refine scaffolds**: Edit generated files — params.py needs correct descriptive parameter names (codegen produces line-number based names), build_all.py needs valid module references, assembly.py needs real mate logic. Replace placeholder boxes in station_*.py with actual CadQuery geometry.\n\n4. **Build + render**:\n   ```bash\n   python cad_pipeline.py full --subsystem \u003cyour_subsystem\u003e --skip-spec --skip-codegen --timestamp\n   ```\n\nSee `templates/render_config_template.json` for field documentation.\n\n## Usage\n\n```\npython cad_spec_gen.py [FILES...] --config CONFIG [OPTIONS]\n\nRequired:\n  --config PATH         JSON config with subsystem mapping\n\nOptions:\n  --output-dir DIR      Output directory (default: ./output)\n  --doc-dir DIR         Design docs directory for --all\n  --all                 Process all NN-*.md in doc-dir\n  --force               Force regeneration (ignore MD5 check)\n  --review              Run design review before spec generation\n  --review-only         Run design review only (no spec generation)\n  --auto-fill           Auto-fill computable missing values (torques, units, Ra)\n```\n\n### Process all subsystems at once\n\n```bash\npython cad_spec_gen.py --all --config config/gisbot.json --doc-dir docs/design\n```\n\n### BOM parser (standalone)\n\n```bash\npython bom_parser.py examples/04-末端执行机构设计.md          # tree view (GIS-EE format)\npython bom_parser.py examples/04-末端执行机构设计.md --json   # JSON output\npython bom_parser.py examples/04-末端执行机构设计.md --summary # one-line summary\n# Supports any BOM table header: 料号/图号/编号 + 名称 + 数量 (+ optional 材质/类型/备注)\n```\n\n## Configuration\n\nCreate a JSON config file (see `config/gisbot.json` for a full 19-subsystem example):\n\n```json\n{\n  \"doc_dir\": \"docs/design\",\n  \"output_dir\": \"./output\",\n  \"subsystems\": {\n    \"04\": {\n      \"name\": \"End Effector\",\n      \"prefix\": \"GIS-EE\",\n      \"cad_dir\": \"end_effector\",\n      \"aliases\": [\"ee\", \"end_effector\"]\n    },\n    \"19\": {\n      \"name\": \"Lifting Platform\",\n      \"prefix\": \"SLP\",\n      \"cad_dir\": \"lifting_platform\",\n      \"aliases\": [\"升降\", \"lifting\"]\n    }\n  }\n}\n```\n\n## 15 PBR Material Presets\n\n| Category | Presets |\n|----------|---------|\n| Metal | `brushed_aluminum` `stainless_304` `black_anodized` `dark_steel` `bronze` `copper` `gunmetal` `anodized_blue` `anodized_green` `anodized_purple` `anodized_red` |\n| Plastic | `peek_amber` `white_nylon` `black_rubber` `polycarbonate_clear` |\n\n## Documentation\n\n| Document | Language | Description |\n|----------|----------|-------------|\n| [System Prompt](system_prompt.md) | EN | Universal system prompt — paste into any LLM |\n| [Skill Manifest](skill.json) | — | Machine-readable skill definition |\n| [Project Progress Board](docs/PROGRESS.md) | 中文 | 当前看板、验证记录、下一步建议；每轮结束更新 |\n| [Superpowers Planning Index](docs/superpowers/README.md) | 中文 | plans/specs/reports/runbooks 入口和更新规则 |\n| [User Guide (English)](docs/cad-help-guide-en.md) | EN | Full feature walkthrough, 16 intents, workflows |\n| [User Guide (Chinese)](docs/cad-help-guide-zh.md) | 中文 | 完整功能说明、16种意图、典型工作流 |\n| [Agent Integration Guide](docs/cad_pipeline_agent_guide.md) | 中文 | LLM/Agent framework integration (GPT, GLM, LangChain, etc.) |\n| [CAD Spec Template](templates/cad_spec_template.md) | — | Output format reference with all 9 sections |\n| [AI Prompt Templates](templates/) | EN | Unified prompt template (`prompt_enhance_unified.txt`) with auto view-type switching (standard/exploded/ortho/section) |\n\n## Project Structure\n\n```\n├── skill.json                      # Machine-readable skill manifest\n├── system_prompt.md                # Universal system prompt (any LLM)\n├── skill_cad_help.md               # Skill knowledge (16 intents + actions)\n├── cad_pipeline.py                 # Unified 6-phase pipeline orchestrator\n├── cad_paths.py                    # Path resolution (SKILL_ROOT / PROJECT_ROOT / Blender / Gemini)\n├── render_config.py                # Render config engine (15 material presets + material bridging)\n├── pipeline_config.json            # Persistent config (Blender path, render settings)\n├── cad_spec_gen.py                 # Spec extraction (CLI entry point)\n├── cad_spec_extractors.py          # 8 extraction functions + table parser\n├── cad_spec_defaults.py            # Standard defaults, engineering constants\n├── cad_spec_reviewer.py            # Design review engine (4 categories)\n├── bom_parser.py                   # BOM table parser (also standalone CLI)\n├── annotate_render.py              # PIL-based component label annotation (CN/EN)\n├── enhance_prompt.py               # Prompt builder for AI enhancement phase\n├── prompt_data_builder.py          # Auto-generates material/assembly data from params.py\n├── comfyui_enhancer.py             # ComfyUI backend: ControlNet depth+canny geometry lock\n├── comfyui_env_check.py            # ComfyUI environment validator (GPU, models, server mode)\n├── codegen/                        # Jinja2 code generation from CAD_SPEC.md\n│   ├── gen_params.py               # §1 params → params.py\n│   ├── gen_build.py                # §5 BOM → build_all.py (STEP + STD + DXF)\n│   ├── gen_parts.py                # §5 custom leaf parts → station_*.py scaffolds\n│   ├── gen_std_parts.py            # §5 purchased parts → std_*.py + geometry_report.json\n│   └── gen_assembly.py             # §4+§5+§6 → assembly.py (incl. standard parts)\n├── templates/\n│   ├── params.py.j2                # Jinja2: params.py generation\n│   ├── build_all.py.j2             # Jinja2: build_all.py generation\n│   ├── part_module.py.j2           # Jinja2: part module scaffold\n│   ├── assembly.py.j2              # Jinja2: assembly scaffold\n│   ├── cad_spec_template.md        # Output template reference\n│   ├── design_review_template.md   # Design review output template\n│   ├── prompt_enhance_unified.txt  # AI prompt: all views (unified template)\n│   └── prompt_section.txt          # Section view prompt template\n├── gemini_gen.py                   # Gemini image generation (OpenAI-compatible API)\n├── .claude/commands/               # Claude Code slash commands (5 commands, legacy format)\n├── adapters/\n│   ├── openai/\n│   │   ├── functions.json         # OpenAI Function Calling schema\n│   │   └── README.md              # GPT-4 / Assistants setup guide\n│   ├── langchain/\n│   │   ├── tools.py               # LangChain Tool wrapper\n│   │   └── README.md              # LangChain / AutoGen setup guide\n│   └── dify/\n│       └── README.md              # Dify / Coze setup guide\n├── config/\n│   └── gisbot.json                # Example: 19-subsystem config\n├── cad/\n│   ├── end_effector/              # Reference: radial 4-station layout (GIS-EE, 24 parts)\n│   └── lifting_platform/         # Reference: vertical linear actuator (SLP, 32 parts)\n├── examples/\n│   └── 04-末端执行机构设计.md       # Example design document\n└── docs/\n    ├── cad-help-guide-en.md       # User guide (English)\n    ├── cad-help-guide-zh.md       # User guide (Chinese)\n    └── cad_pipeline_agent_guide.md # Cross-LLM agent integration guide\n```\n\nCodex SKILL.md files are generated outside the repository at `~/.agents/skills/cad-*/`.\n\n## CI\n\nGitHub Actions workflows（见 `.github/workflows/`）：\n\n- `tests.yml`：常规单元/集成测试，PR 与 push 触发（ubuntu + windows matrix，不含真 SolidWorks）\n- `sw-smoke`：真 SolidWorks 环境回归（self-hosted runner，仅 `main` push + 手动触发；commit 含 `[skip smoke]` 跳过）\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fproecheng%2Fcad-spec-gen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fproecheng%2Fcad-spec-gen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fproecheng%2Fcad-spec-gen/lists"}