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
8 changes: 4 additions & 4 deletions .claude/agents/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ Do not stop and report — diagnose, fix, and re-evaluate in the same session un

| Phase | Classes | Stages Active |
|-------|---------|---------------|
| 1 | AND, OR, NOT | 1 only |
| 2 | All 12: + NAND, NOR, XOR, XNOR, Switch, Input, Output, LED, Junction | 1 only |
| 3 | All 12 | 1 + 2 + 3 |
| 4 | All 12 | 1 + 2 + 3 + 4 |
| 1 | NMOS, PMOS, VDD, GND | 1 only |
| 2 | All 14 tier A (see `ml/classes.yaml`): + INPUT_PORT, OUTPUT_PORT, JUNCTION, AND, OR, NOT, NAND, NOR, XOR, XNOR | 1 only |
| 3 | All 14 | 1 + 2 + 3 |
| 4 | All 14 | 1 + 2 + 3 + 4 |

Current phase tracked in `ml/experiments/current_phase.txt`.

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ What is true today:
AND, OR, NOT, NAND, NOR, XOR, XNOR, Switch, Input, Output, LED, Junction).
It does not recognise NMOS/PMOS transistors or supply symbols, and it detects
nothing useful on transistor-level schematics.
- **Retraining on transistor-level classes is in progress.** It needs a new
class schema, a synthetic transistor-level generator, 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,
- **Retraining on transistor-level classes is in progress.** The class schema
(`ml/classes.yaml`) is in place; it still needs a synthetic transistor-level
generator, 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,
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
30 changes: 25 additions & 5 deletions agent_docs/ml-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,36 @@ Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Wire Extraction]
| 3 | `backend/pipeline/graph_builder.py` | NetworkX DiGraph | Directed circuit graph |
| 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | DigiSim-importable JSON |

## Class Vocabulary
Single source of truth: `ml/classes.yaml` (name, tier, YOLO id, frontend node type, terminals, default size, legacy aliases).
Never hand-edit the generated files; after editing the YAML run `cd ml && uv run python class_schema.py generate`
(`check` verifies nothing is stale; pytest `backend/test_class_schema.py` and Jest `yoloClassMap.test.ts` assert the backend and frontend maps equal the YAML).

| Tier | Classes (YOLO ids in file order) |
|------|----------------------------------|
| A (required, 14) | `NMOS PMOS VDD GND INPUT_PORT OUTPUT_PORT JUNCTION AND OR NOT NAND NOR XOR XNOR` |
| B (next, analog) | `RESISTOR CAPACITOR INDUCTOR BJT_NPN BJT_PNP CLOCK` |

Generated: `backend/pipeline/class_map.py` (`CLASS_TO_NODE_TYPE`, re-exported by `detector.py`),
`frontend/src/logic/vision/yoloClassMap.generated.ts` (`YOLO_CLASS_MAP`), dataset `data.yaml`
(`class_schema.py data-yaml --path DIR`, tier A by default; `screenshot_pipeline.py` uses the same renderer).

Legacy aliases (old 12-class gate-era weights): `SWITCH`, `INPUT` -> `INPUT_PORT`; `OUTPUT`, `LED` -> `OUTPUT_PORT`;
the gate names and `JUNCTION` are unchanged. Old weights emit these names upper-case, matching the alias keys.
Legacy ids differ from the canonical ids, so the frontend ONNX decoder uses `legacy_order` from `classes.yaml`
(AND=0 ... JUNCTION=11) when the model output has exactly 12 classes, and the canonical order otherwise.
The backend is unaffected because it reads class names from the model weights.

## Training Phases

| Phase | Classes Active | Stages Active | Threshold |
|-------|---------------|---------------|-----------|
| 1 | AND, OR, NOT | 1 only | F1 ≥ 0.95, acc ≥ 0.95 per class |
| 2 | All 12 | 1 only | same |
| 3 | All 12 | 1 + 2 + 3 | same |
| 4 | All 12 | 1 + 2 + 3 + 4 | same |
| 1 | NMOS, PMOS, VDD, GND | 1 only | F1 >= 0.95, acc >= 0.95 per class |
| 2 | All 14 tier A | 1 only | same on synthetic held-out-style test; real held-out set F1 >= 0.85 per class with >= 30 test instances; JUNCTION recall >= 0.90 |
| 3 | All 14 tier A | 1 + 2 + 3 | same |
| 4 | All 14 tier A | 1 + 2 + 3 + 4 | same |

