Spaces:
Running
Running
Update modules/database.py
Browse files- modules/database.py +102 -41
modules/database.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
# modules/database.py — AKIRA V21 FINAL CORRIGIDO (Dezembro 2025)
|
| 2 |
"""
|
| 3 |
✅ TOTALMENTE ADAPTADO ao index.js atualizado
|
| 4 |
-
✅ CORREÇÃO:
|
|
|
|
| 5 |
✅ Estrutura completa com reply_metadata
|
| 6 |
✅ Todos os métodos necessários implementados
|
| 7 |
"""
|
|
@@ -11,6 +12,7 @@ import time
|
|
| 11 |
import os
|
| 12 |
import json
|
| 13 |
import hashlib
|
|
|
|
| 14 |
from datetime import datetime
|
| 15 |
from typing import Optional, List, Dict, Any, Tuple
|
| 16 |
from loguru import logger
|
|
@@ -67,12 +69,12 @@ class Database:
|
|
| 67 |
raise
|
| 68 |
|
| 69 |
def _init_db(self):
|
| 70 |
-
"""Cria todas as tabelas necessárias"""
|
| 71 |
try:
|
| 72 |
with self._get_connection() as conn:
|
| 73 |
c = conn.cursor()
|
| 74 |
|
| 75 |
-
# Tabela principal de mensagens
|
| 76 |
c.execute('''
|
| 77 |
CREATE TABLE IF NOT EXISTS mensagens (
|
| 78 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -112,7 +114,7 @@ class Database:
|
|
| 112 |
comando_executado TEXT,
|
| 113 |
has_media BOOLEAN DEFAULT 0,
|
| 114 |
media_type TEXT DEFAULT '',
|
| 115 |
-
message_id TEXT UNIQUE
|
| 116 |
bot_response_time_ms INTEGER DEFAULT 0,
|
| 117 |
is_mention BOOLEAN DEFAULT 0,
|
| 118 |
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
@@ -120,6 +122,18 @@ class Database:
|
|
| 120 |
)
|
| 121 |
''')
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
# Usuários privilegiados
|
| 124 |
c.execute('''
|
| 125 |
CREATE TABLE IF NOT EXISTS usuarios_privilegiados (
|
|
@@ -257,7 +271,7 @@ class Database:
|
|
| 257 |
''')
|
| 258 |
|
| 259 |
conn.commit()
|
| 260 |
-
logger.info("✅ Tabelas criadas/verificadas")
|
| 261 |
|
| 262 |
except Exception as e:
|
| 263 |
logger.error(f"❌ Erro ao criar tabelas: {e}")
|
|
@@ -284,7 +298,7 @@ class Database:
|
|
| 284 |
("is_mention", "BOOLEAN DEFAULT 0"),
|
| 285 |
("has_media", "BOOLEAN DEFAULT 0"),
|
| 286 |
("media_type", "TEXT DEFAULT ''"),
|
| 287 |
-
("message_id", "TEXT
|
| 288 |
("bot_response_time_ms", "INTEGER DEFAULT 0")
|
| 289 |
]
|
| 290 |
|
|
@@ -297,10 +311,10 @@ class Database:
|
|
| 297 |
conn.commit()
|
| 298 |
|
| 299 |
except Exception as e:
|
| 300 |
-
logger.warning(f"Erro ao verificar colunas: {e}")
|
| 301 |
|
| 302 |
# ========================================================================
|
| 303 |
-
# MÉTODOS DE SALVAMENTO (ADAPTADOS AO INDEX.JS)
|
| 304 |
# ========================================================================
|
| 305 |
|
| 306 |
def salvar_mensagem(self, usuario: str, mensagem: str, resposta: str,
|
|
@@ -327,7 +341,7 @@ class Database:
|
|
| 327 |
message_id: str = None,
|
| 328 |
bot_response_time_ms: int = 0,
|
| 329 |
is_mention: bool = False) -> bool:
|
| 330 |
-
"""Salva mensagem no banco -
|
| 331 |
try:
|
| 332 |
numero_final = str(numero or usuario).strip()
|
| 333 |
contexto_id = self._gerar_contexto_id(numero_final, tipo_conversa)
|
|
@@ -336,39 +350,85 @@ class Database:
|
|
| 336 |
if isinstance(reply_info_json, dict):
|
| 337 |
reply_info_json = json.dumps(reply_info_json, ensure_ascii=False)
|
| 338 |
|
| 339 |
-
# Gera message_id se não fornecido
|
| 340 |
if not message_id:
|
| 341 |
-
|
|
|
|
|
|
|
| 342 |
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
tipo_conversa, tipo_mensagem, is_reply, mensagem_original, mensagem_citada_limpa,
|
| 348 |
-
reply_to_bot, reply_info_json, humor, modo_resposta, emocao_detectada,
|
| 349 |
-
confianca_emocao, grupo_id, grupo_nome, audio_transcricao, fonte_stt,
|
| 350 |
-
confianca_stt, comando_executado, has_media, media_type, message_id,
|
| 351 |
-
bot_response_time_ms, is_mention)
|
| 352 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 353 |
-
""",
|
| 354 |
-
(
|
| 355 |
-
usuario[:50], usuario_nome[:100] or usuario[:100],
|
| 356 |
-
mensagem[:4000], resposta[:4000], numero_final,
|
| 357 |
-
contexto_id, tipo_conversa, tipo_conversa, tipo_mensagem,
|
| 358 |
-
int(is_reply), mensagem_original, mensagem_citada_limpa,
|
| 359 |
-
int(reply_to_bot), reply_info_json, humor, modo_resposta,
|
| 360 |
-
emocao_detectada, confianca_emocao, grupo_id[:50], grupo_nome[:100],
|
| 361 |
-
audio_transcricao[:2000] if audio_transcricao else None,
|
| 362 |
-
fonte_stt[:50], confianca_stt, comando_executado[:100] if comando_executado else None,
|
| 363 |
-
int(has_media), media_type[:50], message_id[:100],
|
| 364 |
-
bot_response_time_ms, int(is_mention)
|
| 365 |
-
),
|
| 366 |
-
commit=True,
|
| 367 |
-
fetch=False
|
| 368 |
-
)
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
except Exception as e:
|
| 374 |
logger.error(f"❌ Erro ao salvar mensagem: {e}")
|
|
@@ -616,7 +676,8 @@ class Database:
|
|
| 616 |
(numero, comando, parametros, sucesso, resposta, tipo_conversa, grupo_id)
|
| 617 |
VALUES (?, ?, ?, ?, ?, ?, ?)
|
| 618 |
""",
|
| 619 |
-
(
|
|
|
|
| 620 |
commit=True,
|
| 621 |
fetch=False
|
| 622 |
)
|
|
|
|
| 1 |
+
# modules/database.py — AKIRA V21 FINAL CORRIGIDO (Dezembro 2025) - CORREÇÃO: message_id
|
| 2 |
"""
|
| 3 |
✅ TOTALMENTE ADAPTADO ao index.js atualizado
|
| 4 |
+
✅ CORREÇÃO: Problema com message_id UNIQUE resolvido
|
| 5 |
+
✅ Métodos corretos para api.py, contexto.py, treinamento.py
|
| 6 |
✅ Estrutura completa com reply_metadata
|
| 7 |
✅ Todos os métodos necessários implementados
|
| 8 |
"""
|
|
|
|
| 12 |
import os
|
| 13 |
import json
|
| 14 |
import hashlib
|
| 15 |
+
import random
|
| 16 |
from datetime import datetime
|
| 17 |
from typing import Optional, List, Dict, Any, Tuple
|
| 18 |
from loguru import logger
|
|
|
|
| 69 |
raise
|
| 70 |
|
| 71 |
def _init_db(self):
|
| 72 |
+
"""Cria todas as tabelas necessárias - CORREÇÃO: message_id sem UNIQUE"""
|
| 73 |
try:
|
| 74 |
with self._get_connection() as conn:
|
| 75 |
c = conn.cursor()
|
| 76 |
|
| 77 |
+
# Tabela principal de mensagens - CORREÇÃO: message_id sem UNIQUE
|
| 78 |
c.execute('''
|
| 79 |
CREATE TABLE IF NOT EXISTS mensagens (
|
| 80 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 114 |
comando_executado TEXT,
|
| 115 |
has_media BOOLEAN DEFAULT 0,
|
| 116 |
media_type TEXT DEFAULT '',
|
| 117 |
+
message_id TEXT, -- CORREÇÃO: Removido UNIQUE
|
| 118 |
bot_response_time_ms INTEGER DEFAULT 0,
|
| 119 |
is_mention BOOLEAN DEFAULT 0,
|
| 120 |
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
|
|
| 122 |
)
|
| 123 |
''')
|
| 124 |
|
| 125 |
+
# Índice para message_id para performance (sem UNIQUE)
|
| 126 |
+
c.execute('''
|
| 127 |
+
CREATE INDEX IF NOT EXISTS idx_mensagens_message_id
|
| 128 |
+
ON mensagens(message_id)
|
| 129 |
+
''')
|
| 130 |
+
|
| 131 |
+
# Índice para busca por número
|
| 132 |
+
c.execute('''
|
| 133 |
+
CREATE INDEX IF NOT EXISTS idx_mensagens_numero
|
| 134 |
+
ON mensagens(numero)
|
| 135 |
+
''')
|
| 136 |
+
|
| 137 |
# Usuários privilegiados
|
| 138 |
c.execute('''
|
| 139 |
CREATE TABLE IF NOT EXISTS usuarios_privilegiados (
|
|
|
|
| 271 |
''')
|
| 272 |
|
| 273 |
conn.commit()
|
| 274 |
+
logger.info("✅ Tabelas criadas/verificadas com message_id corrigido")
|
| 275 |
|
| 276 |
except Exception as e:
|
| 277 |
logger.error(f"❌ Erro ao criar tabelas: {e}")
|
|
|
|
| 298 |
("is_mention", "BOOLEAN DEFAULT 0"),
|
| 299 |
("has_media", "BOOLEAN DEFAULT 0"),
|
| 300 |
("media_type", "TEXT DEFAULT ''"),
|
| 301 |
+
("message_id", "TEXT"), # CORREÇÃO: Sem UNIQUE aqui também
|
| 302 |
("bot_response_time_ms", "INTEGER DEFAULT 0")
|
| 303 |
]
|
| 304 |
|
|
|
|
| 311 |
conn.commit()
|
| 312 |
|
| 313 |
except Exception as e:
|
| 314 |
+
logger.warning(f"⚠️ Erro ao verificar colunas: {e}")
|
| 315 |
|
| 316 |
# ========================================================================
|
| 317 |
+
# MÉTODOS DE SALVAMENTO (ADAPTADOS AO INDEX.JS) - CORRIGIDOS
|
| 318 |
# ========================================================================
|
| 319 |
|
| 320 |
def salvar_mensagem(self, usuario: str, mensagem: str, resposta: str,
|
|
|
|
| 341 |
message_id: str = None,
|
| 342 |
bot_response_time_ms: int = 0,
|
| 343 |
is_mention: bool = False) -> bool:
|
| 344 |
+
"""Salva mensagem no banco - CORREÇÃO: message_id sem UNIQUE constraint"""
|
| 345 |
try:
|
| 346 |
numero_final = str(numero or usuario).strip()
|
| 347 |
contexto_id = self._gerar_contexto_id(numero_final, tipo_conversa)
|
|
|
|
| 350 |
if isinstance(reply_info_json, dict):
|
| 351 |
reply_info_json = json.dumps(reply_info_json, ensure_ascii=False)
|
| 352 |
|
| 353 |
+
# CORREÇÃO: Gera message_id único se não fornecido
|
| 354 |
if not message_id:
|
| 355 |
+
timestamp = int(time.time() * 1000)
|
| 356 |
+
random_suffix = random.randint(1000, 9999)
|
| 357 |
+
message_id = f"{numero_final}_{timestamp}_{random_suffix}"
|
| 358 |
|
| 359 |
+
# CORREÇÃO: Adiciona um sufixo aleatório extra para garantir unicidade
|
| 360 |
+
# mesmo que o timestamp seja o mesmo
|
| 361 |
+
unique_suffix = random.randint(100, 999)
|
| 362 |
+
message_id = f"{message_id}_{unique_suffix}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
+
try:
|
| 365 |
+
self._execute_with_retry(
|
| 366 |
+
"""
|
| 367 |
+
INSERT INTO mensagens
|
| 368 |
+
(usuario, usuario_nome, mensagem, resposta, numero, contexto_id, tipo_contexto,
|
| 369 |
+
tipo_conversa, tipo_mensagem, is_reply, mensagem_original, mensagem_citada_limpa,
|
| 370 |
+
reply_to_bot, reply_info_json, humor, modo_resposta, emocao_detectada,
|
| 371 |
+
confianca_emocao, grupo_id, grupo_nome, audio_transcricao, fonte_stt,
|
| 372 |
+
confianca_stt, comando_executado, has_media, media_type, message_id,
|
| 373 |
+
bot_response_time_ms, is_mention)
|
| 374 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 375 |
+
""",
|
| 376 |
+
(
|
| 377 |
+
usuario[:50], usuario_nome[:100] or usuario[:100],
|
| 378 |
+
mensagem[:4000], resposta[:4000], numero_final,
|
| 379 |
+
contexto_id, tipo_conversa, tipo_conversa, tipo_mensagem,
|
| 380 |
+
int(is_reply), mensagem_original, mensagem_citada_limpa,
|
| 381 |
+
int(reply_to_bot), reply_info_json, humor, modo_resposta,
|
| 382 |
+
emocao_detectada, confianca_emocao, grupo_id[:50], grupo_nome[:100],
|
| 383 |
+
audio_transcricao[:2000] if audio_transcricao else None,
|
| 384 |
+
fonte_stt[:50], confianca_stt, comando_executado[:100] if comando_executado else None,
|
| 385 |
+
int(has_media), media_type[:50], message_id[:200],
|
| 386 |
+
bot_response_time_ms, int(is_mention)
|
| 387 |
+
),
|
| 388 |
+
commit=True,
|
| 389 |
+
fetch=False
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
logger.debug(f"✅ Mensagem salva: {numero_final} | Message ID: {message_id}")
|
| 393 |
+
return True
|
| 394 |
+
|
| 395 |
+
except sqlite3.IntegrityError as e:
|
| 396 |
+
# CORREÇÃO: Se ainda houver erro de UNIQUE (pode ser de outra coluna)
|
| 397 |
+
if "UNIQUE constraint failed" in str(e):
|
| 398 |
+
logger.warning(f"🔄 Erro de UNIQUE, gerando novo message_id")
|
| 399 |
+
# Gera um novo message_id completamente diferente
|
| 400 |
+
new_message_id = f"{numero_final}_{int(time.time() * 1000)}_{random.randint(10000, 99999)}"
|
| 401 |
+
|
| 402 |
+
self._execute_with_retry(
|
| 403 |
+
"""
|
| 404 |
+
INSERT INTO mensagens
|
| 405 |
+
(usuario, usuario_nome, mensagem, resposta, numero, contexto_id, tipo_contexto,
|
| 406 |
+
tipo_conversa, tipo_mensagem, is_reply, mensagem_original, mensagem_citada_limpa,
|
| 407 |
+
reply_to_bot, reply_info_json, humor, modo_resposta, emocao_detectada,
|
| 408 |
+
confianca_emocao, grupo_id, grupo_nome, audio_transcricao, fonte_stt,
|
| 409 |
+
confianca_stt, comando_executado, has_media, media_type, message_id,
|
| 410 |
+
bot_response_time_ms, is_mention)
|
| 411 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 412 |
+
""",
|
| 413 |
+
(
|
| 414 |
+
usuario[:50], usuario_nome[:100] or usuario[:100],
|
| 415 |
+
mensagem[:4000], resposta[:4000], numero_final,
|
| 416 |
+
contexto_id, tipo_conversa, tipo_conversa, tipo_mensagem,
|
| 417 |
+
int(is_reply), mensagem_original, mensagem_citada_limpa,
|
| 418 |
+
int(reply_to_bot), reply_info_json, humor, modo_resposta,
|
| 419 |
+
emocao_detectada, confianca_emocao, grupo_id[:50], grupo_nome[:100],
|
| 420 |
+
audio_transcricao[:2000] if audio_transcricao else None,
|
| 421 |
+
fonte_stt[:50], confianca_stt, comando_executado[:100] if comando_executado else None,
|
| 422 |
+
int(has_media), media_type[:50], new_message_id[:200],
|
| 423 |
+
bot_response_time_ms, int(is_mention)
|
| 424 |
+
),
|
| 425 |
+
commit=True,
|
| 426 |
+
fetch=False
|
| 427 |
+
)
|
| 428 |
+
logger.debug(f"✅ Mensagem salva com novo message_id: {new_message_id}")
|
| 429 |
+
return True
|
| 430 |
+
else:
|
| 431 |
+
raise
|
| 432 |
|
| 433 |
except Exception as e:
|
| 434 |
logger.error(f"❌ Erro ao salvar mensagem: {e}")
|
|
|
|
| 676 |
(numero, comando, parametros, sucesso, resposta, tipo_conversa, grupo_id)
|
| 677 |
VALUES (?, ?, ?, ?, ?, ?, ?)
|
| 678 |
""",
|
| 679 |
+
(
|
| 680 |
+
str(numero).strip(), comando, parametros, int(sucesso), resposta, tipo_conversa, grupo_id),
|
| 681 |
commit=True,
|
| 682 |
fetch=False
|
| 683 |
)
|