Metadata-Version: 2.4
Name: cadcore-ai
Version: 0.1.0
Summary: Standalone Agentic Python CAD generation pipeline
Author: Kukil Kashyap Borgohain
License-Expression: MIT
Project-URL: Homepage, https://github.com/kXborg/CadCore
Project-URL: Repository, https://github.com/kXborg/CadCore
Project-URL: Issues, https://github.com/kXborg/CadCore/issues
Project-URL: Documentation, https://github.com/kXborg/CadCore#readme
Keywords: cad,build123d,freecad,agentic-ai,text-to-cad,3d-printing,opencascade
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Manufacturing
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: build123d>=0.8.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: jinja2>=3.1.0
Provides-Extra: llm
Requires-Dist: google-genai>=0.1.0; extra == "llm"
Requires-Dist: openai>=1.0.0; extra == "llm"
Requires-Dist: anthropic>=0.18.0; extra == "llm"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: trimesh>=4.0.0; extra == "dev"
Dynamic: license-file

# CadCore

CadCore is a standalone agentic pipeline that translates natural language descriptions into parametric 3D CAD models (`.step`, `.stl`), 2D technical drawings (`.svg`), and interactive 3D Web Viewers (`.html`) with an automated self-healing execution loop.

---

## Architecture

```mermaid
flowchart TD
    User("User Prompt<br/>(Natural Language)") --> LLM("LLM Planner & Coder<br/>(Gemini / OpenAI / Anthropic / Ollama)")
    LLM --> Code("Generated Parametric Script<br/>(build123d / FreeCAD)")
    Code --> Sandbox("Subprocess Sandbox Executor")
    Sandbox --> Validate{"Execution & Solid Validation"}
    
    Validate -- "Error / Invalid Solid" --> Heal("Self-Healing Feedback<br/>(Traceback + Code Context)")
    Heal -->|"Retry (Up to max_retries)"| LLM
    
    Validate -- "Success" --> Exporter("Multi-Format Exporter")
    
    Exporter --> STEP("model.step<br/>(Standard B-Rep CAD)")
    Exporter --> STL("model.stl<br/>(3D Printing Mesh)")
    Exporter --> SVG("drawing.svg<br/>(2D Technical Drawing)")
    Exporter --> HTML("viewer.html<br/>(Interactive 3D Web Viewer)")
    Exporter --> META("cadcore_meta.json<br/>(Metrics & Metadata)")

    classDef prompt fill:#1e293b,stroke:#38bdf8,stroke-width:2px,color:#f8fafc;
    classDef llm fill:#1e1b4b,stroke:#818cf8,stroke-width:2px,color:#f8fafc;
    classDef script fill:#0f172a,stroke:#94a3b8,stroke-width:2px,color:#f8fafc;
    classDef decision fill:#172554,stroke:#60a5fa,stroke-width:2px,color:#f8fafc;
    classDef healing fill:#451a03,stroke:#f59e0b,stroke-width:2px,color:#f8fafc;
    classDef exporter fill:#064e3b,stroke:#10b981,stroke-width:2px,color:#f8fafc;
    classDef artifact fill:#0c4a6e,stroke:#38bdf8,stroke-width:1.5px,color:#f8fafc;

    class User prompt;
    class LLM llm;
    class Code,Sandbox script;
    class Validate decision;
    class Heal healing;
    class Exporter exporter;
    class STEP,STL,SVG,HTML,META artifact;
```

---

## Key Features

* **Multi-Backend CAD Support**:
  * **`build123d` (Default)**: Modern OpenCASCADE-based Pythonic CAD engine. Fast, headless, and runs in pure Python.
  * **`freecad`**: Executes native FreeCAD scripts headlessly via `FreeCADCmd`.
* **Pluggable LLM Providers**: Built-in support for Google Gemini (`google-genai`), OpenAI / Ollama (`openai`), Anthropic (`anthropic`), and offline `mock` testing.
* **Self-Healing Loop**: Captures runtime errors, missing imports, or invalid topology, then sends tracebacks back to the LLM for automatic correction.
* **Multi-Format Export**: Generates STEP files for CAD exchange, STL meshes for 3D printing, SVG for 2D engineering drawings, and standalone HTML 3D viewers.
* **Geometric Validation**: Analyzes exported meshes for volume, bounding box dimensions, and watertight manifold status.

---

## Installation

### Prerequisites
* Python 3.10, 3.11, or 3.12 (Python 3.11 recommended).
* Optional: FreeCAD 0.20+ if using the FreeCAD backend.

### 1. From PyPI

