Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions .claude/agents/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,12 @@ Do not stop and report — diagnose, fix, and re-evaluate in the same session un
| Stage | Input | Method | Output |
|-------|-------|--------|--------|
| 1 — Detection | Circuit image | YOLOv8 (transfer learning) | Bounding boxes + class labels |
| 2 — Wire Extraction | Image | OpenCV only — no neural net | Wire segments as pixel coordinate pairs |
| 3 — Graph | Detections + wires | NetworkX DiGraph | Directed circuit graph |
| 2 - Wire Extraction (net tracing) | Image + detections | OpenCV only, no neural net | Components with pins + undirected nets |
| 3 - Graph | Net trace | NetworkX component/net MultiGraph | Net-based circuit graph |
| 4 — Export | Graph | JSON serialization | DigiSim-importable JSON |

**Stage 4 output format:**
```json
{
"components": [{ "id": "gate_0", "type": "AND", "x": 120, "y": 80 }],
"connections": [{ "from": "gate_0", "to": "gate_1", "fromPort": "output", "toPort": "input_a" }]
}
```
**Stage 4 output format:** schema 2 (components with pins, undirected `nets`, ReactFlow `edges`, legacy gate-level
`connections`), documented in the `backend/pipeline/circuit_exporter.py` module docstring.

## Training Phases (do not advance without hitting threshold)

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ should use the seeded cells or package their own.
- **🔍 ⌘K Component Search**: Instant search and filtering across the entire component palette.
- **⚙️ Real-time Simulation Engine**: Relaxation-based digital gate evaluation, a switch-level CMOS solver (NMOS/PMOS + supplies resolve to correct truth tables), and Modified Nodal Analysis (MNA) solver for analog nodes with live signal propagation (HIGH/LOW/Z/X).
- **📸 ML Image-to-Circuit Detection**:
- **YOLOv8 Schematic Detection**: Detects schematic symbols and uses OpenCV line transforms (Hough) to extract wire paths into a NetworkX graph. See [Machine learning status](#-machine-learning-status) for what the detector currently recognises.
- **YOLOv8 Schematic Detection**: Detects schematic symbols, then traces wires classically (OpenCV skeleton nets, junction vs crossover, pin assignment) into a net-based NetworkX graph. See [Machine learning status](#-machine-learning-status) for what the detector currently recognises.
- **DINOv2 Physical Board Analysis**: Physical board photo component recognition using DINOv2 embeddings and OCR.
- **📄 Human & LLM-Parsable Netlist JSON Schema**: Export and import circuits using an intuitive, semantic JSON format (`input_A.out -> and_1.a`) with 100% loss-free round-trip reconstruction.

Expand Down Expand Up @@ -133,8 +133,8 @@ deploy steps and required secrets: [`docs/deploy-vercel-render.md`](docs/deploy-
## 🧠 Machine Learning Status

The image-to-circuit pipeline is four strictly sequential stages: YOLOv8 detection
(`backend/pipeline/detector.py`), classical OpenCV wire extraction
(`wire_extractor.py`, no neural network), NetworkX graph building
(`backend/pipeline/detector.py`), classical OpenCV net tracing
(`net_tracer.py`, no neural network), net-based NetworkX graph building
(`graph_builder.py`) and DigiSim JSON export (`circuit_exporter.py`). Details:
[`agent_docs/ml-pipeline.md`](agent_docs/ml-pipeline.md).

Expand All @@ -149,7 +149,7 @@ What is true today:
(`ml/classes.yaml`) and a synthetic transistor and gate generator
(`backend/data_gen/generate_v2.py`, see [`docs/synth_v2/README.md`](docs/synth_v2/README.md)) are in place; it still needs
real hand-drawn data (see [Data and licences](#-data-and-licences)),
a GPU training run and net tracing that no longer assumes left-to-right gates. Until that lands,
and a GPU training run (net tracing for transistor-level schematics is in place). Until that lands,
treat detection results on transistor schematics as unsupported.
- **Training is transfer learning only** (pretrained COCO weights, never random
init), with the gate: F1 >= 0.95 and accuracy >= 0.95 per class before a phase
Expand Down
45 changes: 37 additions & 8 deletions agent_docs/ml-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,45 @@
Photo of a circuit → structured JSON → DigiSim recreates the circuit automatically.

## 4 Stages (strictly sequential)
Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Wire Extraction]
Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Net Tracing (wire extraction)]

→ [Stage 3: NetworkX Graph] → [Stage 4: DigiSim JSON Export]
→ [Stage 3: NetworkX Net Graph] → [Stage 4: DigiSim JSON Export]

| Stage | File | Method | Output |
|-------|------|--------|--------|
| 1 | `backend/pipeline/detector.py` | YOLOv8 transfer learning | Bounding boxes + class labels |
| 2 | `backend/pipeline/wire_extractor.py` | OpenCV only — no neural net | Wire segments as pixel pairs |
| 3 | `backend/pipeline/graph_builder.py` | NetworkX DiGraph | Directed circuit graph |
| 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | DigiSim-importable JSON |
| 1 | `backend/pipeline/detector.py` | YOLOv8 transfer learning | Boxes + class labels (+ optional per-terminal keypoints) |
| 2 | `backend/pipeline/net_tracer.py` (+ `ink.py`, `skeleton_graph.py`, `pin_assignment.py`, `label_attach.py`) | OpenCV/scikit-image only, no neural net | Components with resolved pins, undirected nets, labels |
| 3 | `backend/pipeline/graph_builder.py` | NetworkX bipartite component/net MultiGraph | Net-based circuit graph |
| 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | Schema 2 JSON (components with pins, nets, ReactFlow edges, legacy `connections`) |

## Net Tracing (stage 2)
- Ink is binarised against a morphological paper-background estimate; symbol boxes are erased (plus a margin), junction dots are kept;
the wire ink is skeletonised into edges and branch clusters. A cluster whose centre lies in a `JUNCTION` box connects all its wires;
a dotless 4-way cluster is a crossover (straight-through pairs only); any other branch point connects. VDD symbols share one global net,
GND symbols another. Every threshold scales with the measured stroke width and the median symbol size (`TraceConfig`).
- Pins: wire ends at a symbol box are its contacts. With detector keypoints (`Detection.keypoints`: keypoint i = terminal i of the class in
`ml/classes.yaml`, the contract for a T7 pose head) contacts are matched to keypoints; without them a classical rule set assigns terminals
(MOSFET drain/source by electrical distance to the supply, gates by input side) and estimates the 8-way orientation.
- Labels: names beside ports and supplies are cropped and read with RapidOCR's recogniser; nets take their port's name.
- Bench: `cd backend && uv run python data_gen/generate_v2.py --count 300 --seed 1 --out DIR && uv run python bench_tracing.py --data DIR --truth-table`
drives the tracer from perturbed ground-truth detections and scores it with `ml/eval_netlist.py` per render style (clean = cad/textbook,
hand_drawn = hand/photo); it exits 1 unless net F1 >= 0.90 for both styles, exact match >= 70% clean / >= 50% hand-drawn, and p95 runtime < 2 s.
- Measured T2 results: 300 samples from `generate_v2.py --count 300 --seed 1` (held out from tuning, which used seed 7). Detections are
perturbed ground truth (box edges N(0, 3% of side), keypoints N(0, 3% of short side), 2% of junction dots dropped), scored with
`ml/eval_netlist.py`. These scores come from perturbed ground-truth detections because no trained detector for the new classes exists yet,
so they bound the tracer, not the end-to-end photo pipeline.

| Mode | Style (circuits) | Net F1 | Exact match | Truth-table match |
|------|------------------|--------|-------------|-------------------|
| Keypoints | clean (151) | 0.9995 | 99.3% | 99.3% |
| Keypoints | hand-drawn (149) | 0.9989 | 98.7% | 98.7% |
| Geometry fallback (no keypoints) | clean | 0.9897 | 88.7% | 92.0% (overall) |
| Geometry fallback (no keypoints) | hand-drawn | 0.9799 | 86.6% | 92.0% (overall) |

Keypoint mode overall truth-table match is 99.0%. Runtime per image: mean 0.12 s, p95 0.29 s, max 0.80 s (keypoints); p95 0.34 s (geometry fallback).
- Not yet: the T3 screenshot round-trip truth-table check is tracked as a T3/T8 follow-up (the T3 screenshot set does not exist yet). The
frontend importer (T9) still reads only the legacy `connections` (gate-level); wiring transistor-level imports means consuming
`nets`/`edges` (handles `t:`/`s:` + terminal) and `library_cell` in `App.tsx importCircuit`.

## Class Vocabulary
Single source of truth: `ml/classes.yaml` (name, tier, YOLO id, frontend node type, terminals, default size, legacy aliases).
Expand Down Expand Up @@ -57,8 +86,8 @@ Current phase: `ml/experiments/current_phase.txt`
Classes with fewer than 30 GT instances are labelled `low n` instead of judged. Models are scored in the dataset's vocabulary: predictions map by
class name, then by legacy alias (`ml/classes.yaml`); predictions with no counterpart are counted as `unmapped`.
- **Legacy block:** the original ultralytics validation numbers (mAP, max-F1 per class, confusion-matrix accuracy); `--reproduce OLD_eval_test.json` checks them.
- **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `<image stem>.json`, schema in `ml/eval_netlist.py`; T2 emits the ground truth,
T8 must emit predictions in it) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table
- **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `<image stem>.json`, schema in `ml/eval_netlist.py`; the T2 generator's
pin-map netlists are read as ground truth directly, and the stage 4 exporter output is a valid prediction) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table
equivalence of the rebuilt circuit under DigiSim's own `simulate()` (`ml/sim_bridge/truth_table.cjs`; needs `cd frontend && npm install`; `--no-truth-table` skips it).
- **Frozen sets:** the SHA-256 of the split's images and labels directories as resolved from `data.yaml`, its netlists directory (`--gt-netlists` when given) and class names must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing.
Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. `--freeze` exists because the hash check needs a
Expand Down
20 changes: 12 additions & 8 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import tempfile
from pathlib import Path

import cv2
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from flask_cors import CORS
Expand All @@ -19,7 +20,8 @@
from pipeline.circuit_exporter import CircuitExporter
from pipeline.detector import GateDetector
from pipeline.graph_builder import GraphBuilder
from pipeline.wire_extractor import WireExtractor
from pipeline.label_attach import rapidocr_recognizer
from pipeline.net_tracer import NetTracer
from projects import projects_bp
from recognition import recognition_bp

Expand Down Expand Up @@ -116,11 +118,12 @@ def detect_gates() -> tuple:
@require_auth
def detect_circuit() -> tuple:
"""
Run the full local pipeline: detection → wire extraction → graph → JSON export.
Run the full local pipeline: detection → net tracing → net graph → JSON export.

Returns:
JSON with 'components' and 'connections' (CircuitExportJSON) on success,
503 while model weights are missing, or an 'error' key on failure.
JSON in the exporter's schema_version 2 (components with pins, nets, edges, plus the legacy
'connections' list CircuitExportJSON reads) on success, 503 while model weights are missing,
or an 'error' key on failure.
Raises:
400: When no image file is included in the request.
500: When any pipeline stage fails.
Expand Down Expand Up @@ -149,10 +152,11 @@ def detect_circuit() -> tuple:
temp_path = Path(tmp.name)

detections = detector.detect(temp_path)
gate_boxes = [d.box for d in detections if d.class_name != "JUNCTION"]
wires = WireExtractor().extract(temp_path, exclude_boxes=gate_boxes)
graph = GraphBuilder().build(detections, wires)
payload = CircuitExporter().export(graph)
image = cv2.imread(str(temp_path))
if image is None:
return jsonify({"error": "Could not decode the uploaded image"}), 400
trace = NetTracer(ocr=rapidocr_recognizer).trace(image, detections)
payload = CircuitExporter().export(GraphBuilder().build(trace))
payload["status"] = "ok"
payload["detections"] = [
{
Expand Down
Loading
Loading