Create semantic_mongo_live_db.py
Browse files
modules/database/semantic_mongo_live_db.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modules/database/semantic_mongo_live_db.py
|
2 |
+
import logging
|
3 |
+
import base64
|
4 |
+
from datetime import datetime, timezone
|
5 |
+
from pymongo.errors import PyMongoError
|
6 |
+
|
7 |
+
# Importaciones locales
|
8 |
+
from .mongo_db import (
|
9 |
+
get_collection,
|
10 |
+
insert_document,
|
11 |
+
find_documents,
|
12 |
+
update_document,
|
13 |
+
delete_document
|
14 |
+
)
|
15 |
+
|
16 |
+
# Configuraci贸n del logger
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
COLLECTION_NAME = 'student_semantic_live_analysis'
|
19 |
+
|
20 |
+
##########################################
|
21 |
+
##########################################
|
22 |
+
|
23 |
+
def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'):
|
24 |
+
"""
|
25 |
+
Versi贸n corregida con:
|
26 |
+
- Verificaci贸n correcta de colecci贸n
|
27 |
+
- Manejo de proyecci贸n alternativo
|
28 |
+
- Mejor manejo de errores
|
29 |
+
"""
|
30 |
+
try:
|
31 |
+
# 1. Obtener colecci贸n con verificaci贸n correcta
|
32 |
+
collection = get_collection(COLLECTION_NAME)
|
33 |
+
if collection is None: # Cambiado de 'if not collection'
|
34 |
+
logger.error(f"No se pudo obtener la colecci贸n {COLLECTION_NAME}")
|
35 |
+
return False
|
36 |
+
|
37 |
+
# 2. Validaci贸n de par谩metros
|
38 |
+
if not all([username, text, analysis_result]):
|
39 |
+
logger.error("Par谩metros incompletos para guardar an谩lisis")
|
40 |
+
return False
|
41 |
+
|
42 |
+
# 3. Preparar documento
|
43 |
+
analysis_document = {
|
44 |
+
'username': username,
|
45 |
+
'timestamp': datetime.now(timezone.utc),
|
46 |
+
'text': text[:50000],
|
47 |
+
'analysis_type': 'semantic_live',
|
48 |
+
'language': lang_code,
|
49 |
+
'key_concepts': analysis_result.get('key_concepts', [])[:50],
|
50 |
+
'concept_centrality': analysis_result.get('concept_centrality', {})
|
51 |
+
}
|
52 |
+
|
53 |
+
# 4. Manejo del gr谩fico
|
54 |
+
if 'concept_graph' in analysis_result and analysis_result['concept_graph']:
|
55 |
+
try:
|
56 |
+
if isinstance(analysis_result['concept_graph'], bytes):
|
57 |
+
analysis_document['concept_graph'] = base64.b64encode(
|
58 |
+
analysis_result['concept_graph']).decode('utf-8')
|
59 |
+
except Exception as e:
|
60 |
+
logger.error(f"Error procesando gr谩fico: {str(e)}")
|
61 |
+
|
62 |
+
# 5. Insertar documento
|
63 |
+
try:
|
64 |
+
result = collection.insert_one(analysis_document)
|
65 |
+
if result.inserted_id:
|
66 |
+
logger.info(f"An谩lisis guardado. ID: {result.inserted_id}")
|
67 |
+
return True
|
68 |
+
logger.error("Inserci贸n fallida - Sin ID devuelto")
|
69 |
+
return False
|
70 |
+
except PyMongoError as e:
|
71 |
+
logger.error(f"Error de MongoDB: {str(e)}")
|
72 |
+
return False
|
73 |
+
|
74 |
+
except Exception as e:
|
75 |
+
logger.error(f"Error inesperado: {str(e)}", exc_info=True)
|
76 |
+
return False
|
77 |
+
|
78 |
+
##########################################
|
79 |
+
##########################################
|
80 |
+
def get_student_semantic_live_analysis(username, limit=10):
|
81 |
+
"""
|
82 |
+
Versi贸n corregida sin usar projection
|
83 |
+
"""
|
84 |
+
try:
|
85 |
+
collection = get_collection(COLLECTION_NAME)
|
86 |
+
if collection is None:
|
87 |
+
logger.error("No se pudo obtener la colecci贸n")
|
88 |
+
return []
|
89 |
+
|
90 |
+
query = {"username": username, "analysis_type": "semantic_live"}
|
91 |
+
|
92 |
+
# Versi贸n alternativa sin projection
|
93 |
+
cursor = collection.find(query, {
|
94 |
+
"timestamp": 1,
|
95 |
+
"text": 1,
|
96 |
+
"key_concepts": 1,
|
97 |
+
"concept_graph": 1,
|
98 |
+
"_id": 1
|
99 |
+
}).sort("timestamp", -1).limit(limit)
|
100 |
+
|
101 |
+
results = list(cursor)
|
102 |
+
logger.info(f"Recuperados {len(results)} an谩lisis para {username}")
|
103 |
+
return results
|
104 |
+
|
105 |
+
except PyMongoError as e:
|
106 |
+
logger.error(f"Error de MongoDB: {str(e)}")
|
107 |
+
return []
|
108 |
+
except Exception as e:
|
109 |
+
logger.error(f"Error inesperado: {str(e)}")
|
110 |
+
return []
|
111 |
+
|
112 |
+
#######################################################
|
113 |
+
#######################################################
|
114 |
+
def update_student_semantic_live_analysis(analysis_id, update_data):
|
115 |
+
"""Actualiza un an谩lisis existente con manejo de errores"""
|
116 |
+
try:
|
117 |
+
query = {"_id": analysis_id}
|
118 |
+
update = {"$set": update_data}
|
119 |
+
return update_document(COLLECTION_NAME, query, update) > 0
|
120 |
+
except PyMongoError as e:
|
121 |
+
logger.error(f"Error al actualizar: {str(e)}")
|
122 |
+
return False
|
123 |
+
|
124 |
+
#######################################################
|
125 |
+
#######################################################
|
126 |
+
def delete_student_semantic_live_analysis(analysis_id):
|
127 |
+
"""Elimina un an谩lisis con manejo de errores"""
|
128 |
+
try:
|
129 |
+
query = {"_id": analysis_id}
|
130 |
+
return delete_document(COLLECTION_NAME, query) > 0
|
131 |
+
except PyMongoError as e:
|
132 |
+
logger.error(f"Error al eliminar: {str(e)}")
|
133 |
+
return False
|
134 |
+
|
135 |
+
#######################################################
|
136 |
+
#######################################################
|
137 |
+
def get_student_semantic_live_data(username):
|
138 |
+
"""
|
139 |
+
Obtiene todos los an谩lisis sem谩nticos en vivo de un estudiante.
|
140 |
+
Versi贸n corregida que usa la funci贸n _live.
|
141 |
+
"""
|
142 |
+
try:
|
143 |
+
analyses = get_student_semantic_live_analysis(username, limit=None)
|
144 |
+
|
145 |
+
formatted_analyses = []
|
146 |
+
for analysis in analyses:
|
147 |
+
formatted_analysis = {
|
148 |
+
'timestamp': analysis.get('timestamp'),
|
149 |
+
'text': analysis.get('text', ''),
|
150 |
+
'key_concepts': analysis.get('key_concepts', []),
|
151 |
+
'concept_graph': analysis.get('concept_graph')
|
152 |
+
}
|
153 |
+
formatted_analyses.append(formatted_analysis)
|
154 |
+
|
155 |
+
return {
|
156 |
+
'username': username,
|
157 |
+
'entries': formatted_analyses,
|
158 |
+
'count': len(formatted_analyses),
|
159 |
+
'status': 'success'
|
160 |
+
}
|
161 |
+
|
162 |
+
except Exception as e:
|
163 |
+
logger.error(f"Error al obtener datos: {str(e)}")
|
164 |
+
return {
|
165 |
+
'username': username,
|
166 |
+
'entries': [],
|
167 |
+
'count': 0,
|
168 |
+
'status': 'error',
|
169 |
+
'error': str(e)
|
170 |
+
}
|
171 |
+
|
172 |
+
|
173 |
+
#######################################################
|
174 |
+
#######################################################
|
175 |
+
|
176 |
+
__all__ = [
|
177 |
+
'store_student_semantic_live_result',
|
178 |
+
'get_student_semantic_live_analysis',
|
179 |
+
'update_student_semantic_live_analysis',
|
180 |
+
'delete_student_semantic_live_analysis',
|
181 |
+
'get_student_semantic_live_data'
|
182 |
+
]
|