akra35567 commited on
Commit
8e7cff7
·
1 Parent(s): 03a73f0

Update modules/database.py

Browse files
Files changed (1) hide show
  1. modules/database.py +54 -15
modules/database.py CHANGED
@@ -291,19 +291,30 @@ class Database:
291
  # MÉTODOS OBRIGATÓRIOS (SEM fetch!)
292
  # ================================================================
293
  def carregar_contexto(self, user_key: str) -> Dict[str, Any]:
294
- """Carrega contexto do usuário"""
295
  try:
296
  result = self._execute_with_retry(
297
  "SELECT historico, emocao_atual, termos, girias, tom FROM contexto WHERE user_key = ?",
298
  (user_key,)
299
  )
 
 
 
 
 
 
 
 
 
 
 
300
  if result:
301
  row = result[0]
302
  return {
303
- "historico": row[0] or "[]",
304
  "emocao_atual": row[1] or "neutra",
305
- "termos": row[2] or "[]",
306
- "girias": row[3] or "[]",
307
  "tom": row[4] or "neutro"
308
  }
309
  return {}
@@ -341,31 +352,55 @@ class Database:
341
  try:
342
  cols = ['usuario', 'mensagem', 'resposta']
343
  vals = [usuario, mensagem, resposta]
344
- if numero: cols.append('numero'); vals.append(numero)
345
- if is_reply is not None: cols.append('is_reply'); vals.append(int(is_reply))
346
- if mensagem_original: cols.append('mensagem_original'); vals.append(mensagem_original)
 
 
 
 
 
 
347
  placeholders = ', '.join(['?' for _ in cols])
348
  query = f"INSERT INTO mensagens ({', '.join(cols)}) VALUES ({placeholders})"
349
  self._execute_with_retry(query, tuple(vals), commit=True)
350
  except Exception as e:
351
  logger.warning(f"Fallback salvar_mensagem: {e}")
352
- self._execute_with_retry("INSERT INTO mensagens (usuario, mensagem, resposta) VALUES (?, ?, ?)", (usuario, mensagem, resposta), commit=True)
 
 
 
 
353
 
354
- def recuperar_mensagens(self, usuario: str, limite: int = 5) -> List[Tuple]:
355
  return self._execute_with_retry(
356
  "SELECT mensagem, resposta FROM mensagens WHERE usuario=? OR numero=? ORDER BY id DESC LIMIT ?",
357
  (usuario, usuario, limite)
358
  ) or []
359
 
360
  def salvar_giria_aprendida(self, numero_usuario: str, giria: str, significado: str, contexto: Optional[str] = None):
361
- existing = self._execute_with_retry("SELECT id, frequencia FROM girias_aprendidas WHERE numero_usuario=? AND giria=?", (numero_usuario, giria))
 
 
 
362
  if existing:
363
- self._execute_with_retry("UPDATE girias_aprendidas SET frequencia=frequencia+1, updated_at=CURRENT_TIMESTAMP WHERE id=?", (existing[0][0],), commit=True)
 
 
 
 
364
  else:
365
- self._execute_with_retry("INSERT INTO girias_aprendidas (numero_usuario, giria, significado, contexto) VALUES (?, ?, ?, ?)", (numero_usuario, giria, significado, contexto), commit=True)
 
 
 
 
366
 
367
  def recuperar_girias_usuario(self, numero_usuario: str) -> List[Dict[str, Any]]:
368
- result = self._execute_with_retry("SELECT giria, significado, contexto, frequencia FROM girias_aprendidas WHERE numero_usuario=? ORDER BY frequencia DESC, updated_at DESC", (numero_usuario,))
 
 
 
369
  return [{"giria": r[0], "significado": r[1], "contexto": r[2], "frequencia": r[3]} for r in result] if result else []
370
 
371
  def obter_tom_predominante(self, numero_usuario: str, limite: int = 10) -> Optional[str]:
@@ -377,7 +412,11 @@ class Database:
377
  return result[0][0] if result else None
378
 
379
  def registrar_tom_usuario(self, numero_usuario: str, tom_detectado: str, intensidade: float = 0.5, contexto: Optional[str] = None):
380
- self._execute_with_retry("INSERT INTO tom_usuario (numero_usuario, tom_detectado, intensidade, contexto) VALUES (?, ?, ?, ?)", (numero_usuario, tom_detectado, intensidade, contexto), commit=True)
 
 
 
 
381
 
382
  def obter_pronomes_por_tom(self, tom: str) -> str:
383
  result = self._execute_with_retry("SELECT pronomes FROM pronomes_por_tom WHERE tom=?", (tom.lower(),))
@@ -426,4 +465,4 @@ class Database:
426
  emocoes["tristeza"] = 0.8; emocoes["neutro"] = 0.2
427
  elif any(p in msg for p in ["medo", "assustado", "tenso", "nervoso"]):
428
  emocoes["medo"] = 0.8; emocoes["neutro"] = 0.2
429
- return emocoes
 
291
  # MÉTODOS OBRIGATÓRIOS (SEM fetch!)
