Repository navigation
Expand file tree
/
Copy pathgenerate.py
More file actions
193 lines (165 loc) · 12.1 KB
/
Copy pathgenerate.py
File metadata and controls
193 lines (165 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""
CircuitMind - Generate Module
generate/generate.py
Converts a natural language prompt into a structured circuit JSON.
Strategy: LLM (Groq) first → rule-based fallback if LLM is unavailable.
"""
import json
import os
import re
import logging
logger = logging.getLogger(__name__)
try:
from groq import Groq
GROQ_AVAILABLE = True
except ImportError:
GROQ_AVAILABLE = False
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
# ── Input Validation ───────────────────────────────────────────────────────────
def validate_input(prompt: str) -> str:
if not prompt or len(prompt.strip()) == 0:
raise ValueError("Input cannot be empty. Try: 'make me a LED circuit'")
if len(prompt.strip()) < 3:
raise ValueError("Input too short. Try: 'make me a LED circuit'")
if len(prompt) > 1000:
raise ValueError("Input too long. Keep it under 1000 characters.")
return prompt.strip()
# ── Rule-Based Fallback ────────────────────────────────────────────────────────
_RULES = [
# ── Digital Logic Circuits ──────────────────────────────────────────────────
(["odd parity", "odd_parity"], "Odd Parity Generator", ["input_a", "input_b", "input_c", "xor1", "xnor2", "parity_output"], ["input_a -> xor1 -> xnor2 -> parity_output", "input_b -> xor1", "input_c -> xnor2"], "3-bit odd parity generator circuit"),
(["even parity", "even_parity"], "Even Parity Generator", ["input_a", "input_b", "input_c", "xor1", "xor2", "parity_output"], ["input_a -> xor1 -> xor2 -> parity_output", "input_b -> xor1", "input_c -> xor2"], "3-bit even parity generator circuit"),
# Use full phrases here — matching is substring OR, so ["half", "adder"]
# would also fire on "half subtractor" (and vice versa) because of "half".
(["half subtractor", "half-subtractor", "half_subtractor", "halfsubtractor"],
"Half Subtractor Circuit", ["input_a", "input_b", "xor", "not", "and", "diff_output", "borrow_output"], ["input_a -> xor -> diff_output", "input_b -> xor", "input_a -> not -> and -> borrow_output", "input_b -> and"], "Half subtractor circuit computing difference and borrow"),
(["full subtractor", "full-subtractor", "full_subtractor", "fullsubtractor"],
"Full Subtractor Circuit", ["input_a", "input_b", "bin", "xor1", "xor2", "not1", "and1", "not2", "and2", "or", "diff_output", "borrow_output"], ["input_a -> xor1 -> xor2 -> diff_output", "input_b -> xor1", "bin -> xor2", "input_a -> not1 -> and1 -> or -> borrow_output", "input_b -> and1", "xor1 -> not2 -> and2 -> or", "bin -> and2"], "Full subtractor circuit with borrow-in"),
(["half adder", "half-adder", "half_adder", "halfadder"],
"Half Adder Circuit", ["input_a", "input_b", "xor", "and", "sum_output", "carry_output"], ["input_a -> xor -> sum_output", "input_b -> xor", "input_a -> and -> carry_output", "input_b -> and"], "Half adder circuit computing sum and carry"),
(["full adder", "full-adder", "full_adder", "fulladder"],
"Full Adder Circuit", ["input_a", "input_b", "cin", "xor1", "xor2", "and1", "and2", "or", "sum_output", "cout"], ["input_a -> xor1 -> xor2 -> sum_output", "input_b -> xor1", "cin -> xor2", "input_a -> and1 -> or -> cout", "input_b -> and1", "xor1 -> and2 -> or", "cin -> and2"], "Full adder circuit with carry-in"),
(["multiplexer", "mux"], "2-to-1 Multiplexer", ["input_a", "input_b", "sel", "not", "and1", "and2", "or", "output"], ["input_a -> and1 -> or -> output", "sel -> not -> and1", "input_b -> and2 -> or", "sel -> and2"], "2-to-1 multiplexer circuit"),
(["demultiplexer", "demux"], "1-to-2 Demultiplexer", ["input_din", "sel", "not", "and1", "and2", "output_y0", "output_y1"], ["input_din -> and1 -> output_y0", "sel -> not -> and1", "input_din -> and2 -> output_y1", "sel -> and2"], "1-to-2 demultiplexer circuit"),
(["decoder"], "2-to-4 Decoder", ["input_a", "input_b", "not_a", "not_b", "and0", "and1", "and2", "and3", "y0", "y1", "y2", "y3"], ["input_a -> not_a -> and0 -> y0", "input_b -> not_b -> and0", "input_a -> and1 -> y1", "input_b -> not_b -> and1", "input_a -> not_a -> and2 -> y2", "input_b -> and2", "input_a -> and3 -> y3", "input_b -> and3"], "2-to-4 line decoder circuit"),
(["comparator"], "1-Bit Comparator", ["input_a", "input_b", "not_a", "not_b", "xnor", "and_gt", "and_lt", "eq_out", "gt_out", "lt_out"], ["input_a -> xnor -> eq_out", "input_b -> xnor", "input_a -> and_gt -> gt_out", "input_b -> not_b -> and_gt", "input_a -> not_a -> and_lt -> lt_out", "input_b -> and_lt"], "1-bit magnitude comparator"),
(["xor", "xnor"], "XOR / XNOR Circuit", ["input_a", "input_b", "xor", "output"], ["input_a -> xor -> output", "input_b -> xor"], "2-input XOR gate circuit"),
(["logic gate", "logic circuit"], "Logic Gate Circuit", ["input_a", "input_b", "and", "or", "output"], ["input_a -> and -> or -> output", "input_b -> and", "input_b -> or"], "Combinational logic gate circuit"),
# ── Analog / IC Circuits ─────────────────────────────────────────────────────
(["led", "light"], "LED Circuit", ["battery", "resistor", "led"], ["battery -> resistor -> led"], "Basic LED circuit with current-limiting resistor"),
(["motor"], "Motor Circuit", ["battery", "switch", "dc_motor"], ["battery -> switch -> dc_motor"], "Basic DC motor circuit with on/off switch"),
(["buzzer"], "Buzzer Circuit", ["battery", "resistor", "buzzer"], ["battery -> resistor -> buzzer"], "Buzzer circuit with resistor for sound output"),
(["fan"], "Fan Circuit", ["battery", "switch", "capacitor", "dc_motor"], ["battery -> switch -> capacitor -> dc_motor"], "Fan circuit with capacitor for smooth startup"),
(["temperature", "sensor"], "Temperature Sensor", ["battery", "thermistor", "resistor", "microcontroller"],["battery -> thermistor -> resistor -> microcontroller"],"Temperature sensing circuit using thermistor"),
(["solar"], "Solar Charging Circuit", ["solar_cell", "diode", "charge_controller", "battery"],["solar_cell -> diode -> charge_controller -> battery"],"Solar panel battery charging circuit"),
(["555", "ne555", "lm555", "timer"], "555 Timer Circuit", ["battery", "555_timer", "resistor", "capacitor", "led"],["battery -> 555_timer -> resistor -> capacitor -> led"],"555 timer astable multivibrator"),
(["rc", "filter"], "RC Filter Circuit", ["power_supply", "resistor", "capacitor"], ["power_supply -> resistor -> capacitor -> ground"], "RC low-pass filter circuit"),
]
def _build_rule_patterns(rules):
"""
Precompiles a regex per rule that enforces alphanumeric token boundaries
and accepts standard English plural inflections ('s', 'es').
"""
compiled = []
for keywords, name, components, connections, description in rules:
patterns = []
for kw in keywords:
escaped = re.escape(kw)
if kw.endswith(('x', 'ch', 'sh')):
pat = rf'(?<![a-z0-9]){escaped}(?:es|s)?(?![a-z0-9])'
else:
pat = rf'(?<![a-z0-9]){escaped}s?(?![a-z0-9])'
patterns.append(pat)
combined_re = re.compile("|".join(patterns), re.IGNORECASE)
compiled.append((combined_re, name, components, connections, description))
return compiled
_COMPILED_RULES = _build_rule_patterns(_RULES)
def generate_with_rules(prompt: str) -> dict:
p = prompt.lower()
for pattern, name, components, connections, description in _COMPILED_RULES:
if pattern.search(p):
return {
"circuit_name": name,
"components": components,
"connections": connections,
"confidence": "high",
"description": description,
"source": "rule-based",
}
return {
"circuit_name": "Unknown",
"components": [],
"connections": [],
"confidence": "low",
"description": "Circuit not recognised. Try: led, motor, buzzer, fan, temperature, solar, 555 timer, rc filter.",
"source": "rule-based",
}
# ── LLM Generation ────────────────────────────────────────────────────────────
_SYSTEM_PROMPT = (
"You are a circuit generator AI. "
"Convert user requests into circuit JSON. "
"Reply ONLY with valid JSON — no explanation, no markdown, no code blocks.\n"
"IMPORTANT: Use ONLY these exact component names — no prefixes, values, or modifiers:\n"
"battery, power_supply, solar_cell, resistor, capacitor, inductor, potentiometer, "
"diode, led, zener_diode, transistor, npn_transistor, pnp_transistor, mosfet, "
"op_amp, 555_timer, arduino, microcontroller, "
"buzzer, motor, dc_motor, speaker, relay, display, lcd, "
"ldr, thermistor, photodiode, button, switch, sensor, "
"ground, fuse, transformer"
)
_USER_TEMPLATE = (
'Convert this into a circuit JSON:\n\n"{prompt}"\n\n'
"Use exactly this format:\n"
'{{\n'
' "circuit_name": "name of circuit",\n'
' "components": ["component1", "component2"],\n'
' "connections": ["comp1 -> comp2 -> comp3"],\n'
' "confidence": "high",\n'
' "description": "one line explanation"\n'
'}}'
)
def generate_with_llm(prompt: str) -> dict:
if not GROQ_AVAILABLE:
raise RuntimeError("Groq not installed. Run: pip install groq")
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
raise RuntimeError("GROQ_API_KEY not set in environment")
client = Groq(api_key=api_key)
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": _USER_TEMPLATE.format(prompt=prompt)},
],
max_tokens=512,
temperature=0.2,
)
raw = completion.choices[0].message.content.strip()
# Strip accidental markdown fences
if raw.startswith("```"):
parts = raw.split("```")
raw = parts[1].lstrip("json").strip() if len(parts) > 1 else raw
result = json.loads(raw) # raises JSONDecodeError if invalid
result["source"] = "llm"
return result
# ── Public API ────────────────────────────────────────────────────────────────
def generate_circuit(user_prompt: str) -> dict:
"""
Main entry point.
Input: user text e.g. 'make me a LED circuit'
Output: circuit JSON dict — never raises, always returns.
"""
try:
clean_prompt = validate_input(user_prompt)
except ValueError as e:
return {"error": str(e), "error_code": "INVALID_INPUT", "components": [], "connections": []}
try:
logger.info("Attempting LLM generation via Groq")
return generate_with_llm(clean_prompt)
except Exception as e:
logger.warning(f"LLM unavailable ({e}), falling back to rule-based generation")
return generate_with_rules(clean_prompt)