Update modules/database/chat_mongo_db.py
Browse files- modules/database/chat_mongo_db.py +140 -117
modules/database/chat_mongo_db.py
CHANGED
|
@@ -1,117 +1,140 @@
|
|
| 1 |
-
# /modules/database/chat_mongo_db.py
|
| 2 |
-
from .mongo_db import insert_document, find_documents, get_collection
|
| 3 |
-
from datetime import datetime, timezone
|
| 4 |
-
import logging
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /modules/database/chat_mongo_db.py
|
| 2 |
+
from .mongo_db import insert_document, find_documents, get_collection
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
import logging
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
COLLECTION_NAME = 'chat_history-v3'
|
| 9 |
+
|
| 10 |
+
def clean_text_content(text: str) -> str:
|
| 11 |
+
"""
|
| 12 |
+
Limpia y normaliza el texto para almacenamiento seguro en UTF-8.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
text: Texto a limpiar
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
str: Texto limpio y normalizado
|
| 19 |
+
"""
|
| 20 |
+
if not text:
|
| 21 |
+
return text
|
| 22 |
+
|
| 23 |
+
# Caracteres especiales a eliminar (incluyendo los bloques y otros caracteres problemáticos)
|
| 24 |
+
special_chars = ["▌", "\u2588", "\u2580", "\u2584", "\u258C", "\u2590"]
|
| 25 |
+
|
| 26 |
+
# Eliminar caracteres especiales
|
| 27 |
+
for char in special_chars:
|
| 28 |
+
text = text.replace(char, "")
|
| 29 |
+
|
| 30 |
+
# Normalizar espacios y saltos de línea
|
| 31 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 32 |
+
|
| 33 |
+
# Asegurar codificación UTF-8
|
| 34 |
+
try:
|
| 35 |
+
text = text.encode('utf-8', errors='strict').decode('utf-8')
|
| 36 |
+
except UnicodeError:
|
| 37 |
+
text = text.encode('utf-8', errors='ignore').decode('utf-8')
|
| 38 |
+
logger.warning("Se encontraron caracteres no UTF-8 en el texto")
|
| 39 |
+
|
| 40 |
+
return text
|
| 41 |
+
|
| 42 |
+
def get_chat_history(username: str, analysis_type: str = 'sidebar', limit: int = None) -> list:
|
| 43 |
+
"""
|
| 44 |
+
Recupera el historial del chat con codificación UTF-8 segura.
|
| 45 |
+
"""
|
| 46 |
+
try:
|
| 47 |
+
query = {
|
| 48 |
+
"username": username,
|
| 49 |
+
"analysis_type": analysis_type
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
collection = get_collection(COLLECTION_NAME)
|
| 53 |
+
if collection is None:
|
| 54 |
+
logger.error("No se pudo obtener la colección de chat")
|
| 55 |
+
return []
|
| 56 |
+
|
| 57 |
+
cursor = collection.find(query).sort("timestamp", -1)
|
| 58 |
+
if limit:
|
| 59 |
+
cursor = cursor.limit(limit)
|
| 60 |
+
|
| 61 |
+
conversations = []
|
| 62 |
+
for chat in cursor:
|
| 63 |
+
try:
|
| 64 |
+
# Limpiar y asegurar UTF-8 en cada mensaje
|
| 65 |
+
cleaned_messages = []
|
| 66 |
+
for msg in chat.get('messages', []):
|
| 67 |
+
try:
|
| 68 |
+
cleaned_messages.append({
|
| 69 |
+
'role': msg.get('role', 'unknown'),
|
| 70 |
+
'content': clean_text_content(msg.get('content', ''))
|
| 71 |
+
})
|
| 72 |
+
except Exception as msg_error:
|
| 73 |
+
logger.error(f"Error procesando mensaje: {str(msg_error)}")
|
| 74 |
+
continue
|
| 75 |
+
|
| 76 |
+
conversations.append({
|
| 77 |
+
'timestamp': chat['timestamp'],
|
| 78 |
+
'messages': cleaned_messages
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.error(f"Error formateando chat: {str(e)}")
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
return conversations
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"Error al recuperar historial de chat: {str(e)}")
|
| 89 |
+
return []
|
| 90 |
+
|
| 91 |
+
def store_chat_history(username: str, messages: list, analysis_type: str = 'sidebar', metadata: dict = None) -> bool:
|
| 92 |
+
"""
|
| 93 |
+
Guarda el historial del chat con codificación UTF-8 segura.
|
| 94 |
+
"""
|
| 95 |
+
try:
|
| 96 |
+
collection = get_collection(COLLECTION_NAME)
|
| 97 |
+
if collection is None:
|
| 98 |
+
logger.error("No se pudo obtener la colección de chat")
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
# Limpiar y formatear cada mensaje
|
| 102 |
+
formatted_messages = []
|
| 103 |
+
for msg in messages:
|
| 104 |
+
try:
|
| 105 |
+
formatted_messages.append({
|
| 106 |
+
'role': msg.get('role', 'unknown'),
|
| 107 |
+
'content': clean_text_content(msg.get('content', '')),
|
| 108 |
+
'timestamp': datetime.now(timezone.utc).isoformat()
|
| 109 |
+
})
|
| 110 |
+
except Exception as msg_error:
|
| 111 |
+
logger.error(f"Error procesando mensaje para almacenar: {str(msg_error)}")
|
| 112 |
+
continue
|
| 113 |
+
|
| 114 |
+
chat_document = {
|
| 115 |
+
'username': username,
|
| 116 |
+
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 117 |
+
'messages': formatted_messages,
|
| 118 |
+
'analysis_type': analysis_type,
|
| 119 |
+
'metadata': metadata or {}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
# Verificación adicional de UTF-8 antes de insertar
|
| 123 |
+
try:
|
| 124 |
+
import json
|
| 125 |
+
json.dumps(chat_document, ensure_ascii=False)
|
| 126 |
+
except UnicodeEncodeError as e:
|
| 127 |
+
logger.error(f"Error de codificación en documento: {str(e)}")
|
| 128 |
+
return False
|
| 129 |
+
|
| 130 |
+
result = collection.insert_one(chat_document)
|
| 131 |
+
if result.inserted_id:
|
| 132 |
+
logger.info(f"Chat guardado para {username} con ID: {result.inserted_id}")
|
| 133 |
+
return True
|
| 134 |
+
|
| 135 |
+
logger.error("No se pudo insertar el documento")
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
except Exception as e:
|
| 139 |
+
logger.error(f"Error al guardar historial: {str(e)}")
|
| 140 |
+
return False
|