Update modules/database/semantic_mongo_live_db.py
Browse files
modules/database/semantic_mongo_live_db.py
CHANGED
@@ -17,71 +17,74 @@ from .mongo_db import (
|
|
17 |
logger = logging.getLogger(__name__)
|
18 |
COLLECTION_NAME = 'student_semantic_live_analysis'
|
19 |
|
|
|
|
|
|
|
20 |
def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'):
|
21 |
"""
|
22 |
-
|
23 |
-
|
|
|
|
|
24 |
"""
|
25 |
try:
|
26 |
-
#
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
if not text or not isinstance(text, str):
|
32 |
-
logger.error("Texto de análisis inválido")
|
33 |
return False
|
34 |
|
35 |
-
|
36 |
-
|
|
|
37 |
return False
|
38 |
|
39 |
-
#
|
40 |
-
concept_graph_data = None
|
41 |
-
if 'concept_graph' in analysis_result and analysis_result['concept_graph']:
|
42 |
-
try:
|
43 |
-
if isinstance(analysis_result['concept_graph'], bytes):
|
44 |
-
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8')
|
45 |
-
elif isinstance(analysis_result['concept_graph'], str):
|
46 |
-
# Verificar si ya está en base64
|
47 |
-
concept_graph_data = analysis_result['concept_graph']
|
48 |
-
except Exception as e:
|
49 |
-
logger.error(f"Error al procesar gráfico: {str(e)}")
|
50 |
-
|
51 |
-
# Crear documento con campos validados
|
52 |
analysis_document = {
|
53 |
-
'username': username,
|
54 |
'timestamp': datetime.now(timezone.utc),
|
55 |
-
'text': text[:50000], # Limitar tamaño
|
56 |
'analysis_type': 'semantic_live',
|
57 |
-
'language': lang_code,
|
58 |
-
'key_concepts': analysis_result.get('key_concepts', [])[:50],
|
59 |
'concept_centrality': analysis_result.get('concept_centrality', {}),
|
60 |
'metadata': {
|
61 |
-
'version': '1.
|
62 |
-
'source': '
|
63 |
}
|
64 |
}
|
65 |
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
#
|
70 |
try:
|
71 |
-
result =
|
72 |
-
if result:
|
73 |
-
logger.info(f"Análisis
|
74 |
return True
|
75 |
-
|
|
|
76 |
return False
|
|
|
77 |
except PyMongoError as e:
|
78 |
logger.error(f"Error de MongoDB: {str(e)}")
|
79 |
return False
|
80 |
|
81 |
except Exception as e:
|
82 |
-
logger.error(f"Error
|
83 |
return False
|
84 |
|
|
|
|
|
85 |
def get_student_semantic_live_analysis(username, limit=10):
|
86 |
"""
|
87 |
Recupera los análisis semánticos en vivo de un estudiante.
|
|
|
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 |
+
- Mejor verificación de colección
|
27 |
+
- Logs más detallados
|
28 |
+
- Validación de inserción mejorada
|
29 |
"""
|
30 |
try:
|
31 |
+
# 1. Verificación de colección
|
32 |
+
collection = get_collection(COLLECTION_NAME)
|
33 |
+
if not collection:
|
34 |
+
logger.error(f"No se pudo acceder a la colección {COLLECTION_NAME}")
|
|
|
|
|
|
|
35 |
return False
|
36 |
|
37 |
+
# 2. Validación de parámetros extendida
|
38 |
+
if not all([username, text, analysis_result]):
|
39 |
+
logger.error("Parámetros incompletos para guardar análisis")
|
40 |
return False
|
41 |
|
42 |
+
# 3. Preparación del documento con más logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
analysis_document = {
|
44 |
+
'username': str(username),
|
45 |
'timestamp': datetime.now(timezone.utc),
|
46 |
+
'text': str(text)[:50000], # Limitar tamaño
|
47 |
'analysis_type': 'semantic_live',
|
48 |
+
'language': str(lang_code),
|
49 |
+
'key_concepts': analysis_result.get('key_concepts', [])[:50],
|
50 |
'concept_centrality': analysis_result.get('concept_centrality', {}),
|
51 |
'metadata': {
|
52 |
+
'version': '1.1',
|
53 |
+
'source': 'live_interface_v2'
|
54 |
}
|
55 |
}
|
56 |
|
57 |
+
# 4. Manejo del gráfico con más controles
|
58 |
+
if 'concept_graph' in analysis_result:
|
59 |
+
try:
|
60 |
+
graph_data = analysis_result['concept_graph']
|
61 |
+
if isinstance(graph_data, bytes):
|
62 |
+
analysis_document['concept_graph'] = base64.b64encode(graph_data).decode('utf-8')
|
63 |
+
elif isinstance(graph_data, str) and graph_data:
|
64 |
+
analysis_document['concept_graph'] = graph_data
|
65 |
+
except Exception as e:
|
66 |
+
logger.warning(f"Error procesando gráfico: {str(e)}")
|
67 |
|
68 |
+
# 5. Inserción con verificación explícita
|
69 |
try:
|
70 |
+
result = collection.insert_one(analysis_document)
|
71 |
+
if result.inserted_id:
|
72 |
+
logger.info(f"Análisis guardado. ID: {result.inserted_id}")
|
73 |
return True
|
74 |
+
|
75 |
+
logger.error("Inserción fallida - Sin ID devuelto")
|
76 |
return False
|
77 |
+
|
78 |
except PyMongoError as e:
|
79 |
logger.error(f"Error de MongoDB: {str(e)}")
|
80 |
return False
|
81 |
|
82 |
except Exception as e:
|
83 |
+
logger.error(f"Error crítico: {str(e)}", exc_info=True)
|
84 |
return False
|
85 |
|
86 |
+
##########################################
|
87 |
+
##########################################
|
88 |
def get_student_semantic_live_analysis(username, limit=10):
|
89 |
"""
|
90 |
Recupera los análisis semánticos en vivo de un estudiante.
|