Update database.py
Browse files- database.py +35 -6
database.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
-
# database.py —
|
| 2 |
import sqlite3
|
| 3 |
import time
|
| 4 |
import os
|
| 5 |
import json
|
|
|
|
| 6 |
from typing import List, Dict, Any, Tuple
|
| 7 |
from loguru import logger
|
| 8 |
|
|
|
|
| 9 |
class Database:
|
| 10 |
def __init__(self, db_path: str = "/app/akira.db"):
|
| 11 |
self.db_path = db_path
|
|
@@ -189,7 +191,6 @@ class Database:
|
|
| 189 |
girias TEXT,
|
| 190 |
tom TEXT
|
| 191 |
);
|
| 192 |
-
|
| 193 |
-- TABELAS NOVAS (V22/V23)
|
| 194 |
CREATE TABLE IF NOT EXISTS abrev_usuarios (
|
| 195 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -198,7 +199,6 @@ class Database:
|
|
| 198 |
palavra_completa TEXT,
|
| 199 |
frequencia INTEGER DEFAULT 1
|
| 200 |
);
|
| 201 |
-
|
| 202 |
-- DADOS INICIAIS
|
| 203 |
INSERT OR IGNORE INTO pronomes_por_tom (tom, pronomes) VALUES
|
| 204 |
('formal', 'Sr., ilustre, boss, maior, homem'),
|
|
@@ -207,7 +207,7 @@ class Database:
|
|
| 207 |
('neutro', 'amigo, parceiro, camarada');
|
| 208 |
''')
|
| 209 |
conn.commit()
|
| 210 |
-
logger.info(f"Banco
|
| 211 |
|
| 212 |
# ================================================================
|
| 213 |
# MIGRAÇÃO AUTOMÁTICA — GARANTE COLUNAS + ÍNDICES
|
|
@@ -224,7 +224,6 @@ class Database:
|
|
| 224 |
c.execute("ALTER TABLE embeddings ADD COLUMN source_type TEXT DEFAULT 'conversa'")
|
| 225 |
if 'texto' not in cols:
|
| 226 |
c.execute("ALTER TABLE embeddings ADD COLUMN texto TEXT DEFAULT ''")
|
| 227 |
-
|
| 228 |
# Índices
|
| 229 |
c.executescript('''
|
| 230 |
CREATE INDEX IF NOT EXISTS idx_mensagens_numero ON mensagens(numero);
|
|
@@ -291,4 +290,34 @@ class Database:
|
|
| 291 |
casual = any(w in mensagem.lower() for w in ["epá", "kandando", "bué", "kota"])
|
| 292 |
if rude: return "rude"
|
| 293 |
if casual: return "casual"
|
| 294 |
-
return "neutro"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# database.py — V24 — COMPLETO COM salvar_embedding() + NUMPY + MIGRAÇÕES
|
| 2 |
import sqlite3
|
| 3 |
import time
|
| 4 |
import os
|
| 5 |
import json
|
| 6 |
+
import numpy as np
|
| 7 |
from typing import List, Dict, Any, Tuple
|
| 8 |
from loguru import logger
|
| 9 |
|
| 10 |
+
|
| 11 |
class Database:
|
| 12 |
def __init__(self, db_path: str = "/app/akira.db"):
|
| 13 |
self.db_path = db_path
|
|
|
|
| 191 |
girias TEXT,
|
| 192 |
tom TEXT
|
| 193 |
);
|
|
|
|
| 194 |
-- TABELAS NOVAS (V22/V23)
|
| 195 |
CREATE TABLE IF NOT EXISTS abrev_usuarios (
|
| 196 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 199 |
palavra_completa TEXT,
|
| 200 |
frequencia INTEGER DEFAULT 1
|
| 201 |
);
|
|
|
|
| 202 |
-- DADOS INICIAIS
|
| 203 |
INSERT OR IGNORE INTO pronomes_por_tom (tom, pronomes) VALUES
|
| 204 |
('formal', 'Sr., ilustre, boss, maior, homem'),
|
|
|
|
| 207 |
('neutro', 'amigo, parceiro, camarada');
|
| 208 |
''')
|
| 209 |
conn.commit()
|
| 210 |
+
logger.info(f"Banco V24 inicializado: {self.db_path}")
|
| 211 |
|
| 212 |
# ================================================================
|
| 213 |
# MIGRAÇÃO AUTOMÁTICA — GARANTE COLUNAS + ÍNDICES
|
|
|
|
| 224 |
c.execute("ALTER TABLE embeddings ADD COLUMN source_type TEXT DEFAULT 'conversa'")
|
| 225 |
if 'texto' not in cols:
|
| 226 |
c.execute("ALTER TABLE embeddings ADD COLUMN texto TEXT DEFAULT ''")
|
|
|
|
| 227 |
# Índices
|
| 228 |
c.executescript('''
|
| 229 |
CREATE INDEX IF NOT EXISTS idx_mensagens_numero ON mensagens(numero);
|
|
|
|
| 290 |
casual = any(w in mensagem.lower() for w in ["epá", "kandando", "bué", "kota"])
|
| 291 |
if rude: return "rude"
|
| 292 |
if casual: return "casual"
|
| 293 |
+
return "neutro"
|
| 294 |
+
|
| 295 |
+
# ================================================================
|
| 296 |
+
# NOVO MÉTODO: salvar_embedding() — COM NUMPY
|
| 297 |
+
# ================================================================
|
| 298 |
+
def salvar_embedding(self, numero_usuario: str, mensagem: str, resposta: str, embedding: list, texto: str = ""):
|
| 299 |
+
"""
|
| 300 |
+
Salva embedding no banco (tabela 'embeddings').
|
| 301 |
+
"""
|
| 302 |
+
try:
|
| 303 |
+
embedding_blob = np.array(embedding, dtype=np.float32).tobytes()
|
| 304 |
+
|
| 305 |
+
self._execute(
|
| 306 |
+
"""INSERT INTO embeddings
|
| 307 |
+
(numero_usuario, source_type, texto, embedding)
|
| 308 |
+
VALUES (?, ?, ?, ?)""",
|
| 309 |
+
(numero_usuario, 'conversa', texto or f"{mensagem} {resposta}", embedding_blob),
|
| 310 |
+
commit=True
|
| 311 |
+
)
|
| 312 |
+
logger.debug(f"Embedding salvo para {numero_usuario}")
|
| 313 |
+
except Exception as e:
|
| 314 |
+
logger.error(f"Erro ao salvar embedding: {e}")
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# ================================================================
|
| 318 |
+
# TESTE RÁPIDO (OPCIONAL)
|
| 319 |
+
# ================================================================
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
db = Database()
|
| 322 |
+
db.salvar_mensagem("Zé", "Oi", "Epá!", "244999123456")
|
| 323 |
+
print("Banco V24 pronto!")
|