|
|
import graphviz
|
|
|
import re
|
|
|
import torch
|
|
|
import os
|
|
|
import pandas as pd
|
|
|
import pickle
|
|
|
import torch.nn as nn
|
|
|
from torchvision import models, transforms
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
|
VISION_MODEL_PATH = "automata_model.pth"
|
|
|
LOGIC_MODEL_PATH = "logic_model.pth"
|
|
|
VISION_CLASSES = ['ADVANCED_TOC', 'DFA', 'MINIMAL_DFA', 'NFA', 'PDA', 'TM', 'TRANSDUCER']
|
|
|
|
|
|
|
|
|
class LogicBrain(nn.Module):
|
|
|
def __init__(self, vocab_size, num_intents):
|
|
|
super(LogicBrain, self).__init__()
|
|
|
self.embedding = nn.Embedding(vocab_size, 128)
|
|
|
self.lstm = nn.LSTM(128, 256, num_layers=2, batch_first=True, bidirectional=True)
|
|
|
self.fc = nn.Linear(256 * 2, num_intents)
|
|
|
|
|
|
def forward(self, x):
|
|
|
emb = self.embedding(x)
|
|
|
out, _ = self.lstm(emb)
|
|
|
out, _ = torch.max(out, dim=1)
|
|
|
return self.fc(out)
|
|
|
|
|
|
class Vocabulary:
|
|
|
def __init__(self): self.word2idx = {}
|
|
|
def encode(self, text, max_len=20):
|
|
|
tokens = re.findall(r"\w+", text.lower())
|
|
|
vec = [self.word2idx.get(t, 1) for t in tokens[:max_len]]
|
|
|
vec += [0] * (max_len - len(vec))
|
|
|
return vec
|
|
|
|
|
|
class AutomataCore:
|
|
|
def __init__(self):
|
|
|
self.device = torch.device("cpu")
|
|
|
|
|
|
|
|
|
self.vision_model = self._load_vision()
|
|
|
|
|
|
|
|
|
self.vocab = None
|
|
|
self.intents = None
|
|
|
self.logic_model = self._load_brain()
|
|
|
|
|
|
|
|
|
self.func_map = {
|
|
|
"DFA_SUBSTRING": self._dfa_substring,
|
|
|
"DFA_ENDS_WITH": self._dfa_ends_with,
|
|
|
"DFA_STARTS_WITH": self._dfa_starts_with,
|
|
|
"DFA_LENGTH": self._dfa_length,
|
|
|
"DFA_CONSECUTIVE": self._dfa_consecutive,
|
|
|
"TM_PALINDROME": self._tm_palindrome,
|
|
|
"TM_ADDER": self._tm_adder,
|
|
|
"PDA_ANBN": self._pda_anbn,
|
|
|
"MOORE_MODULO": self._moore_modulo
|
|
|
}
|
|
|
|
|
|
def _load_vision(self):
|
|
|
if not os.path.exists(VISION_MODEL_PATH): return None
|
|
|
try:
|
|
|
m = models.resnet18(weights=None)
|
|
|
m.fc = torch.nn.Linear(m.fc.in_features, len(VISION_CLASSES))
|
|
|
m.load_state_dict(torch.load(VISION_MODEL_PATH, map_location=self.device))
|
|
|
m.eval()
|
|
|
return m
|
|
|
except: return None
|
|
|
|
|
|
def _load_brain(self):
|
|
|
if not os.path.exists(LOGIC_MODEL_PATH):
|
|
|
print("⚠️ Brain not found. Using Regex fallback.")
|
|
|
return None
|
|
|
try:
|
|
|
with open("vocab.pkl", "rb") as f: self.vocab = pickle.load(f)
|
|
|
with open("intents.pkl", "rb") as f: self.intents = pickle.load(f)
|
|
|
|
|
|
|
|
|
model = LogicBrain(len(self.vocab.word2idx), len(self.intents))
|
|
|
model.load_state_dict(torch.load(LOGIC_MODEL_PATH, map_location=self.device))
|
|
|
model.eval()
|
|
|
print("🧠 Neural Brain Loaded (1.5M Parameter Version)")
|
|
|
return model
|
|
|
except Exception as e:
|
|
|
print(f"⚠️ Error loading brain: {e}")
|
|
|
return None
|
|
|
|
|
|
def _infer_alphabet(self, text):
|
|
|
if not text: return ['0', '1']
|
|
|
chars = set(text)
|
|
|
if chars.issubset({'0', '1'}): return ['0', '1']
|
|
|
return sorted(list(chars))
|
|
|
|
|
|
|
|
|
def generate_system(self, prompt):
|
|
|
prompt = prompt.lower()
|
|
|
intent = "UNKNOWN"
|
|
|
confidence = 0.0
|
|
|
|
|
|
|
|
|
if self.logic_model:
|
|
|
vec = torch.tensor([self.vocab.encode(prompt)])
|
|
|
with torch.no_grad():
|
|
|
logits = self.logic_model(vec)
|
|
|
probs = torch.nn.functional.softmax(logits, dim=1)
|
|
|
conf, idx = torch.max(probs, 1)
|
|
|
intent = self.intents[idx.item()]
|
|
|
confidence = conf.item()
|
|
|
|
|
|
|
|
|
if intent == "UNKNOWN" or confidence < 0.6:
|
|
|
|
|
|
if "substring" in prompt: intent = "DFA_SUBSTRING"
|
|
|
elif "end" in prompt: intent = "DFA_ENDS_WITH"
|
|
|
elif "start" in prompt: intent = "DFA_STARTS_WITH"
|
|
|
elif "adder" in prompt: intent = "TM_ADDER"
|
|
|
elif "mod" in prompt: intent = "MOORE_MODULO"
|
|
|
|
|
|
|
|
|
|
|
|
tokens = re.findall(r"[a-z0-9]+", prompt)
|
|
|
stopwords = ["dfa", "tm", "make", "generate", "machine", "the", "with", "ends", "starts", "substring", "containing", "automata", "construct", "build"]
|
|
|
candidates = [t for t in tokens if t not in stopwords]
|
|
|
param = candidates[-1] if candidates else "01"
|
|
|
|
|
|
|
|
|
dot = graphviz.Digraph(engine='dot', format='png')
|
|
|
dot.attr(rankdir='LR', bgcolor='transparent', nodesep='0.6', ranksep='0.5')
|
|
|
dot.attr('node', style='filled', fillcolor='#2B2B2B', color='#5c85d6', fontcolor='white', fontname='Arial')
|
|
|
dot.attr('edge', color='#5c85d6', fontcolor='white', fontname='Arial')
|
|
|
dot.node('start', '', shape='none', width='0')
|
|
|
|
|
|
transitions = []
|
|
|
if intent in self.func_map:
|
|
|
transitions = self.func_map[intent](dot, param)
|
|
|
logic_name = f"{intent} (AI Conf: {confidence*100:.1f}%)"
|
|
|
else:
|
|
|
transitions = self._dfa_exact(dot, param)
|
|
|
logic_name = "Exact Match (AI Unsure)"
|
|
|
|
|
|
return dot, transitions, logic_name
|
|
|
|
|
|
|
|
|
def _dfa_substring(self, dot, sub):
|
|
|
transitions = []
|
|
|
states = len(sub) + 1
|
|
|
dot.edge('start', 'q0')
|
|
|
alphabet = self._infer_alphabet(sub)
|
|
|
for i in range(states):
|
|
|
is_final = (i == len(sub))
|
|
|
shape = 'doublecircle' if is_final else 'circle'
|
|
|
dot.node(f'q{i}', shape=shape)
|
|
|
if is_final:
|
|
|
dot.edge(f'q{i}', f'q{i}', ",".join(alphabet))
|
|
|
for c in alphabet: transitions.append({"State":f"q{i}", "In":c, "Next":f"q{i}"})
|
|
|
continue
|
|
|
for char in alphabet:
|
|
|
pattern = sub[:i] + char
|
|
|
nxt = 0
|
|
|
for l in range(len(pattern), 0, -1):
|
|
|
if sub.startswith(pattern[-l:]): nxt = l; break
|
|
|
dot.edge(f'q{i}', f'q{nxt}', char)
|
|
|
transitions.append({"State":f"q{i}", "In":char, "Next":f"q{nxt}"})
|
|
|
return transitions
|
|
|
|
|
|
def _dfa_ends_with(self, dot, sub):
|
|
|
transitions = []
|
|
|
states = len(sub) + 1
|
|
|
dot.edge('start', 'q0')
|
|
|
alphabet = self._infer_alphabet(sub)
|
|
|
for i in range(states):
|
|
|
shape = 'doublecircle' if i == len(sub) else 'circle'
|
|
|
dot.node(f'q{i}', shape=shape)
|
|
|
for char in alphabet:
|
|
|
curr = sub[:i] + char
|
|
|
nxt = 0
|
|
|
for l in range(min(len(curr), len(sub)), 0, -1):
|
|
|
if sub.startswith(curr[-l:]): nxt = l; break
|
|
|
dot.edge(f'q{i}', f'q{nxt}', char)
|
|
|
transitions.append({"State":f"q{i}", "In":char, "Next":f"q{nxt}"})
|
|
|
return transitions
|
|
|
|
|
|
def _dfa_starts_with(self, dot, prefix):
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0')
|
|
|
prev = 'q0'
|
|
|
alphabet = self._infer_alphabet(prefix)
|
|
|
for i, char in enumerate(prefix):
|
|
|
curr = f'q{i+1}'
|
|
|
dot.edge(prev, curr, char)
|
|
|
transitions.append({"State":prev, "In":char, "Next":curr})
|
|
|
for oc in [c for c in alphabet if c != char]:
|
|
|
dot.edge(prev, 'dead', oc)
|
|
|
transitions.append({"State":prev, "In":oc, "Next":'dead'})
|
|
|
prev = curr
|
|
|
dot.node(prev, shape='doublecircle'); dot.edge(prev,prev, ",".join(alphabet))
|
|
|
dot.node('dead', shape='circle'); dot.edge('dead','dead', ",".join(alphabet))
|
|
|
return transitions
|
|
|
|
|
|
def _dfa_length(self, dot, param):
|
|
|
try: n = int(re.search(r'\d+', str(param)).group())
|
|
|
except: n = 3
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0')
|
|
|
for i in range(n):
|
|
|
dot.edge(f'q{i}', f'q{i+1}', '0,1')
|
|
|
transitions.append({"State":f"q{i}", "In":"0,1", "Next":f"q{i+1}"})
|
|
|
dot.node(f'q{n}', shape='doublecircle')
|
|
|
dot.edge(f'q{n}', 'trap', '0,1'); dot.edge('trap','trap','0,1')
|
|
|
return transitions
|
|
|
|
|
|
def _dfa_consecutive(self, dot, param):
|
|
|
c = param[0] if param else "0"
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0'); dot.node('q2', shape='doublecircle')
|
|
|
other = '1' if c == '0' else '0'
|
|
|
|
|
|
|
|
|
dot.edge('q0', 'q1', c); transitions.append({"State":'q0', "In":c, "Next":'q1'})
|
|
|
dot.edge('q0', 'q0', other); transitions.append({"State":'q0', "In":other, "Next":'q0'})
|
|
|
|
|
|
dot.edge('q1', 'q2', c); transitions.append({"State":'q1', "In":c, "Next":'q2'})
|
|
|
dot.edge('q1', 'q0', other); transitions.append({"State":'q1', "In":other, "Next":'q0'})
|
|
|
|
|
|
dot.edge('q2', 'q2', '0,1')
|
|
|
return transitions
|
|
|
|
|
|
def _dfa_exact(self, dot, s):
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0')
|
|
|
for i, c in enumerate(s):
|
|
|
dot.edge(f'q{i}', f'q{i+1}', c)
|
|
|
transitions.append({"State":f"q{i}", "In":c, "Next":f"q{i+1}"})
|
|
|
dot.node(f'q{len(s)}', shape='doublecircle')
|
|
|
return transitions
|
|
|
|
|
|
def _tm_palindrome(self, dot, _):
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0'); dot.node('accept', shape='doublecircle')
|
|
|
edges = [('q0','scan','B/B,R'), ('scan','scan','0,1/0,1,R'), ('scan','check','B/B,L'),
|
|
|
('check','back','0/B,L'), ('check','back','1/B,L'), ('back','match','B/B,R'),
|
|
|
('match','q0','0,1/B,R'), ('q0','accept','B/B,R')]
|
|
|
for u,v,l in edges:
|
|
|
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
|
|
return transitions
|
|
|
|
|
|
def _tm_adder(self, dot, _):
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0'); dot.node('halt', shape='doublecircle')
|
|
|
edges = [('q0','q0','0/0,R'), ('q0','q0','1/1,R'), ('q0','carry','B/B,L'),
|
|
|
('carry','carry','1/0,L'), ('carry','halt','0/1,R'), ('carry','halt','B/1,R')]
|
|
|
for u,v,l in edges:
|
|
|
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
|
|
return transitions
|
|
|
|
|
|
def _pda_anbn(self, dot, _):
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0'); dot.node('accept', shape='doublecircle')
|
|
|
edges = [('q0','q1','ε,ε->Z0'), ('q1','q1','a,ε->A'), ('q1','q2','b,A->ε'),
|
|
|
('q2','q2','b,A->ε'), ('q2','accept','ε,Z0->ε')]
|
|
|
for u,v,l in edges:
|
|
|
dot.edge(u,v,l); transitions.append({"State":u, "Rule":l, "Next":v})
|
|
|
return transitions
|
|
|
|
|
|
def _moore_modulo(self, dot, param):
|
|
|
try: k = int(re.search(r'\d+', str(param)).group())
|
|
|
except: k = 3
|
|
|
transitions = []
|
|
|
dot.edge('start', 'q0')
|
|
|
for i in range(k):
|
|
|
out = 1 if i == 0 else 0
|
|
|
dot.node(f'q{i}', label=f'q{i}/{out}')
|
|
|
n0=(i*2)%k; n1=(i*2+1)%k
|
|
|
dot.edge(f'q{i}', f'q{n0}', '0'); dot.edge(f'q{i}', f'q{n1}', '1')
|
|
|
transitions.append({"State":f"q{i}", "Out":out, "In(0)":f"q{n0}", "In(1)":f"q{n1}"})
|
|
|
return transitions
|
|
|
|
|
|
|
|
|
def predict_image(self, image_path):
|
|
|
if not self.vision_model: return "Model not found", 0.0
|
|
|
img = Image.open(image_path).convert("RGB")
|
|
|
tf = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485]*3, [0.229]*3)])
|
|
|
with torch.no_grad():
|
|
|
out = self.vision_model(tf(img).unsqueeze(0).to(self.device))
|
|
|
conf, idx = torch.max(torch.nn.functional.softmax(out, dim=1), 1)
|
|
|
return VISION_CLASSES[idx.item()], conf.item() |