AIdeaText commited on
Commit
85ccd2a
·
verified ·
1 Parent(s): 5fbca50

Update modules/database/chat_mongo_db.py

Browse files
Files changed (1) hide show
  1. 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
- logger = logging.getLogger(__name__)
7
- COLLECTION_NAME = 'chat_history-v3'
8
-
9
- def get_chat_history(username: str, analysis_type: str = 'sidebar', limit: int = None) -> list:
10
- """
11
- Recupera el historial del chat.
12
-
13
- Args:
14
- username: Nombre del usuario
15
- analysis_type: Tipo de análisis ('sidebar' por defecto)
16
- limit: Límite de conversaciones a recuperar
17
-
18
- Returns:
19
- list: Lista de conversaciones con formato
20
- """
21
- try:
22
- query = {
23
- "username": username,
24
- "analysis_type": analysis_type
25
- }
26
-
27
- collection = get_collection(COLLECTION_NAME)
28
- if collection is None:
29
- logger.error("No se pudo obtener la colección de chat")
30
- return []
31
-
32
- # Obtener y formatear conversaciones
33
- cursor = collection.find(query).sort("timestamp", -1)
34
- if limit:
35
- cursor = cursor.limit(limit)
36
-
37
- conversations = []
38
- for chat in cursor:
39
- try:
40
- formatted_chat = {
41
- 'timestamp': chat['timestamp'],
42
- 'messages': [
43
- {
44
- 'role': msg.get('role', 'unknown'),
45
- 'content': msg.get('content', '')
46
- }
47
- for msg in chat.get('messages', [])
48
- ]
49
- }
50
- conversations.append(formatted_chat)
51
- except Exception as e:
52
- logger.error(f"Error formateando chat: {str(e)}")
53
- continue
54
-
55
- return conversations
56
-
57
- except Exception as e:
58
- logger.error(f"Error al recuperar historial de chat: {str(e)}")
59
- return []
60
-
61
- def store_chat_history(username: str, messages: list, analysis_type: str = 'sidebar') -> bool:
62
- """
63
- Guarda el historial del chat.
64
-
65
- Args:
66
- username: Nombre del usuario
67
- messages: Lista de mensajes a guardar
68
- analysis_type: Tipo de análisis
69
-
70
- Returns:
71
- bool: True si se guardó correctamente
72
- """
73
- try:
74
- collection = get_collection(COLLECTION_NAME)
75
- if collection is None:
76
- logger.error("No se pudo obtener la colección de chat")
77
- return False
78
-
79
- # Formatear mensajes antes de guardar
80
- formatted_messages = [
81
- {
82
- 'role': msg.get('role', 'unknown'),
83
- 'content': msg.get('content', ''),
84
- 'timestamp': datetime.now(timezone.utc).isoformat()
85
- }
86
- for msg in messages
87
- ]
88
-
89
- chat_document = {
90
- 'username': username,
91
- 'timestamp': datetime.now(timezone.utc).isoformat(),
92
- 'messages': formatted_messages,
93
- 'analysis_type': analysis_type,
94
- 'metadata': metadata or {} # Nuevo campo 18-5-2025
95
- }
96
-
97
- result = collection.insert_one(chat_document)
98
- if result.inserted_id:
99
- logger.info(f"Historial de chat guardado con ID: {result.inserted_id} para el usuario: {username}")
100
- return True
101
-
102
- logger.error("No se pudo insertar el documento")
103
- return False
104
-
105
- except Exception as e:
106
- logger.error(f"Error al guardar historial de chat: {str(e)}")
107
- return False
108
-
109
-
110
- #def get_chat_history(username, analysis_type=None, limit=10):
111
- # query = {"username": username}
112
- # if analysis_type:
113
- # query["analysis_type"] = analysis_type
114
-
115
- # return find_documents(COLLECTION_NAME, query, sort=[("timestamp", -1)], limit=limit)
116
-
117
- # Agregar funciones para actualizar y eliminar chat si es necesario
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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