```bash
pip install cadcore-ai
```

### 2. From Source

```bash
# Clone repository
git clone https://github.com/kXborg/CadCore.git
cd CadCore

# Create and activate virtual environment
python -m venv .venv
.\.venv\Scripts\activate     # On Windows
# source .venv/bin/activate  # On Linux/macOS

# Install dependencies in editable mode
pip install -e .
```

---

## Configuration

Set API keys via environment variables according to your provider:

```bash
# Google Gemini (Default)
export GEMINI_API_KEY="your-gemini-key"

# OpenAI / Compatible
export OPENAI_API_KEY="your-openai-key"

# Anthropic
export ANTHROPIC_API_KEY="your-anthropic-key"

# Ollama / Local LLM (Optional URL override)
export OLLAMA_BASE_URL="http://localhost:11434/v1"
```

---

## CLI Usage

CadCore provides a CLI interface through `cadcore` or `python -m cadcore`.

### 1. Check Supported Backends
```bash
python -m cadcore list-backends
```

### 2. Generate a CAD Part
```bash
python -m cadcore generate "NEMA 17 stepper motor mount plate 42x42mm with central 22mm hole and 4 corner M3 holes at 31mm spacing" --output ./outputs/nema17
```

### 3. Generate and Open Interactive 3D Viewer
```bash
python -m cadcore generate "L-bracket 50x50x25mm with 4mm thickness and 2 M5 mounting holes on each leg" --output ./outputs/l_bracket --view
```

### 4. CLI Options Reference
```text
Arguments:
  PROMPT                       Natural language description of the CAD model.

Options:
  -o, --output PATH            Directory to save generated artifacts. [default: ./output]
  -b, --backend [build123d|freecad]
                               CAD engine backend. [default: build123d]
  -p, --provider [gemini|openai|anthropic|ollama|mock]
                               LLM Provider. [default: gemini]
  -m, --model TEXT             LLM model identifier override.
  -r, --retries INTEGER        Maximum self-healing retry attempts. [default: 3]
  -v, --view                   Open 3D interactive viewer in browser upon completion.
```

---

## Python API Usage

CadCore can be embedded directly into Python workflows:

```python
from pathlib import Path
from cadcore.config import PipelineConfig, CADBackendType, LLMConfig, LLMProvider
from cadcore.pipeline import CADAgentPipeline

# Configure pipeline
config = PipelineConfig(
    backend=CADBackendType.BUILD123D,
    output_dir=Path("./outputs/flange"),
    max_retries=2,
    export_step=True,
    export_stl=True,
    export_svg=True,
    generate_viewer=True,
    llm=LLMConfig(
        provider=LLMProvider.GEMINI,
        model="gemini-2.5-flash",
    ),
)

# Run pipeline
pipeline = CADAgentPipeline(config)
result = pipeline.run("Round pipe flange 60mm OD, 30mm ID, 8mm thickness with 4 bolt holes of 5mm diameter")

if result.success:
    print(f"Generated successfully in {result.execution_time_seconds:.2f}s ({result.iterations} attempt(s))")
    print(f"STEP: {result.artifacts['model.step']}")
    print(f"STL:  {result.artifacts['model.stl']}")
    print(f"SVG:  {result.artifacts['drawing.svg']}")
    print(f"3D Viewer: {result.artifacts['viewer.html']}")
    print(f"Volume: {result.metrics.get('volume_mm3')} mm³")
else:
    print(f"Generation failed: {result.error_message}")
```

---

## Repository Structure

```
CadCore/
├── cadcore/
│   ├── __init__.py
│   ├── __main__.py          # Entrypoint for python -m cadcore
│   ├── cli.py               # Typer & Rich CLI
│   ├── config.py            # Configuration & provider settings
│   ├── executor.py          # Subprocess sandbox & trimesh validation
│   ├── pipeline.py          # Orchestrator & self-healing loop
│   ├── viewer.py            # Three.js 3D/2D HTML viewer generator
│   ├── backends/
│   │   ├── base.py          # Abstract CADBackend
│   │   ├── build123d_backend.py
│   │   └── freecad_backend.py
│   └── llm/
│       ├── client.py        # Pluggable LLM clients
│       └── prompts.py       # CAD prompts & few-shot examples
├── examples/
│   └── basic_pipeline_demo.py
├── tests/
│   └── test_pipeline.py
├── pyproject.toml
├── requirements.txt
└── README.md
```

---

## Testing

Run the test suite with `pytest`:

```bash
pytest tests/ -v
```

---

## License

MIT License.
