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
def __init__(self):
|
9 |
+
self.rules = []
|
10 |
+
self.variables = {}
|
11 |
+
self.conclusions = set()
|
12 |
+
|
13 |
+
def add_rule(self, conditions, conclusion, probability=1.0):
|
14 |
+
rule_id = str(uuid.uuid4())
|
15 |
+
self.rules.append({
|
16 |
+
'id': rule_id,
|
17 |
+
'conditions': conditions,
|
18 |
+
'conclusion': conclusion,
|
19 |
+
'probability': probability
|
20 |
+
})
|
21 |
+
self.conclusions.add(conclusion)
|
22 |
+
|
23 |
+
def evaluate(self, facts):
|
24 |
+
results = []
|
25 |
+
for rule in self.rules:
|
26 |
+
is_valid = True
|
27 |
+
for condition in rule['conditions']:
|
28 |
+
var, op, value = condition
|
29 |
+
if var not in facts:
|
30 |
+
is_valid = False
|
31 |
+
break
|
32 |
+
|
33 |
+
if op == '==' and facts[var] != value:
|
34 |
+
is_valid = False
|
35 |
+
elif op == '>' and facts[var] <= value:
|
36 |
+
is_valid = False
|
37 |
+
elif op == '<' and facts[var] >= value:
|
38 |
+
is_valid = False
|
39 |
+
|
40 |
+
if is_valid:
|
41 |
+
results.append({
|
42 |
+
'conclusion': rule['conclusion'],
|
43 |
+
'probability': rule['probability']
|
44 |
+
})
|
45 |
+
|
46 |
+
return results
|
47 |
+
|
48 |
+
def save(self, filename):
|
49 |
+
data = {
|
50 |
+
'rules': self.rules,
|
51 |
+
'variables': self.variables
|
52 |
+
}
|
53 |
+
with open(filename, 'w') as f:
|
54 |
+
json.dump(data, f)
|
55 |
+
|
56 |
+
def load(self, filename):
|
57 |
+
with open(filename, 'r') as f:
|
58 |
+
data = json.load(f)
|
59 |
+
self.rules = data['rules']
|
60 |
+
self.variables = data['variables']
|
61 |
+
self.conclusions = {rule['conclusion'] for rule in self.rules}
|
62 |
+
|
63 |
+
|
64 |
+
def main():
|
65 |
+
st.set_page_config(page_title="Neo Sistema Especialista", layout="wide")
|
66 |
+
|
67 |
+
if 'expert_system' not in st.session_state:
|
68 |
+
st.session_state.expert_system = ExpertSystem()
|
69 |
+
|
70 |
+
if 'current_facts' not in st.session_state:
|
71 |
+
st.session_state.current_facts = {}
|
72 |
+
|
73 |
+
st.title("Expert SINTA - Sistema Especialista")
|
74 |
+
|
75 |
+
# Sidebar para navegação
|
76 |
+
menu = st.sidebar.selectbox(
|
77 |
+
"Menu",
|
78 |
+
["Base de Conhecimento", "Consulta", "Variáveis", "Carregar/Salvar"]
|
79 |
+
)
|
80 |
+
|
81 |
+
if menu == "Base de Conhecimento":
|
82 |
+
show_knowledge_base()
|
83 |
+
elif menu == "Consulta":
|
84 |
+
show_consultation()
|
85 |
+
elif menu == "Variáveis":
|
86 |
+
show_variables()
|
87 |
+
else:
|
88 |
+
show_save_load()
|
89 |
+
|
90 |
+
|
91 |
+
def show_knowledge_base():
|
92 |
+
st.header("Base de Conhecimento")
|
93 |
+
|
94 |
+
# Exibir regras existentes
|
95 |
+
st.subheader("Regras Existentes")
|
96 |
+
for i, rule in enumerate(st.session_state.expert_system.rules):
|
97 |
+
st.write(f"Regra {i + 1}:")
|
98 |
+
st.write(f"SE {' E '.join([f'{c[0]} {c[1]} {c[2]}' for c in rule['conditions']])}")
|
99 |
+
st.write(f"ENTÃO {rule['conclusion']} (Probabilidade: {rule['probability']})")
|
100 |
+
st.write("---")
|
101 |
+
|
102 |
+
# Adicionar nova regra
|
103 |
+
st.subheader("Adicionar Nova Regra")
|
104 |
+
|
105 |
+
with st.form("nova_regra"):
|
106 |
+
# Condições
|
107 |
+
st.write("Condições")
|
108 |
+
num_conditions = st.number_input("Número de condições", min_value=1, value=1)
|
109 |
+
|
110 |
+
conditions = []
|
111 |
+
for i in range(int(num_conditions)):
|
112 |
+
col1, col2, col3 = st.columns(3)
|
113 |
+
with col1:
|
114 |
+
var = st.text_input(f"Variável {i + 1}")
|
115 |
+
with col2:
|
116 |
+
op = st.selectbox(f"Operador {i + 1}", ["==", ">", "<"])
|
117 |
+
with col3:
|
118 |
+
val = st.text_input(f"Valor {i + 1}")
|
119 |
+
if var and val:
|
120 |
+
conditions.append((var, op, val))
|
121 |
+
|
122 |
+
# Conclusão
|
123 |
+
conclusion = st.text_input("Conclusão")
|
124 |
+
probability = st.slider("Probabilidade", 0.0, 1.0, 1.0)
|
125 |
+
|
126 |
+
if st.form_submit_button("Adicionar Regra"):
|
127 |
+
if conditions and conclusion:
|
128 |
+
st.session_state.expert_system.add_rule(conditions, conclusion, probability)
|
129 |
+
st.success("Regra adicionada com sucesso!")
|
130 |
+
else:
|
131 |
+
st.error("Preencha todos os campos necessários")
|
132 |
+
|
133 |
+
|
134 |
+
def show_consultation():
|
135 |
+
st.header("Consulta ao Sistema Especialista")
|
136 |
+
|
137 |
+
# Interface para inserir fatos
|
138 |
+
st.subheader("Inserir Fatos")
|
139 |
+
|
140 |
+
with st.form("consulta"):
|
141 |
+
facts = {}
|
142 |
+
variables = set()
|
143 |
+
for rule in st.session_state.expert_system.rules:
|
144 |
+
for condition in rule['conditions']:
|
145 |
+
variables.add(condition[0])
|
146 |
+
|
147 |
+
for var in variables:
|
148 |
+
value = st.text_input(f"Valor para {var}")
|
149 |
+
if value:
|
150 |
+
facts[var] = value
|
151 |
+
|
152 |
+
if st.form_submit_button("Consultar"):
|
153 |
+
if facts:
|
154 |
+
results = st.session_state.expert_system.evaluate(facts)
|
155 |
+
st.session_state.current_facts = facts
|
156 |
+
|
157 |
+
if results:
|
158 |
+
st.success("Resultados encontrados!")
|
159 |
+
for result in results:
|
160 |
+
st.write(f"Conclusão: {result['conclusion']}")
|
161 |
+
st.write(f"Probabilidade: {result['probability']:.2%}")
|
162 |
+
else:
|
163 |
+
st.warning("Nenhuma conclusão encontrada para os fatos fornecidos.")
|
164 |
+
else:
|
165 |
+
st.error("Insira pelo menos um fato para consulta")
|
166 |
+
|
167 |
+
|
168 |
+
def show_variables():
|
169 |
+
st.header("Variáveis do Sistema")
|
170 |
+
|
171 |
+
# Exibir variáveis existentes
|
172 |
+
variables = set()
|
173 |
+
for rule in st.session_state.expert_system.rules:
|
174 |
+
for condition in rule['conditions']:
|
175 |
+
variables.add(condition[0])
|
176 |
+
|
177 |
+
st.subheader("Variáveis Utilizadas")
|
178 |
+
for var in variables:
|
179 |
+
st.write(f"- {var}")
|
180 |
+
|
181 |
+
|
182 |
+
def show_save_load():
|
183 |
+
st.header("Carregar/Salvar Base de Conhecimento")
|
184 |
+
|
185 |
+
col1, col2 = st.columns(2)
|
186 |
+
|
187 |
+
with col1:
|
188 |
+
st.subheader("Salvar Base")
|
189 |
+
filename = st.text_input("Nome do arquivo para salvar", "base_conhecimento.json")
|
190 |
+
if st.button("Salvar"):
|
191 |
+
try:
|
192 |
+
st.session_state.expert_system.save(filename)
|
193 |
+
st.success(f"Base de conhecimento salva em {filename}")
|
194 |
+
except Exception as e:
|
195 |
+
st.error(f"Erro ao salvar: {str(e)}")
|
196 |
+
|
197 |
+
with col2:
|
198 |
+
st.subheader("Carregar Base")
|
199 |
+
uploaded_file = st.file_uploader("Escolha um arquivo .json", type="json")
|
200 |
+
if uploaded_file is not None:
|
201 |
+
try:
|
202 |
+
# Salvar o arquivo temporariamente
|
203 |
+
temp_path = Path("temp.json")
|
204 |
+
temp_path.write_bytes(uploaded_file.getvalue())
|
205 |
+
|
206 |
+
st.session_state.expert_system.load(temp_path)
|
207 |
+
temp_path.unlink() # Remover arquivo temporário
|
208 |
+
|
209 |
+
st.success("Base de conhecimento carregada com sucesso!")
|
210 |
+
except Exception as e:
|
211 |
+
st.error(f"Erro ao carregar: {str(e)}")
|
212 |
+
|
213 |
+
|
214 |
+
if __name__ == "__main__":
|
215 |
+
main()
|