Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pandas as pd | |
import json | |
from pathlib import Path | |
import uuid | |
class ExpertSystem: | |
def __init__(self): | |
self.rules = [] | |
self.variables = {} | |
self.conclusions = set() | |
def add_rule(self, conditions, conclusion, probability=1.0): | |
rule_id = str(uuid.uuid4()) | |
self.rules.append({ | |
'id': rule_id, | |
'conditions': conditions, | |
'conclusion': conclusion, | |
'probability': probability | |
}) | |
self.conclusions.add(conclusion) | |
def evaluate(self, facts): | |
results = [] | |
for rule in self.rules: | |
is_valid = True | |
for condition in rule['conditions']: | |
var, op, value = condition | |
if var not in facts: | |
is_valid = False | |
break | |
if op == '==' and facts[var] != value: | |
is_valid = False | |
elif op == '>' and facts[var] <= value: | |
is_valid = False | |
elif op == '<' and facts[var] >= value: | |
is_valid = False | |
if is_valid: | |
results.append({ | |
'conclusion': rule['conclusion'], | |
'probability': rule['probability'] | |
}) | |
return results | |
def save(self, filename): | |
data = { | |
'rules': self.rules, | |
'variables': self.variables | |
} | |
with open(filename, 'w') as f: | |
json.dump(data, f) | |
def load(self, filename): | |
with open(filename, 'r') as f: | |
data = json.load(f) | |
self.rules = data['rules'] | |
self.variables = data['variables'] | |
self.conclusions = {rule['conclusion'] for rule in self.rules} | |
def main(): | |
st.set_page_config(page_title="Neo Sistema Especialista", layout="wide") | |
if 'expert_system' not in st.session_state: | |
st.session_state.expert_system = ExpertSystem() | |
if 'current_facts' not in st.session_state: | |
st.session_state.current_facts = {} | |
st.title("Neo Sistema Especialista") | |
# Sidebar para navegação | |
menu = st.sidebar.selectbox( | |
"Menu", | |
["Base de Conhecimento", "Consulta", "Variáveis", "Carregar/Salvar"] | |
) | |
if menu == "Base de Conhecimento": | |
show_knowledge_base() | |
elif menu == "Consulta": | |
show_consultation() | |
elif menu == "Variáveis": | |
show_variables() | |
else: | |
show_save_load() | |
def show_knowledge_base(): | |
st.header("Base de Conhecimento") | |
# Exibir regras existentes | |
st.subheader("Regras Existentes") | |
for i, rule in enumerate(st.session_state.expert_system.rules): | |
st.write(f"Regra {i + 1}:") | |
st.write(f"SE {' E '.join([f'{c[0]} {c[1]} {c[2]}' for c in rule['conditions']])}") | |
st.write(f"ENTÃO {rule['conclusion']} (Probabilidade: {rule['probability']})") | |
st.write("---") | |
# Adicionar nova regra | |
st.subheader("Adicionar Nova Regra") | |
with st.form("nova_regra"): | |
# Condições | |
st.write("Condições") | |
num_conditions = st.number_input("Número de condições", min_value=1, value=1) | |
conditions = [] | |
for i in range(int(num_conditions)): | |
col1, col2, col3 = st.columns(3) | |
with col1: | |
var = st.text_input(f"Variável {i + 1}") | |
with col2: | |
op = st.selectbox(f"Operador {i + 1}", ["==", ">", "<"]) | |
with col3: | |
val = st.text_input(f"Valor {i + 1}") | |
if var and val: | |
conditions.append((var, op, val)) | |
# Conclusão | |
conclusion = st.text_input("Conclusão") | |
probability = st.slider("Probabilidade", 0.0, 1.0, 1.0) | |
if st.form_submit_button("Adicionar Regra"): | |
if conditions and conclusion: | |
st.session_state.expert_system.add_rule(conditions, conclusion, probability) | |
st.success("Regra adicionada com sucesso!") | |
else: | |
st.error("Preencha todos os campos necessários") | |
def show_consultation(): | |
st.header("Consulta ao Sistema Especialista") | |
# Interface para inserir fatos | |
st.subheader("Inserir Fatos") | |
with st.form("consulta"): | |
facts = {} | |
variables = set() | |
for rule in st.session_state.expert_system.rules: | |
for condition in rule['conditions']: | |
variables.add(condition[0]) | |
for var in variables: | |
value = st.text_input(f"Valor para {var}") | |
if value: | |
facts[var] = value | |
if st.form_submit_button("Consultar"): | |
if facts: | |
results = st.session_state.expert_system.evaluate(facts) | |
st.session_state.current_facts = facts | |
if results: | |
st.success("Resultados encontrados!") | |
for result in results: | |
st.write(f"Conclusão: {result['conclusion']}") | |
st.write(f"Probabilidade: {result['probability']:.2%}") | |
else: | |
st.warning("Nenhuma conclusão encontrada para os fatos fornecidos.") | |
else: | |
st.error("Insira pelo menos um fato para consulta") | |
def show_variables(): | |
st.header("Variáveis do Sistema") | |
# Exibir variáveis existentes | |
variables = set() | |
for rule in st.session_state.expert_system.rules: | |
for condition in rule['conditions']: | |
variables.add(condition[0]) | |
st.subheader("Variáveis Utilizadas") | |
for var in variables: | |
st.write(f"- {var}") | |
def show_save_load(): | |
st.header("Carregar/Salvar Base de Conhecimento") | |
col1, col2 = st.columns(2) | |
with col1: | |
st.subheader("Salvar Base") | |
filename = st.text_input("Nome do arquivo para salvar", "base_conhecimento.json") | |
if st.button("Salvar"): | |
try: | |
st.session_state.expert_system.save(filename) | |
st.success(f"Base de conhecimento salva em {filename}") | |
except Exception as e: | |
st.error(f"Erro ao salvar: {str(e)}") | |
with col2: | |
st.subheader("Carregar Base") | |
uploaded_file = st.file_uploader("Escolha um arquivo .json", type="json") | |
if uploaded_file is not None: | |
try: | |
# Salvar o arquivo temporariamente | |
temp_path = Path("temp.json") | |
temp_path.write_bytes(uploaded_file.getvalue()) | |
st.session_state.expert_system.load(temp_path) | |
temp_path.unlink() # Remover arquivo temporário | |
st.success("Base de conhecimento carregada com sucesso!") | |
except Exception as e: | |
st.error(f"Erro ao carregar: {str(e)}") | |
if __name__ == "__main__": | |
main() |