292
  # ================================================================
293
  def carregar_contexto(self, user_key: str) -> Dict[str, Any]:
294
+ """Carrega contexto do usuário com correção JSON segura"""
295
  try:
296
  result = self._execute_with_retry(
297
  "SELECT historico, emocao_atual, termos, girias, tom FROM contexto WHERE user_key = ?",
298
  (user_key,)
299
  )
300
+
301
+ def safe_json_load(v, default):
302
+ if not v:
303
+ return default
304
+ if isinstance(v, (list, dict)):
305
+ return v
306
+ try:
307
+ return json.loads(v)
308
+ except Exception:
309
+ return default
310
+
311
  if result:
312
  row = result[0]
313
  return {
314
+ "historico": safe_json_load(row[0], []),
315
  "emocao_atual": row[1] or "neutra",
316
+ "termos": safe_json_load(row[2], []),
317
+ "girias": safe_json_load(row[3], []),
318
  "tom": row[4] or "neutro"
319
  }
320
  return {}
 
352
  try:
353
  cols = ['usuario', 'mensagem', 'resposta']
354
  vals = [usuario, mensagem, resposta]
355
+ if numero:
356
+ cols.append('numero')
357
+ vals.append(numero)
358
+ if is_reply is not None:
359
+ cols.append('is_reply')
360
+ vals.append(int(is_reply))
361
+ if mensagem_original:
362
+ cols.append('mensagem_original')
363
+ vals.append(mensagem_original)
364
  placeholders = ', '.join(['?' for _ in cols])
365
  query = f"INSERT INTO mensagens ({', '.join(cols)}) VALUES ({placeholders})"
366
  self._execute_with_retry(query, tuple(vals), commit=True)
367
  except Exception as e:
368
  logger.warning(f"Fallback salvar_mensagem: {e}")
369
+ self._execute_with_retry(
370
+ "INSERT INTO mensagens (usuario, mensagem, resposta) VALUES (?, ?, ?)",
371
+ (usuario, mensagem, resposta),
372
+ commit=True
373
+ )
374
 
375
+ def recuperar_mensagens(self, usuario: str, limite: int = 5) -> List[Tuple]]:
376
  return self._execute_with_retry(
377
  "SELECT mensagem, resposta FROM mensagens WHERE usuario=? OR numero=? ORDER BY id DESC LIMIT ?",
378
  (usuario, usuario, limite)
379
  ) or []
380
 
381
  def salvar_giria_aprendida(self, numero_usuario: str, giria: str, significado: str, contexto: Optional[str] = None):
382
+ existing = self._execute_with_retry(
383
+ "SELECT id, frequencia FROM girias_aprendidas WHERE numero_usuario=? AND giria=?",
384
+ (numero_usuario, giria)
385
+ )
386
  if existing:
387
+ self._execute_with_retry(
388
+ "UPDATE girias_aprendidas SET frequencia=frequencia+1, updated_at=CURRENT_TIMESTAMP WHERE id=?",
389
+ (existing[0][0],),
390
+ commit=True
391
+ )
392
  else:
393
+ self._execute_with_retry(
394
+ "INSERT INTO girias_aprendidas (numero_usuario, giria, significado, contexto) VALUES (?, ?, ?, ?)",
395
+ (numero_usuario, giria, significado, contexto),
396
+ commit=True
397
+ )
398
 
399
  def recuperar_girias_usuario(self, numero_usuario: str) -> List[Dict[str, Any]]:
400
+ result = self._execute_with_retry(
401
+ "SELECT giria, significado, contexto, frequencia FROM girias_aprendidas WHERE numero_usuario=? ORDER BY frequencia DESC, updated_at DESC",
402
+ (numero_usuario,)
403
+ )
404
  return [{"giria": r[0], "significado": r[1], "contexto": r[2], "frequencia": r[3]} for r in result] if result else []
405
 
406
  def obter_tom_predominante(self, numero_usuario: str, limite: int = 10) -> Optional[str]:
 
412
  return result[0][0] if result else None
413
 
414
  def registrar_tom_usuario(self, numero_usuario: str, tom_detectado: str, intensidade: float = 0.5, contexto: Optional[str] = None):
415
+ self._execute_with_retry(
416
+ "INSERT INTO tom_usuario (numero_usuario, tom_detectado, intensidade, contexto) VALUES (?, ?, ?, ?)",
417
+ (numero_usuario, tom_detectado, intensidade, contexto),
418
+ commit=True
419
+ )
420
 
421
  def obter_pronomes_por_tom(self, tom: str) -> str:
422
  result = self._execute_with_retry("SELECT pronomes FROM pronomes_por_tom WHERE tom=?", (tom.lower(),))
 
465
  emocoes["tristeza"] = 0.8; emocoes["neutro"] = 0.2
466
  elif any(p in msg for p in ["medo", "assustado", "tenso", "nervoso"]):
467
  emocoes["medo"] = 0.8; emocoes["neutro"] = 0.2
468
+ return emocoes