All 12 classes: `AND OR NOT NAND NOR XOR XNOR Switch Input Output LED Junction`
Tier B classes are trained after phase 4.

Current phase: `ml/experiments/current_phase.txt`

Expand Down
9 changes: 5 additions & 4 deletions backend/data_gen/screenshot_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@
from data_gen.symbols import ( # noqa: E402
CLASS_NAMES,
CLASS_TO_ID,
SCHEMA,
DrawnSymbol,
draw_symbol,
hand_stroke,
render_data_yaml,
)

REPO_ROOT = Path(__file__).resolve().parents[2]
Expand Down Expand Up @@ -145,7 +147,7 @@ def place(name: str, cx: float, cy: float, s: float) -> DrawnSymbol:
"""Draw one symbol, record its annotation, and return it."""
sym = draw_symbol(img, name, cx, cy, s * rng.uniform(0.88, 1.12), color, thickness, rng)
symbols.append(sym)
counts[name] += 1
counts[CLASS_NAMES[CLASS_TO_ID[name]]] += 1
return sym

# Sources on the left: INPUT boxes or SWITCH symbols.
Expand Down Expand Up @@ -253,7 +255,7 @@ def _write_yolo_label(
def _convert_roboflow_split(split_src: str, split_dst: str, out_dir: Path, counts: Counter) -> int:
"""
Copy one Roboflow split into the merged dataset, converting polygon labels
to bounding boxes and remapping class ids to the canonical 12-class list.
to bounding boxes and remapping class ids to the canonical class list (ml/classes.yaml).

Args:
split_src: Roboflow split directory name ('train', 'valid', 'test').
Expand Down Expand Up @@ -343,8 +345,7 @@ def build_dataset(out_dir: Path, count: int, seed: int) -> None:
print(f"roboflow {split}: {n} images merged")
counts.update(rf_counts)

yaml_text = f"path: {out_dir.resolve()}\ntrain: images/train\nval: images/valid\ntest: images/test\nnc: {len(CLASS_NAMES)}\nnames: {CLASS_NAMES}\n"
(out_dir / "data.yaml").write_text(yaml_text)
(out_dir / "data.yaml").write_text(render_data_yaml(SCHEMA, out_dir))

total = sum(counts.values())
max_count = max(counts.values())
Expand Down
33 changes: 16 additions & 17 deletions backend/data_gen/symbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,27 @@
screenshot pipeline can auto-generate YOLO labels and route wires.
"""

import sys
from dataclasses import dataclass, field
from pathlib import Path

import cv2
import numpy as np

# Canonical class list for the whole ML pipeline (ids are the YOLO class ids).
CLASS_NAMES: list[str] = [
"AND",
"OR",
"NOT",
"NAND",
"NOR",
"XOR",
"XNOR",
"SWITCH",
"INPUT",
"OUTPUT",
"LED",
"JUNCTION",
]

CLASS_TO_ID: dict[str, int] = {name: i for i, name in enumerate(CLASS_NAMES)}
# Canonical class list for the whole ML pipeline, loaded from ml/classes.yaml (the single
# source of truth). CLASS_NAMES index == YOLO class id (tier A only); CLASS_TO_ID also
# resolves legacy gate-era names (SWITCH, INPUT, OUTPUT, LED) to their canonical class id,
# because this renderer still draws those symbols.
_ML_DIR = Path(__file__).resolve().parents[2] / "ml"
if str(_ML_DIR) not in sys.path:
sys.path.insert(0, str(_ML_DIR))

from class_schema import load_schema, render_data_yaml # noqa: E402,F401 (render_data_yaml re-exported)

SCHEMA = load_schema()
CLASS_NAMES: list[str] = [c.name for c in SCHEMA.classes_up_to("A")]
CLASS_TO_ID: dict[str, int] = {name: i for i, name in enumerate(SCHEMA.names)}
CLASS_TO_ID.update({alias: CLASS_TO_ID[canonical] for alias, canonical in SCHEMA.aliases.items()})


@dataclass
Expand Down
67 changes: 67 additions & 0 deletions backend/pipeline/class_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
Module: class_map.py
Purpose: AUTO-GENERATED from ml/classes.yaml by ml/class_schema.py - do not edit by hand.
Class vocabulary data for the detector: canonical names by YOLO id, legacy aliases
that old weights still predict, and the class-to-frontend-node-type map.
Regenerate with `cd ml && uv run python class_schema.py generate`.
"""

# Canonical class names; the index is the YOLO class id.
CLASS_NAMES: tuple[str, ...] = (
"NMOS",
"PMOS",
"VDD",
"GND",
"INPUT_PORT",
"OUTPUT_PORT",
"JUNCTION",
"AND",
"OR",
"NOT",
"NAND",
"NOR",
"XOR",
"XNOR",
"RESISTOR",
"CAPACITOR",
"INDUCTOR",
"BJT_NPN",
"BJT_PNP",
"CLOCK",
)

# Legacy (gate-era) class names -> canonical class, so old weights keep resolving.
CLASS_ALIASES: dict[str, str] = {
"SWITCH": "INPUT_PORT",
"INPUT": "INPUT_PORT",
"OUTPUT": "OUTPUT_PORT",
"LED": "OUTPUT_PORT",
}

# Class name (canonical and legacy) -> ReactFlow node type used by the frontend.
CLASS_TO_NODE_TYPE: dict[str, str] = {
"NMOS": "nmos",
"PMOS": "pmos",
"VDD": "vsource",
"GND": "ground",
"INPUT_PORT": "input",
"OUTPUT_PORT": "output",
"JUNCTION": "junction",
"AND": "andGate",
"OR": "orGate",
"NOT": "notGate",
"NAND": "nandGate",
"NOR": "norGate",
"XOR": "xorGate",
"XNOR": "xnorGate",
"RESISTOR": "resistor",
"CAPACITOR": "capacitor",
"INDUCTOR": "inductor",
"BJT_NPN": "bjtNpn",
"BJT_PNP": "bjtPnp",
"CLOCK": "clockSource",
"SWITCH": "input",
"INPUT": "input",
"OUTPUT": "output",
"LED": "output",
}
38 changes: 16 additions & 22 deletions backend/pipeline/detector.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
"""
Module: detector.py
Purpose: YOLOv8 gate detection stage — takes a circuit image and returns bounding boxes
with class labels for all detected logic gates. Runs fully local inference
with the transfer-learned weights produced by ml/train.py.
Purpose: YOLOv8 symbol detection stage — takes a circuit image and returns bounding boxes
with class labels for all detected circuit symbols (transistors, supplies, ports,
gates, junctions). Runs fully local inference with the transfer-learned weights
produced by ml/train.py. The class vocabulary comes from ml/classes.yaml via the
generated pipeline/class_map.py; legacy gate-era names stay resolvable as aliases.
"""

from dataclasses import dataclass
from pathlib import Path

from ultralytics import YOLO

from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TO_NODE_TYPE

__all__ = [
"CLASS_ALIASES",
"CLASS_NAMES",
"CLASS_TO_NODE_TYPE",
"Detection",
"GateDetector",
]


@dataclass
class Detection:
"""A single gate detection result from the YOLO model."""
"""A single symbol detection result from the YOLO model."""

class_name: str
confidence: float
Expand All @@ -38,24 +50,6 @@ def box(self) -> tuple[float, float, float, float]:
)


# Canonical model class names → ReactFlow node types used by the frontend.
# SWITCH acts as a toggleable input; LED acts as an output indicator.
CLASS_TO_NODE_TYPE: dict[str, str] = {
"AND": "andGate",
"OR": "orGate",
"NOT": "notGate",
"NAND": "nandGate",
"NOR": "norGate",
"XOR": "xorGate",
"XNOR": "xnorGate",
"SWITCH": "input",
"INPUT": "input",
"OUTPUT": "output",
"LED": "output",
"JUNCTION": "junction",
}


class GateDetector:
"""Runs local YOLOv8 inference to detect logic gates in a circuit image."""

Expand Down
1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies = [
"onnxslim>=0.1.96",
"pytest>=9.1.1",
"google-generativeai>=0.8.6",
"pyyaml>=6.0",
]

[dependency-groups]
Expand Down
90 changes: 90 additions & 0 deletions backend/test_class_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""
Module: test_class_schema.py
Purpose: Contract tests tying the backend detector class map to ml/classes.yaml, the single
source of truth for the detector vocabulary. Also verifies the generated files are
not stale and that legacy gate-era class names still resolve for old weights.
"""

import importlib.util
import sys
from pathlib import Path

import yaml

REPO_ROOT = Path(__file__).resolve().parent.parent
SCHEMA_PATH = REPO_ROOT / "ml" / "classes.yaml"

from pipeline import detector # noqa: E402
from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TO_NODE_TYPE # noqa: E402


def _load_class_schema_module():
"""
Import ml/class_schema.py (not on the backend path) as a module.

Returns:
The imported class_schema module.
"""
spec = importlib.util.spec_from_file_location("class_schema", REPO_ROOT / "ml" / "class_schema.py")
module = importlib.util.module_from_spec(spec)
sys.modules["class_schema"] = module
spec.loader.exec_module(module)
return module


def _yaml_doc() -> dict:
"""
Parse ml/classes.yaml directly, independent of the generator.

Returns:
The parsed YAML document.
"""
return yaml.safe_load(SCHEMA_PATH.read_text())


def test_backend_map_equals_yaml():
"""CLASS_TO_NODE_TYPE holds exactly the YAML classes plus legacy aliases."""
doc = _yaml_doc()
expected = {c["name"]: c["node_type"] for c in doc["classes"]}
for alias, canonical in doc["aliases"].items():
expected[alias] = expected[canonical]
assert CLASS_TO_NODE_TYPE == expected
assert detector.CLASS_TO_NODE_TYPE is CLASS_TO_NODE_TYPE


def test_class_names_follow_yolo_ids():
"""CLASS_NAMES is ordered so that index equals the YOLO class id from the YAML."""
doc = _yaml_doc()
assert list(CLASS_NAMES) == [c["name"] for c in sorted(doc["classes"], key=lambda c: c["id"])]
assert [c["id"] for c in doc["classes"]] == list(range(len(doc["classes"])))
assert CLASS_ALIASES == doc["aliases"]


def test_generated_files_are_fresh():
"""Generated backend and frontend files match what the generator renders from the YAML."""
schema_mod = _load_class_schema_module()
assert schema_mod.stale_files(schema_mod.load_schema()) == []


def test_legacy_names_resolve_for_old_weights():
"""The 12 upper-case gate-era names an old model predicts keep their node types."""
legacy = ["AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR", "SWITCH", "INPUT", "OUTPUT", "LED", "JUNCTION"]
assert all(n in CLASS_TO_NODE_TYPE for n in legacy)
assert CLASS_TO_NODE_TYPE["AND"] == "andGate"
assert CLASS_TO_NODE_TYPE["SWITCH"] == "input"
assert CLASS_TO_NODE_TYPE["INPUT"] == "input"
assert CLASS_TO_NODE_TYPE["OUTPUT"] == "output"
assert CLASS_TO_NODE_TYPE["LED"] == "output"
assert CLASS_TO_NODE_TYPE["JUNCTION"] == "junction"


def test_data_yaml_uses_tier_a_by_default(tmp_path):
"""The generated data.yaml lists tier A classes in id order and widens with tier B."""
schema_mod = _load_class_schema_module()
schema = schema_mod.load_schema()
doc = yaml.safe_load(schema_mod.render_data_yaml(schema, tmp_path))
tier_a = [c["name"] for c in _yaml_doc()["classes"] if c["tier"] == "A"]
assert doc["names"] == tier_a
assert doc["nc"] == len(tier_a)
wide = yaml.safe_load(schema_mod.render_data_yaml(schema, tmp_path, "B"))
assert wide["names"] == list(CLASS_NAMES)
Loading
Loading