Spaces:
Running
Running
Update modules/contexto.py
Browse files- modules/contexto.py +49 -27
modules/contexto.py
CHANGED
|
@@ -9,7 +9,7 @@ Contexto de conversa por usuário
|
|
| 9 |
- SÓ STRING NO BANCO → json.loads seguro
|
| 10 |
"""
|
| 11 |
import json
|
| 12 |
-
from typing import List, Tuple, Dict
|
| 13 |
from loguru import logger
|
| 14 |
import modules.config as config
|
| 15 |
from .database import Database
|
|
@@ -19,6 +19,7 @@ class Contexto:
|
|
| 19 |
def __init__(self, db: Database, user_key: str):
|
| 20 |
self.db = db
|
| 21 |
self.user_key = user_key
|
|
|
|
| 22 |
self.historico: List[Tuple[str, str]] = []
|
| 23 |
self.emocao_atual: str = config.HUMOR_INICIAL
|
| 24 |
self.termo_contexto: List[str] = []
|
|
@@ -27,8 +28,15 @@ class Contexto:
|
|
| 27 |
self._carregar_do_banco()
|
| 28 |
|
| 29 |
def _carregar_do_banco(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
-
dados = self.db.carregar_contexto(self.user_key)
|
| 32 |
if not dados:
|
| 33 |
return
|
| 34 |
|
|
@@ -36,55 +44,65 @@ class Contexto:
|
|
| 36 |
hist_raw = dados.get("historico", "[]")
|
| 37 |
if isinstance(hist_raw, str):
|
| 38 |
try:
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
except:
|
| 41 |
-
|
| 42 |
-
else:
|
| 43 |
-
self.historico = []
|
| 44 |
|
| 45 |
# --- EMOÇÃO: sempre str ---
|
| 46 |
-
|
| 47 |
|
| 48 |
# --- TERMOS: sempre str → json.loads ---
|
| 49 |
termos_raw = dados.get("termos", "[]")
|
| 50 |
if isinstance(termos_raw, str):
|
| 51 |
try:
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
except:
|
| 54 |
-
|
| 55 |
-
else:
|
| 56 |
-
self.termo_contexto = []
|
| 57 |
|
| 58 |
# --- GÍRIAS: sempre str → json.loads + filtro ---
|
| 59 |
girias_raw = dados.get("girias", "[]")
|
| 60 |
if isinstance(girias_raw, str):
|
| 61 |
try:
|
| 62 |
girias = json.loads(girias_raw)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
-
logger.warning(f"Erro ao parsear gírias: {e}")
|
| 70 |
-
|
| 71 |
-
else:
|
| 72 |
-
self.girias_aprendidas = []
|
| 73 |
|
| 74 |
# --- TOM: sempre str ---
|
| 75 |
-
|
| 76 |
|
| 77 |
except Exception as e:
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
def salvar_no_banco(self):
|
| 84 |
try:
|
| 85 |
self.db.salvar_contexto(
|
| 86 |
self.user_key,
|
| 87 |
-
|
|
|
|
| 88 |
self.emocao_atual,
|
| 89 |
json.dumps(self.termo_contexto),
|
| 90 |
json.dumps(self.girias_aprendidas),
|
|
@@ -96,8 +114,10 @@ class Contexto:
|
|
| 96 |
def atualizar_aprendizados_do_banco(self):
|
| 97 |
try:
|
| 98 |
girias = self.db.listar_girias_aprendidas(self.user_key)
|
|
|
|
| 99 |
self.girias_aprendidas = [
|
| 100 |
-
{"giria": g[0], "significado": g[1]}
|
|
|
|
| 101 |
]
|
| 102 |
except Exception as e:
|
| 103 |
logger.warning(f"Erro ao atualizar gírias: {e}")
|
|
@@ -105,6 +125,7 @@ class Contexto:
|
|
| 105 |
|
| 106 |
def analisar_emocoes_mensagem(self, mensagem: str) -> str:
|
| 107 |
msg = mensagem.lower()
|
|
|
|
| 108 |
if any(p in msg for p in ["feliz", "fixe", "bué bom", "adoro", "rsrs", "kkk"]):
|
| 109 |
return "feliz"
|
| 110 |
if any(p in msg for p in ["triste", "chateado", "merda", "puto", "caralho"]):
|
|
@@ -116,6 +137,7 @@ class Contexto:
|
|
| 116 |
return "neutra"
|
| 117 |
|
| 118 |
def obter_historico(self) -> List[Tuple[str, str]]:
|
|
|
|
| 119 |
return self.historico[-3:]
|
| 120 |
|
| 121 |
def atualizar_contexto(self, mensagem: str, resposta: str):
|
|
|
|
| 9 |
- SÓ STRING NO BANCO → json.loads seguro
|
| 10 |
"""
|
| 11 |
import json
|
| 12 |
+
from typing import List, Tuple, Dict, Any
|
| 13 |
from loguru import logger
|
| 14 |
import modules.config as config
|
| 15 |
from .database import Database
|
|
|
|
| 19 |
def __init__(self, db: Database, user_key: str):
|
| 20 |
self.db = db
|
| 21 |
self.user_key = user_key
|
| 22 |
+
# Inicializa com tipos garantidos
|
| 23 |
self.historico: List[Tuple[str, str]] = []
|
| 24 |
self.emocao_atual: str = config.HUMOR_INICIAL
|
| 25 |
self.termo_contexto: List[str] = []
|
|
|
|
| 28 |
self._carregar_do_banco()
|
| 29 |
|
| 30 |
def _carregar_do_banco(self):
|
| 31 |
+
# Variáveis temporárias para carregar com segurança
|
| 32 |
+
temp_historico: List[Tuple[str, str]] = []
|
| 33 |
+
temp_emocao: str = config.HUMOR_INICIAL
|
| 34 |
+
temp_termos: List[str] = []
|
| 35 |
+
temp_girias: List[Dict[str, str]] = []
|
| 36 |
+
temp_tom: str = "neutro"
|
| 37 |
+
|
| 38 |
try:
|
| 39 |
+
dados: Dict[str, Any] = self.db.carregar_contexto(self.user_key)
|
| 40 |
if not dados:
|
| 41 |
return
|
| 42 |
|
|
|
|
| 44 |
hist_raw = dados.get("historico", "[]")
|
| 45 |
if isinstance(hist_raw, str):
|
| 46 |
try:
|
| 47 |
+
loaded_hist = json.loads(hist_raw)
|
| 48 |
+
# Melhoria: Garante que é uma lista (e assume o formato correto)
|
| 49 |
+
if isinstance(loaded_hist, list):
|
| 50 |
+
temp_historico = loaded_hist
|
| 51 |
except:
|
| 52 |
+
pass
|
|
|
|
|
|
|
| 53 |
|
| 54 |
# --- EMOÇÃO: sempre str ---
|
| 55 |
+
temp_emocao = str(dados.get("emocao_atual", config.HUMOR_INICIAL))
|
| 56 |
|
| 57 |
# --- TERMOS: sempre str → json.loads ---
|
| 58 |
termos_raw = dados.get("termos", "[]")
|
| 59 |
if isinstance(termos_raw, str):
|
| 60 |
try:
|
| 61 |
+
loaded_termos = json.loads(termos_raw)
|
| 62 |
+
# Melhoria: Garante que é uma lista de strings
|
| 63 |
+
if isinstance(loaded_termos, list) and all(isinstance(t, str) for t in loaded_termos):
|
| 64 |
+
temp_termos = loaded_termos
|
| 65 |
except:
|
| 66 |
+
pass
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# --- GÍRIAS: sempre str → json.loads + filtro ---
|
| 69 |
girias_raw = dados.get("girias", "[]")
|
| 70 |
if isinstance(girias_raw, str):
|
| 71 |
try:
|
| 72 |
girias = json.loads(girias_raw)
|
| 73 |
+
# Melhoria: Garante que é uma lista antes de iterar
|
| 74 |
+
if isinstance(girias, list):
|
| 75 |
+
temp_girias = [
|
| 76 |
+
{"giria": str(g.get("giria", "")), "significado": str(g.get("significado", ""))}
|
| 77 |
+
for g in girias
|
| 78 |
+
if isinstance(g, dict) and "giria" in g
|
| 79 |
+
]
|
| 80 |
except Exception as e:
|
| 81 |
+
logger.warning(f"Erro ao parsear gírias (JSON): {e}")
|
| 82 |
+
# temp_girias permanece []
|
|
|
|
|
|
|
| 83 |
|
| 84 |
# --- TOM: sempre str ---
|
| 85 |
+
temp_tom = str(dados.get("tom", "neutro"))
|
| 86 |
|
| 87 |
except Exception as e:
|
| 88 |
+
# Em caso de erro total (ex: problema na db.carregar_contexto)
|
| 89 |
+
logger.warning(f"Erro ao carregar contexto principal: {e}")
|
| 90 |
+
|
| 91 |
+
finally:
|
| 92 |
+
# Atribui apenas os valores seguros ou padrões
|
| 93 |
+
self.historico = temp_historico
|
| 94 |
+
self.emocao_atual = temp_emocao
|
| 95 |
+
self.termo_contexto = temp_termos
|
| 96 |
+
self.girias_aprendidas = temp_girias
|
| 97 |
+
self.ton_predominante = temp_tom
|
| 98 |
+
|
| 99 |
|
| 100 |
def salvar_no_banco(self):
|
| 101 |
try:
|
| 102 |
self.db.salvar_contexto(
|
| 103 |
self.user_key,
|
| 104 |
+
# Garante que 'historico' é uma lista e limita o tamanho
|
| 105 |
+
json.dumps([tuple(item) for item in self.historico[-config.MEMORIA_MAX:]]),
|
| 106 |
self.emocao_atual,
|
| 107 |
json.dumps(self.termo_contexto),
|
| 108 |
json.dumps(self.girias_aprendidas),
|
|
|
|
| 114 |
def atualizar_aprendizados_do_banco(self):
|
| 115 |
try:
|
| 116 |
girias = self.db.listar_girias_aprendidas(self.user_key)
|
| 117 |
+
# Garante que o resultado é uma lista de dicts com chaves str
|
| 118 |
self.girias_aprendidas = [
|
| 119 |
+
{"giria": str(g[0]), "significado": str(g[1])}
|
| 120 |
+
for g in girias
|
| 121 |
]
|
| 122 |
except Exception as e:
|
| 123 |
logger.warning(f"Erro ao atualizar gírias: {e}")
|
|
|
|
| 125 |
|
| 126 |
def analisar_emocoes_mensagem(self, mensagem: str) -> str:
|
| 127 |
msg = mensagem.lower()
|
| 128 |
+
# Lembre-se que este método retorna uma STRING
|
| 129 |
if any(p in msg for p in ["feliz", "fixe", "bué bom", "adoro", "rsrs", "kkk"]):
|
| 130 |
return "feliz"
|
| 131 |
if any(p in msg for p in ["triste", "chateado", "merda", "puto", "caralho"]):
|
|
|
|
| 137 |
return "neutra"
|
| 138 |
|
| 139 |
def obter_historico(self) -> List[Tuple[str, str]]:
|
| 140 |
+
# Garante que sempre retorna uma lista de tuples
|
| 141 |
return self.historico[-3:]
|
| 142 |
|
| 143 |
def atualizar_contexto(self, mensagem: str, resposta: str):
|