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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import graphviz
|
| 2 |
+
import re
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import pickle
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from torchvision import models, transforms
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
# CONFIG
|
| 12 |
+
VISION_MODEL_PATH = "automata_model.pth"
|
| 13 |
+
LOGIC_MODEL_PATH = "logic_model.pth"
|
| 14 |
+
VISION_CLASSES = ['ADVANCED_TOC', 'DFA', 'MINIMAL_DFA', 'NFA', 'PDA', 'TM', 'TRANSDUCER']
|
| 15 |
+
|
| 16 |
+
# --- NEURAL NETWORK DEFINITION (Must match training) ---
|
| 17 |
+
class LogicBrain(nn.Module):
|
| 18 |
+
def __init__(self, vocab_size, num_intents):
|
| 19 |
+
super(LogicBrain, self).__init__()
|
| 20 |
+
self.embedding = nn.Embedding(vocab_size, 128) # EMBED_DIM
|
| 21 |
+
self.lstm = nn.LSTM(128, 256, num_layers=2, batch_first=True, bidirectional=True) # HIDDEN_DIM
|
| 22 |
+
self.fc = nn.Linear(256 * 2, num_intents)
|
| 23 |
+
|
| 24 |
+
def forward(self, x):
|
| 25 |
+
emb = self.embedding(x)
|
| 26 |
+
out, _ = self.lstm(emb)
|
| 27 |
+
out, _ = torch.max(out, dim=1)
|
| 28 |
+
return self.fc(out)
|
| 29 |
+
|
| 30 |
+
class Vocabulary:
|
| 31 |
+
def __init__(self): self.word2idx = {}
|
| 32 |
+
def encode(self, text, max_len=20):
|
| 33 |
+
tokens = re.findall(r"\w+", text.lower())
|
| 34 |
+
vec = [self.word2idx.get(t, 1) for t in tokens[:max_len]]
|
| 35 |
+
vec += [0] * (max_len - len(vec))
|
| 36 |
+
return vec
|
| 37 |
+
|
| 38 |
+
class AutomataCore:
|
| 39 |
+
def __init__(self):
|
| 40 |
+
self.device = torch.device("cpu")
|
| 41 |
+
|
| 42 |
+
# 1. Load Vision Model (The Eye)
|
| 43 |
+
self.vision_model = self._load_vision()
|
| 44 |
+
|
| 45 |
+
# 2. Load Logic Brain (The NLP Mind)
|
| 46 |
+
self.vocab = None
|
| 47 |
+
self.intents = None
|
| 48 |
+
self.logic_model = self._load_brain()
|
| 49 |
+
|
| 50 |
+
# 3. Logic Map
|
| 51 |
+
self.func_map = {
|
| 52 |
+
"DFA_SUBSTRING": self._dfa_substring,
|
| 53 |
+
"DFA_ENDS_WITH": self._dfa_ends_with,
|
| 54 |
+
"DFA_STARTS_WITH": self._dfa_starts_with,
|
| 55 |
+
"DFA_LENGTH": self._dfa_length,
|
| 56 |
+
"DFA_CONSECUTIVE": self._dfa_consecutive,
|
| 57 |
+
"TM_PALINDROME": self._tm_palindrome,
|
| 58 |
+
"TM_ADDER": self._tm_adder,
|
| 59 |
+
"PDA_ANBN": self._pda_anbn,
|
| 60 |
+
"MOORE_MODULO": self._moore_modulo
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
def _load_vision(self):
|
| 64 |
+
if not os.path.exists(VISION_MODEL_PATH): return None
|
| 65 |
+
try:
|
| 66 |
+
m = models.resnet18(weights=None)
|
| 67 |
+
m.fc = torch.nn.Linear(m.fc.in_features, len(VISION_CLASSES))
|
| 68 |
+
m.load_state_dict(torch.load(VISION_MODEL_PATH, map_location=self.device))
|
| 69 |
+
m.eval()
|
| 70 |
+
return m
|
| 71 |
+
except: return None
|
| 72 |
+
|
| 73 |
+
def _load_brain(self):
|
| 74 |
+
if not os.path.exists(LOGIC_MODEL_PATH):
|
| 75 |
+
print("⚠️ Brain not found. Using Regex fallback.")
|
| 76 |
+
return None
|
| 77 |
+
try:
|
| 78 |
+
with open("vocab.pkl", "rb") as f: self.vocab = pickle.load(f)
|
| 79 |
+
with open("intents.pkl", "rb") as f: self.intents = pickle.load(f)
|
| 80 |
+
|
| 81 |
+
# Recreate model structure
|
| 82 |
+
model = LogicBrain(len(self.vocab.word2idx), len(self.intents))
|
| 83 |
+
model.load_state_dict(torch.load(LOGIC_MODEL_PATH, map_location=self.device))
|
| 84 |
+
model.eval()
|
| 85 |
+
print("🧠 Neural Brain Loaded (1.5M Parameter Version)")
|
| 86 |
+
return model
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"⚠️ Error loading brain: {e}")
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
def _infer_alphabet(self, text):
|
| 92 |
+
if not text: return ['0', '1']
|
| 93 |
+
chars = set(text)
|
| 94 |
+
if chars.issubset({'0', '1'}): return ['0', '1']
|
| 95 |
+
return sorted(list(chars))
|
| 96 |
+
|
| 97 |
+
# --- MAIN GENERATION FUNCTION ---
|
| 98 |
+
def generate_system(self, prompt):
|
| 99 |
+
prompt = prompt.lower()
|
| 100 |
+
intent = "UNKNOWN"
|
| 101 |
+
confidence = 0.0
|
| 102 |
+
|
| 103 |
+
# A. NEURAL INFERENCE (Primary)
|
| 104 |
+
if self.logic_model:
|
| 105 |
+
vec = torch.tensor([self.vocab.encode(prompt)])
|
| 106 |
+
with torch.no_grad():
|
| 107 |
+
logits = self.logic_model(vec)
|
| 108 |
+
probs = torch.nn.functional.softmax(logits, dim=1)
|
| 109 |
+
conf, idx = torch.max(probs, 1)
|
| 110 |
+
intent = self.intents[idx.item()]
|
| 111 |
+
confidence = conf.item()
|
| 112 |
+
|
| 113 |
+
# B. REGEX FALLBACK (Secondary)
|
| 114 |
+
if intent == "UNKNOWN" or confidence < 0.6:
|
| 115 |
+
# Fallback patterns if AI is unsure
|
| 116 |
+
if "substring" in prompt: intent = "DFA_SUBSTRING"
|
| 117 |
+
elif "end" in prompt: intent = "DFA_ENDS_WITH"
|
| 118 |
+
elif "start" in prompt: intent = "DFA_STARTS_WITH"
|
| 119 |
+
elif "adder" in prompt: intent = "TM_ADDER"
|
| 120 |
+
elif "mod" in prompt: intent = "MOORE_MODULO"
|
| 121 |
+
|
| 122 |
+
# C. PARAMETER EXTRACTION
|
| 123 |
+
# (Neural nets are bad at copying exact strings, so we use regex for the parameter)
|
| 124 |
+
tokens = re.findall(r"[a-z0-9]+", prompt)
|
| 125 |
+
stopwords = ["dfa", "tm", "make", "generate", "machine", "the", "with", "ends", "starts", "substring", "containing", "automata", "construct", "build"]
|
| 126 |
+
candidates = [t for t in tokens if t not in stopwords]
|
| 127 |
+
param = candidates[-1] if candidates else "01"
|
| 128 |
+
|
| 129 |
+
# D. RENDER
|
| 130 |
+
dot = graphviz.Digraph(engine='dot', format='png')
|
| 131 |
+
dot.attr(rankdir='LR', bgcolor='transparent', nodesep='0.6', ranksep='0.5')
|
| 132 |
+
dot.attr('node', style='filled', fillcolor='#2B2B2B', color='#5c85d6', fontcolor='white', fontname='Arial')
|
| 133 |
+
dot.attr('edge', color='#5c85d6', fontcolor='white', fontname='Arial')
|
| 134 |
+
dot.node('start', '', shape='none', width='0')
|
| 135 |
+
|
| 136 |
+
transitions = []
|
| 137 |
+
if intent in self.func_map:
|
| 138 |
+
transitions = self.func_map[intent](dot, param)
|
| 139 |
+
logic_name = f"{intent} (AI Conf: {confidence*100:.1f}%)"
|
| 140 |
+
else:
|
| 141 |
+
transitions = self._dfa_exact(dot, param)
|
| 142 |
+
logic_name = "Exact Match (AI Unsure)"
|
| 143 |
+
|
| 144 |
+
return dot, transitions, logic_name
|
| 145 |
+
|
| 146 |
+
# --- BUILDER LOGIC (Same as before) ---
|
| 147 |
+
def _dfa_substring(self, dot, sub):
|
| 148 |
+
transitions = []
|
| 149 |
+
states = len(sub) + 1
|
| 150 |
+
dot.edge('start', 'q0')
|
| 151 |
+
alphabet = self._infer_alphabet(sub)
|
| 152 |
+
for i in range(states):
|
| 153 |
+
is_final = (i == len(sub))
|
| 154 |
+
shape = 'doublecircle' if is_final else 'circle'
|
| 155 |
+
dot.node(f'q{i}', shape=shape)
|
| 156 |
+
if is_final:
|
| 157 |
+
dot.edge(f'q{i}', f'q{i}', ",".join(alphabet))
|
| 158 |
+
for c in alphabet: transitions.append({"State":f"q{i}", "In":c, "Next":f"q{i}"})
|
| 159 |
+
continue
|
| 160 |
+
for char in alphabet:
|
| 161 |
+
pattern = sub[:i] + char
|
| 162 |
+
nxt = 0
|
| 163 |
+
for l in range(len(pattern), 0, -1):
|
| 164 |
+
if sub.startswith(pattern[-l:]): nxt = l; break
|
| 165 |
+
dot.edge(f'q{i}', f'q{nxt}', char)
|
| 166 |
+
transitions.append({"State":f"q{i}", "In":char, "Next":f"q{nxt}"})
|
| 167 |
+
return transitions
|
| 168 |
+
|
| 169 |
+
def _dfa_ends_with(self, dot, sub):
|
| 170 |
+
transitions = []
|
| 171 |
+
states = len(sub) + 1
|
| 172 |
+
dot.edge('start', 'q0')
|
| 173 |
+
alphabet = self._infer_alphabet(sub)
|
| 174 |
+
for i in range(states):
|
| 175 |
+
shape = 'doublecircle' if i == len(sub) else 'circle'
|
| 176 |
+
dot.node(f'q{i}', shape=shape)
|
| 177 |
+
for char in alphabet:
|
| 178 |
+
curr = sub[:i] + char
|
| 179 |
+
nxt = 0
|
| 180 |
+
for l in range(min(len(curr), len(sub)), 0, -1):
|
| 181 |
+
if sub.startswith(curr[-l:]): nxt = l; break
|
| 182 |
+
dot.edge(f'q{i}', f'q{nxt}', char)
|
| 183 |
+
transitions.append({"State":f"q{i}", "In":char, "Next":f"q{nxt}"})
|
| 184 |
+
return transitions
|
| 185 |
+
|
| 186 |
+
def _dfa_starts_with(self, dot, prefix):
|
| 187 |
+
transitions = []
|
| 188 |
+
dot.edge('start', 'q0')
|
| 189 |
+
prev = 'q0'
|
| 190 |
+
alphabet = self._infer_alphabet(prefix)
|
| 191 |
+
for i, char in enumerate(prefix):
|
| 192 |
+
curr = f'q{i+1}'
|
| 193 |
+
dot.edge(prev, curr, char)
|
| 194 |
+
transitions.append({"State":prev, "In":char, "Next":curr})
|
| 195 |
+
for oc in [c for c in alphabet if c != char]:
|
| 196 |
+
dot.edge(prev, 'dead', oc)
|
| 197 |
+
transitions.append({"State":prev, "In":oc, "Next":'dead'})
|
| 198 |
+
prev = curr
|
| 199 |
+
dot.node(prev, shape='doublecircle'); dot.edge(prev,prev, ",".join(alphabet))
|
| 200 |
+
dot.node('dead', shape='circle'); dot.edge('dead','dead', ",".join(alphabet))
|
| 201 |
+
return transitions
|
| 202 |
+
|
| 203 |
+
def _dfa_length(self, dot, param):
|
| 204 |
+
try: n = int(re.search(r'\d+', str(param)).group())
|
| 205 |
+
except: n = 3
|
| 206 |
+
transitions = []
|
| 207 |
+
dot.edge('start', 'q0')
|
| 208 |
+
for i in range(n):
|
| 209 |
+
dot.edge(f'q{i}', f'q{i+1}', '0,1')
|
| 210 |
+
transitions.append({"State":f"q{i}", "In":"0,1", "Next":f"q{i+1}"})
|
| 211 |
+
dot.node(f'q{n}', shape='doublecircle')
|
| 212 |
+
dot.edge(f'q{n}', 'trap', '0,1'); dot.edge('trap','trap','0,1')
|
| 213 |
+
return transitions
|
| 214 |
+
|
| 215 |
+
def _dfa_consecutive(self, dot, param):
|
| 216 |
+
c = param[0] if param else "0"
|
| 217 |
+
transitions = []
|
| 218 |
+
dot.edge('start', 'q0'); dot.node('q2', shape='doublecircle')
|
| 219 |
+
other = '1' if c == '0' else '0'
|
| 220 |
+
|
| 221 |
+
# q0
|
| 222 |
+
dot.edge('q0', 'q1', c); transitions.append({"State":'q0', "In":c, "Next":'q1'})
|
| 223 |
+
dot.edge('q0', 'q0', other); transitions.append({"State":'q0', "In":other, "Next":'q0'})
|
| 224 |
+
# q1
|
| 225 |
+
dot.edge('q1', 'q2', c); transitions.append({"State":'q1', "In":c, "Next":'q2'})
|
| 226 |
+
dot.edge('q1', 'q0', other); transitions.append({"State":'q1', "In":other, "Next":'q0'})
|
| 227 |
+
# q2
|
| 228 |
+
dot.edge('q2', 'q2', '0,1')
|
| 229 |
+
return transitions
|
| 230 |
+
|
| 231 |
+
def _dfa_exact(self, dot, s):
|
| 232 |
+
transitions = []
|
| 233 |
+
dot.edge('start', 'q0')
|
| 234 |
+
for i, c in enumerate(s):
|
| 235 |
+
dot.edge(f'q{i}', f'q{i+1}', c)
|
| 236 |
+
transitions.append({"State":f"q{i}", "In":c, "Next":f"q{i+1}"})
|
| 237 |
+
dot.node(f'q{len(s)}', shape='doublecircle')
|
| 238 |
+
return transitions
|
| 239 |
+
|
| 240 |
+
def _tm_palindrome(self, dot, _):
|
| 241 |
+
transitions = []
|
| 242 |
+
dot.edge('start', 'q0'); dot.node('accept', shape='doublecircle')
|
| 243 |
+
edges = [('q0','scan','B/B,R'), ('scan','scan','0,1/0,1,R'), ('scan','check','B/B,L'),
|
| 244 |
+
('check','back','0/B,L'), ('check','back','1/B,L'), ('back','match','B/B,R'),
|
| 245 |
+
('match','q0','0,1/B,R'), ('q0','accept','B/B,R')]
|
| 246 |
+
for u,v,l in edges:
|
| 247 |
+
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
| 248 |
+
return transitions
|
| 249 |
+
|
| 250 |
+
def _tm_adder(self, dot, _):
|
| 251 |
+
transitions = []
|
| 252 |
+
dot.edge('start', 'q0'); dot.node('halt', shape='doublecircle')
|
| 253 |
+
edges = [('q0','q0','0/0,R'), ('q0','q0','1/1,R'), ('q0','carry','B/B,L'),
|
| 254 |
+
('carry','carry','1/0,L'), ('carry','halt','0/1,R'), ('carry','halt','B/1,R')]
|
| 255 |
+
for u,v,l in edges:
|
| 256 |
+
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
| 257 |
+
return transitions
|
| 258 |
+
|
| 259 |
+
def _pda_anbn(self, dot, _):
|
| 260 |
+
transitions = []
|
| 261 |
+
dot.edge('start', 'q0'); dot.node('accept', shape='doublecircle')
|
| 262 |
+
edges = [('q0','q1','ε,ε->Z0'), ('q1','q1','a,ε->A'), ('q1','q2','b,A->ε'),
|
| 263 |
+
('q2','q2','b,A->ε'), ('q2','accept','ε,Z0->ε')]
|
| 264 |
+
for u,v,l in edges:
|
| 265 |
+
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
| 266 |
+
return transitions
|
| 267 |
+
|
| 268 |
+
def _moore_modulo(self, dot, param):
|
| 269 |
+
try: k = int(re.search(r'\d+', str(param)).group())
|
| 270 |
+
except: k = 3
|
| 271 |
+
transitions = []
|
| 272 |
+
dot.edge('start', 'q0')
|
| 273 |
+
for i in range(k):
|
| 274 |
+
out = 1 if i == 0 else 0
|
| 275 |
+
dot.node(f'q{i}', label=f'q{i}/{out}')
|
| 276 |
+
n0=(i*2)%k; n1=(i*2+1)%k
|
| 277 |
+
dot.edge(f'q{i}', f'q{n0}', '0'); dot.edge(f'q{i}', f'q{n1}', '1')
|
| 278 |
+
transitions.append({"State":f"q{i}", "Out":out, "In(0)":f"q{n0}", "In(1)":f"q{n1}"})
|
| 279 |
+
return transitions
|
| 280 |
+
|
| 281 |
+
# Vision prediction (kept for compatibility)
|
| 282 |
+
def predict_image(self, image_path):
|
| 283 |
+
if not self.vision_model: return "Model not found", 0.0
|
| 284 |
+
img = Image.open(image_path).convert("RGB")
|
| 285 |
+
tf = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485]*3, [0.229]*3)])
|
| 286 |
+
with torch.no_grad():
|
| 287 |
+
out = self.vision_model(tf(img).unsqueeze(0).to(self.device))
|
| 288 |
+
conf, idx = torch.max(torch.nn.functional.softmax(out, dim=1), 1)
|
| 289 |
+
return VISION_CLASSES[idx.item()], conf.item()
|