circuitgen 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- circuitgen/__init__.py +31 -0
- circuitgen/ai.py +305 -0
- circuitgen/api.py +106 -0
- circuitgen/colors.py +12 -0
- circuitgen/engine.py +752 -0
- circuitgen/erc.py +298 -0
- circuitgen/motifs.py +281 -0
- circuitgen/optimization.py +132 -0
- circuitgen/placement.py +1112 -0
- circuitgen/routing.py +1045 -0
- circuitgen/symbols.py +379 -0
- circuitgen-0.1.0.dist-info/METADATA +178 -0
- circuitgen-0.1.0.dist-info/RECORD +16 -0
- circuitgen-0.1.0.dist-info/WHEEL +5 -0
- circuitgen-0.1.0.dist-info/licenses/LICENSE +21 -0
- circuitgen-0.1.0.dist-info/top_level.txt +1 -0
circuitgen/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# PACKAGE METADATA
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# PUBLIC API
|
|
7
|
+
|
|
8
|
+
from .api import (
|
|
9
|
+
CircuitResult,
|
|
10
|
+
ValidationResult,
|
|
11
|
+
from_netlist,
|
|
12
|
+
generate,
|
|
13
|
+
list_providers,
|
|
14
|
+
list_symbols,
|
|
15
|
+
render,
|
|
16
|
+
validate,
|
|
17
|
+
)
|
|
18
|
+
from .engine import CircuitError, CircuitModel
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"CircuitResult",
|
|
22
|
+
"ValidationResult",
|
|
23
|
+
"from_netlist",
|
|
24
|
+
"generate",
|
|
25
|
+
"list_providers",
|
|
26
|
+
"list_symbols",
|
|
27
|
+
"render",
|
|
28
|
+
"validate",
|
|
29
|
+
"CircuitError",
|
|
30
|
+
"CircuitModel",
|
|
31
|
+
]
|
circuitgen/ai.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Provider-independent natural-language-to-netlist translation for CircuitGen.
|
|
2
|
+
|
|
3
|
+
Custom components use explicit logical ``pins`` lists, not verified physical pinouts.
|
|
4
|
+
No third-party SDK is required; Python's standard library handles HTTP requests.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
import urllib.parse
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .engine import CircuitError
|
|
17
|
+
|
|
18
|
+
DEFAULT_PROVIDER = "gemini"
|
|
19
|
+
DEFAULT_MODEL = "gemini-2.5-flash"
|
|
20
|
+
|
|
21
|
+
SCHEMA: dict[str, Any] = {
|
|
22
|
+
"type": "object",
|
|
23
|
+
"properties": {
|
|
24
|
+
"components": {
|
|
25
|
+
"type": "array",
|
|
26
|
+
"items": {
|
|
27
|
+
"type": "object",
|
|
28
|
+
"properties": {
|
|
29
|
+
"id": {"type": "string"},
|
|
30
|
+
"type": {"type": "string"},
|
|
31
|
+
"value": {"type": "string"},
|
|
32
|
+
"pins": {"type": "array", "items": {"type": "string"}},
|
|
33
|
+
},
|
|
34
|
+
"required": ["id", "type", "value"],
|
|
35
|
+
"additionalProperties": False,
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
"nets": {
|
|
39
|
+
"type": "array",
|
|
40
|
+
"items": {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"properties": {
|
|
43
|
+
"name": {"type": "string"},
|
|
44
|
+
"pins": {"type": "array", "items": {"type": "string"}},
|
|
45
|
+
},
|
|
46
|
+
"required": ["name", "pins"],
|
|
47
|
+
"additionalProperties": False,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
"required": ["components", "nets"],
|
|
52
|
+
"additionalProperties": False,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
PROMPT = """You are an electrical netlist translator for CircuitGen.
|
|
56
|
+
Convert the user's educational circuit description into a complete JSON
|
|
57
|
+
netlist. Output only the JSON object; no diagrams, Python, SVG, or commentary.
|
|
58
|
+
|
|
59
|
+
REGISTERED COMPONENT TYPES (use these exact lowercase type strings):
|
|
60
|
+
- Two-terminal: resistor, capacitor, inductor, diode, led, switch, lamp,
|
|
61
|
+
fuse, battery, dc_source, ac_source, current_source.
|
|
62
|
+
- Three-/multi-terminal: npn, pnp, nmos, pmos, opamp, ne555, arduino_uno.
|
|
63
|
+
- Custom components: types not listed above are supported using an explicit
|
|
64
|
+
component-level "pins" array (see below).
|
|
65
|
+
|
|
66
|
+
PIN NAMES FOR REGISTERED COMPONENTS:
|
|
67
|
+
- battery/dc_source/ac_source/current_source: p (positive), n (negative)
|
|
68
|
+
- resistor/capacitor/inductor/switch/lamp/fuse: a, b
|
|
69
|
+
- led/diode: a (anode), b (cathode)
|
|
70
|
+
- npn/pnp: B, C, E
|
|
71
|
+
- nmos/pmos: G, D, S
|
|
72
|
+
- opamp: IN+, IN-, OUT, V+, V-
|
|
73
|
+
- ne555: VCC, GND, TRIG, THRES, DISCH, RESET, CTRL, OUT
|
|
74
|
+
(IMPORTANT: pin 6 is THRES, NEVER THRESH)
|
|
75
|
+
- arduino_uno: D0 through D13, A0 through A5, 3V3, 5V, VIN, GND, RESET
|
|
76
|
+
|
|
77
|
+
CUSTOM COMPONENT RULES (CRITICAL):
|
|
78
|
+
1. If a component type is not registered, provide a "pins" array listing
|
|
79
|
+
unique logical pin names for that component. Never omit this field.
|
|
80
|
+
2. Use the SAME case-sensitive pin names in the nets (e.g. S1.SDA).
|
|
81
|
+
3. Example generic I2C sensor:
|
|
82
|
+
{"id":"S1","type":"i2c_sensor","value":"generic",
|
|
83
|
+
"pins":["SDA","SCL","VCC","GND"]}
|
|
84
|
+
These names are a logical interface for a user-described generic sensor;
|
|
85
|
+
they are NOT a verified physical package pinout.
|
|
86
|
+
4. Pin names may contain letters, digits, underscore, + and - (1-24 chars).
|
|
87
|
+
Keep component types lowercase with underscores, e.g. i2c_sensor.
|
|
88
|
+
5. For a *specific* unfamiliar IC/module whose pinout was not supplied,
|
|
89
|
+
do not invent a real-world physical pinout. Use only the logical pins
|
|
90
|
+
clearly specified by the user. Do not claim physical pin numbers.
|
|
91
|
+
6. Registered components normally omit "pins" because CircuitGen already
|
|
92
|
+
knows them. If supplied, the list must match the registered pins exactly.
|
|
93
|
+
|
|
94
|
+
GENERAL NETLIST RULES:
|
|
95
|
+
1. Preserve explicitly requested components, values, and connections.
|
|
96
|
+
2. Assign a unique ID to every component and unique name to every net.
|
|
97
|
+
3. Each physical/logical pin may belong to AT MOST one net.
|
|
98
|
+
4. A net connects electrically identical nodes, potentially many pins.
|
|
99
|
+
5. Never create different nets for points directly wired together.
|
|
100
|
+
6. Never invent intermediate components or silently change a part's type.
|
|
101
|
+
7. Unused pins on multi-pin components may remain unconnected: do not
|
|
102
|
+
invent connections simply to fill their pins.
|
|
103
|
+
8. Support series, parallel, bridges, feedback, transistors, and ICs.
|
|
104
|
+
9. Match polarity and directions, especially LED anode/cathode.
|
|
105
|
+
10. Return exactly "components" and "nets" at the top level.
|
|
106
|
+
11. For every net terminal reference, use "componentID.pinName" and ensure
|
|
107
|
+
that pinName is defined by the registered symbol or the custom pin list.
|
|
108
|
+
|
|
109
|
+
EXAMPLE — Arduino Uno with custom I2C sensor:
|
|
110
|
+
{
|
|
111
|
+
"components": [
|
|
112
|
+
{"id":"U1","type":"arduino_uno","value":"Arduino Uno"},
|
|
113
|
+
{"id":"S1","type":"i2c_sensor","value":"generic",
|
|
114
|
+
"pins":["SDA","SCL","VCC","GND"]}
|
|
115
|
+
],
|
|
116
|
+
"nets": [
|
|
117
|
+
{"name":"SDA_LINE","pins":["U1.A4","S1.SDA"]},
|
|
118
|
+
{"name":"SCL_LINE","pins":["U1.A5","S1.SCL"]},
|
|
119
|
+
{"name":"VCC","pins":["U1.5V","S1.VCC"]},
|
|
120
|
+
{"name":"GND","pins":["U1.GND","S1.GND"]}
|
|
121
|
+
]
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
User description:
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
PROVIDERS: dict[str, dict[str, str]] = {
|
|
128
|
+
"gemini": {"key": "GEMINI_API_KEY", "model": DEFAULT_MODEL},
|
|
129
|
+
"openai": {"key": "OPENAI_API_KEY", "model": "gpt-4.1-mini",
|
|
130
|
+
"url": "https://api.openai.com/v1/chat/completions"},
|
|
131
|
+
"anthropic": {"key": "ANTHROPIC_API_KEY", "model": "claude-sonnet-4-5",
|
|
132
|
+
"url": "https://api.anthropic.com/v1/messages"},
|
|
133
|
+
"deepseek": {"key": "DEEPSEEK_API_KEY", "model": "deepseek-chat",
|
|
134
|
+
"url": "https://api.deepseek.com/chat/completions"},
|
|
135
|
+
"groq": {"key": "GROQ_API_KEY", "model": "llama-3.3-70b-versatile",
|
|
136
|
+
"url": "https://api.groq.com/openai/v1/chat/completions"},
|
|
137
|
+
"mistral": {"key": "MISTRAL_API_KEY", "model": "mistral-small-latest",
|
|
138
|
+
"url": "https://api.mistral.ai/v1/chat/completions"},
|
|
139
|
+
"xai": {"key": "XAI_API_KEY", "model": "grok-3-mini",
|
|
140
|
+
"url": "https://api.x.ai/v1/chat/completions"},
|
|
141
|
+
"openrouter": {"key": "OPENROUTER_API_KEY", "model": "openai/gpt-4.1-mini",
|
|
142
|
+
"url": "https://openrouter.ai/api/v1/chat/completions"},
|
|
143
|
+
"together": {"key": "TOGETHER_API_KEY", "model": "meta-llama/Llama-3.3-70B-Instruct-Turbo",
|
|
144
|
+
"url": "https://api.together.xyz/v1/chat/completions"},
|
|
145
|
+
"fireworks": {"key": "FIREWORKS_API_KEY", "model": "accounts/fireworks/models/llama-v3p3-70b-instruct",
|
|
146
|
+
"url": "https://api.fireworks.ai/inference/v1/chat/completions"},
|
|
147
|
+
"cerebras": {"key": "CEREBRAS_API_KEY", "model": "llama-3.3-70b",
|
|
148
|
+
"url": "https://api.cerebras.ai/v1/chat/completions"},
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
ALIASES = {"google": "gemini", "claude": "anthropic", "chatgpt": "openai", "grok": "xai"}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def list_providers() -> list[str]:
|
|
155
|
+
"""Return supported provider identifiers."""
|
|
156
|
+
return list(PROVIDERS)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _post_json(url: str, payload: dict[str, Any], headers: dict[str, str],
|
|
160
|
+
provider: str) -> dict[str, Any]:
|
|
161
|
+
req = urllib.request.Request(
|
|
162
|
+
url,
|
|
163
|
+
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
|
164
|
+
headers={"Content-Type": "application/json", **headers},
|
|
165
|
+
method="POST",
|
|
166
|
+
)
|
|
167
|
+
try:
|
|
168
|
+
with urllib.request.urlopen(req, timeout=120) as res:
|
|
169
|
+
data = json.loads(res.read().decode("utf-8"))
|
|
170
|
+
except urllib.error.HTTPError as exc:
|
|
171
|
+
detail = exc.read().decode("utf-8", errors="replace")[:700]
|
|
172
|
+
raise CircuitError(f"{provider} API HTTP {exc.code}: {detail}") from exc
|
|
173
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
174
|
+
raise CircuitError(f"{provider} API connection problem: {exc}") from exc
|
|
175
|
+
except (ValueError, UnicodeError) as exc:
|
|
176
|
+
raise CircuitError(f"{provider} API returned invalid response JSON") from exc
|
|
177
|
+
if not isinstance(data, dict):
|
|
178
|
+
raise CircuitError(f"{provider} API response was not an object")
|
|
179
|
+
if data.get("error"):
|
|
180
|
+
raise CircuitError(f"{provider} API error: {str(data['error'])[:700]}")
|
|
181
|
+
return data
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _parse_netlist(raw: str, provider: str) -> dict[str, Any]:
|
|
185
|
+
text = raw.strip()
|
|
186
|
+
if text.startswith("```"):
|
|
187
|
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE)
|
|
188
|
+
text = re.sub(r"\s*```$", "", text).strip()
|
|
189
|
+
try:
|
|
190
|
+
decoded = json.loads(text)
|
|
191
|
+
except (ValueError, TypeError) as exc:
|
|
192
|
+
raise CircuitError(f"{provider} did not return valid netlist JSON") from exc
|
|
193
|
+
if not isinstance(decoded, dict):
|
|
194
|
+
raise CircuitError(f"{provider} JSON was not an object")
|
|
195
|
+
if not isinstance(decoded.get("components"), list) or not isinstance(decoded.get("nets"), list):
|
|
196
|
+
raise CircuitError(f"{provider} JSON must contain components and nets arrays")
|
|
197
|
+
return decoded
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _gemini(full_text: str, model: str, key: str) -> str:
|
|
201
|
+
payload = {
|
|
202
|
+
"contents": [{"role": "user", "parts": [{"text": full_text}]}],
|
|
203
|
+
"generationConfig": {
|
|
204
|
+
"temperature": 0,
|
|
205
|
+
"responseMimeType": "application/json",
|
|
206
|
+
"responseJsonSchema": SCHEMA,
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
safe_model = urllib.parse.quote(model, safe="-._/")
|
|
210
|
+
data = _post_json(
|
|
211
|
+
f"https://generativelanguage.googleapis.com/v1beta/models/{safe_model}:generateContent",
|
|
212
|
+
payload, {"x-goog-api-key": key}, "gemini",
|
|
213
|
+
)
|
|
214
|
+
try:
|
|
215
|
+
parts = data["candidates"][0]["content"]["parts"]
|
|
216
|
+
return "".join(part.get("text", "") for part in parts)
|
|
217
|
+
except (KeyError, IndexError, TypeError) as exc:
|
|
218
|
+
raise CircuitError("Gemini returned no usable text (possibly blocked or truncated)") from exc
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _anthropic(full_text: str, model: str, key: str) -> str:
|
|
222
|
+
payload = {
|
|
223
|
+
"model": model,
|
|
224
|
+
"max_tokens": 8192,
|
|
225
|
+
"temperature": 0,
|
|
226
|
+
"system": "Return only the requested JSON netlist. No markdown or commentary.",
|
|
227
|
+
"messages": [{"role": "user", "content": full_text}],
|
|
228
|
+
}
|
|
229
|
+
data = _post_json(
|
|
230
|
+
PROVIDERS["anthropic"]["url"], payload,
|
|
231
|
+
{"x-api-key": key, "anthropic-version": "2023-06-01"}, "anthropic",
|
|
232
|
+
)
|
|
233
|
+
if data.get("stop_reason") == "max_tokens":
|
|
234
|
+
raise CircuitError("Anthropic response was truncated; try a simpler circuit")
|
|
235
|
+
blocks = data.get("content", [])
|
|
236
|
+
raw = "".join(block.get("text", "") for block in blocks if block.get("type") == "text")
|
|
237
|
+
if not raw.strip():
|
|
238
|
+
raise CircuitError("Anthropic returned no text")
|
|
239
|
+
return raw
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _openai_compatible(full_text: str, provider: str, model: str, key: str) -> str:
|
|
243
|
+
payload = {
|
|
244
|
+
"model": model,
|
|
245
|
+
"messages": [
|
|
246
|
+
{"role": "system", "content": "Return only one valid JSON object. No markdown."},
|
|
247
|
+
{"role": "user", "content": full_text},
|
|
248
|
+
],
|
|
249
|
+
}
|
|
250
|
+
data = _post_json(
|
|
251
|
+
PROVIDERS[provider]["url"], payload,
|
|
252
|
+
{"Authorization": f"Bearer {key}"}, provider,
|
|
253
|
+
)
|
|
254
|
+
try:
|
|
255
|
+
choice = data["choices"][0]
|
|
256
|
+
if choice.get("finish_reason") == "length":
|
|
257
|
+
raise CircuitError(f"{provider} response was truncated")
|
|
258
|
+
content = choice["message"]["content"]
|
|
259
|
+
if isinstance(content, str):
|
|
260
|
+
return content
|
|
261
|
+
if isinstance(content, list):
|
|
262
|
+
return "".join(part.get("text", "") for part in content if isinstance(part, dict))
|
|
263
|
+
raise TypeError("No text content")
|
|
264
|
+
except (KeyError, IndexError, TypeError) as exc:
|
|
265
|
+
raise CircuitError(f"{provider} returned no usable text") from exc
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def generate_netlist(
|
|
269
|
+
user_prompt: str,
|
|
270
|
+
provider: str = DEFAULT_PROVIDER,
|
|
271
|
+
model: str | None = None,
|
|
272
|
+
correction: str = "",
|
|
273
|
+
) -> dict[str, Any]:
|
|
274
|
+
"""Generate a JSON netlist using the selected AI provider.
|
|
275
|
+
|
|
276
|
+
Returns an unvalidated dict; pass it to the existing engine validator.
|
|
277
|
+
"""
|
|
278
|
+
if not isinstance(user_prompt, str) or not user_prompt.strip():
|
|
279
|
+
raise CircuitError("Circuit description must be a nonempty string")
|
|
280
|
+
provider = ALIASES.get(provider.strip().lower(), provider.strip().lower())
|
|
281
|
+
if provider not in PROVIDERS:
|
|
282
|
+
raise CircuitError(
|
|
283
|
+
f"Unsupported AI provider: {provider}. Available: {', '.join(list_providers())}"
|
|
284
|
+
)
|
|
285
|
+
settings = PROVIDERS[provider]
|
|
286
|
+
chosen_model = model or settings["model"]
|
|
287
|
+
if not isinstance(chosen_model, str) or not chosen_model.strip():
|
|
288
|
+
raise CircuitError("Model must be a nonempty string")
|
|
289
|
+
key = os.environ.get(settings["key"], "").strip()
|
|
290
|
+
if not key:
|
|
291
|
+
raise CircuitError(f"{settings['key']} is not set")
|
|
292
|
+
|
|
293
|
+
full_text = PROMPT + user_prompt
|
|
294
|
+
if correction:
|
|
295
|
+
full_text += (
|
|
296
|
+
"\n\nPREVIOUS OUTPUT WAS REJECTED. Return a corrected full netlist. "
|
|
297
|
+
"Do not claim unsupported circuit is possible. Error: " + correction[:900]
|
|
298
|
+
)
|
|
299
|
+
if provider == "gemini":
|
|
300
|
+
raw = _gemini(full_text, chosen_model, key)
|
|
301
|
+
elif provider == "anthropic":
|
|
302
|
+
raw = _anthropic(full_text, chosen_model, key)
|
|
303
|
+
else:
|
|
304
|
+
raw = _openai_compatible(full_text, provider, chosen_model, key)
|
|
305
|
+
return _parse_netlist(raw, provider)
|
circuitgen/api.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .ai import generate_netlist, list_providers
|
|
8
|
+
from .engine import CircuitError, CircuitModel, make_svg_from_netlist, validate_model
|
|
9
|
+
from .routing import make_routed_svg
|
|
10
|
+
from .symbols import BUILTIN_SYMBOLS
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# RESULTS
|
|
14
|
+
|
|
15
|
+
@dataclasses.dataclass
|
|
16
|
+
class CircuitResult:
|
|
17
|
+
svg: str
|
|
18
|
+
netlist: dict[str, Any]
|
|
19
|
+
model: CircuitModel | None = None
|
|
20
|
+
output_path: str | None = None
|
|
21
|
+
|
|
22
|
+
def save(self, path: str | Path) -> str:
|
|
23
|
+
dest = Path(path)
|
|
24
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
dest.write_text(self.svg, encoding="utf-8")
|
|
26
|
+
self.output_path = str(dest)
|
|
27
|
+
return self.output_path
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclasses.dataclass(frozen=True)
|
|
31
|
+
class ValidationResult:
|
|
32
|
+
valid: bool
|
|
33
|
+
errors: list[str] = dataclasses.field(default_factory=list)
|
|
34
|
+
model: CircuitModel | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# DISCOVERY
|
|
38
|
+
|
|
39
|
+
def list_symbols() -> list[str]:
|
|
40
|
+
return sorted(BUILTIN_SYMBOLS.keys())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# VALIDATION
|
|
44
|
+
|
|
45
|
+
def validate(data: dict[str, Any]) -> ValidationResult:
|
|
46
|
+
try:
|
|
47
|
+
model = validate_model(data)
|
|
48
|
+
return ValidationResult(valid=True, errors=[], model=model)
|
|
49
|
+
except (CircuitError, ValueError, TypeError, KeyError) as exc:
|
|
50
|
+
return ValidationResult(valid=False, errors=[str(exc)], model=None)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# RENDERING
|
|
54
|
+
|
|
55
|
+
def render(
|
|
56
|
+
model: CircuitModel | dict[str, Any],
|
|
57
|
+
*,
|
|
58
|
+
optimize: bool = False,
|
|
59
|
+
color: str = "#000000",
|
|
60
|
+
) -> str:
|
|
61
|
+
if isinstance(model, CircuitModel):
|
|
62
|
+
return make_routed_svg(model, optimize=optimize, color=color)
|
|
63
|
+
if isinstance(model, dict):
|
|
64
|
+
return make_svg_from_netlist(model, optimize=optimize, color=color)
|
|
65
|
+
raise TypeError(f"Expected CircuitModel or netlist dict, got {type(model).__name__}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# WORKFLOWS
|
|
69
|
+
|
|
70
|
+
def from_netlist(
|
|
71
|
+
data: dict[str, Any],
|
|
72
|
+
*,
|
|
73
|
+
output: str | Path | None = None,
|
|
74
|
+
optimize: bool = False,
|
|
75
|
+
color: str = "#000000",
|
|
76
|
+
) -> CircuitResult:
|
|
77
|
+
model = validate_model(data)
|
|
78
|
+
svg = make_svg_from_netlist(data, optimize=optimize, color=color)
|
|
79
|
+
result = CircuitResult(svg=svg, netlist=data, model=model)
|
|
80
|
+
if output is not None:
|
|
81
|
+
result.save(output)
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def generate(
|
|
86
|
+
description: str,
|
|
87
|
+
*,
|
|
88
|
+
provider: str = "gemini",
|
|
89
|
+
model: str | None = None,
|
|
90
|
+
output: str | Path | None = None,
|
|
91
|
+
optimize: bool = False,
|
|
92
|
+
color: str = "#000000",
|
|
93
|
+
correction: str = "",
|
|
94
|
+
) -> CircuitResult:
|
|
95
|
+
netlist = generate_netlist(
|
|
96
|
+
description,
|
|
97
|
+
provider=provider,
|
|
98
|
+
model=model,
|
|
99
|
+
correction=correction,
|
|
100
|
+
)
|
|
101
|
+
return from_netlist(
|
|
102
|
+
netlist,
|
|
103
|
+
output=output,
|
|
104
|
+
optimize=optimize,
|
|
105
|
+
color=color,
|
|
106
|
+
)
|
circuitgen/colors.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Consistent, configurable schematic ink color."""
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
_COLOR = re.compile(r"#[0-9a-fA-F]{6}\Z")
|
|
5
|
+
_HEX_IN_SVG = re.compile(r"#[0-9a-fA-F]{6}\b")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def apply_ink_color(svg: str, color: str = "#000000") -> str:
|
|
9
|
+
"""Recolor schematic ink while preserving white symbol fills."""
|
|
10
|
+
if not isinstance(color, str) or not _COLOR.fullmatch(color):
|
|
11
|
+
raise ValueError("color must be a six-digit hex string, e.g. '#000000'")
|
|
12
|
+
return _HEX_IN_SVG.sub(lambda m: m.group(0) if m.group(0).lower() == '#ffffff' else color, svg)
|