Update modules/database/semantic_mongo_db.py
Browse files- modules/database/semantic_mongo_db.py +196 -178
modules/database/semantic_mongo_db.py
CHANGED
|
@@ -1,179 +1,197 @@
|
|
| 1 |
-
#/modules/database/semantic_mongo_db.py
|
| 2 |
-
|
| 3 |
-
# Importaciones estándar
|
| 4 |
-
import io
|
| 5 |
-
import base64
|
| 6 |
-
from datetime import datetime, timezone
|
| 7 |
-
import logging
|
| 8 |
-
|
| 9 |
-
# Importaciones de terceros
|
| 10 |
-
import matplotlib.pyplot as plt
|
| 11 |
-
|
| 12 |
-
# Importaciones locales
|
| 13 |
-
from .mongo_db import (
|
| 14 |
-
get_collection,
|
| 15 |
-
insert_document,
|
| 16 |
-
find_documents,
|
| 17 |
-
update_document,
|
| 18 |
-
delete_document
|
| 19 |
-
)
|
| 20 |
-
|
| 21 |
-
# Configuración del logger
|
| 22 |
-
logger = logging.getLogger(__name__) # Cambiado de name a __name__
|
| 23 |
-
COLLECTION_NAME = 'student_semantic_analysis'
|
| 24 |
-
|
| 25 |
-
####################################################################
|
| 26 |
-
# modules/database/semantic_mongo_db.py
|
| 27 |
-
|
| 28 |
-
# modules/database/semantic_mongo_db.py
|
| 29 |
-
|
| 30 |
-
def store_student_semantic_result(username, text, analysis_result, lang_code='en'):
|
| 31 |
-
"""
|
| 32 |
-
Guarda el resultado del análisis semántico en MongoDB.
|
| 33 |
-
Args:
|
| 34 |
-
username: Nombre del usuario
|
| 35 |
-
text: Texto completo analizado
|
| 36 |
-
analysis_result: Diccionario con los resultados del análisis
|
| 37 |
-
lang_code: Código de idioma (opcional, default 'en')
|
| 38 |
-
"""
|
| 39 |
-
try:
|
| 40 |
-
# Verificar datos mínimos requeridos
|
| 41 |
-
if not username or not text or not analysis_result:
|
| 42 |
-
logger.error("Datos insuficientes para guardar el análisis")
|
| 43 |
-
return False
|
| 44 |
-
|
| 45 |
-
# Preparar el gráfico conceptual
|
| 46 |
-
concept_graph_data = None
|
| 47 |
-
if 'concept_graph' in analysis_result and analysis_result['concept_graph'] is not None:
|
| 48 |
-
try:
|
| 49 |
-
if isinstance(analysis_result['concept_graph'], bytes):
|
| 50 |
-
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8')
|
| 51 |
-
else:
|
| 52 |
-
logger.warning("El gráfico conceptual no está en formato bytes")
|
| 53 |
-
except Exception as e:
|
| 54 |
-
logger.error(f"Error al codificar gráfico conceptual: {str(e)}")
|
| 55 |
-
|
| 56 |
-
# Crear documento para MongoDB
|
| 57 |
-
analysis_document = {
|
| 58 |
-
'username': username,
|
| 59 |
-
'timestamp': datetime.now(timezone.utc),
|
| 60 |
-
'text': text,
|
| 61 |
-
'analysis_type': 'semantic',
|
| 62 |
-
'key_concepts': analysis_result.get('key_concepts', []),
|
| 63 |
-
'concept_centrality': analysis_result.get('concept_centrality', {}),
|
| 64 |
-
'concept_graph': concept_graph_data,
|
| 65 |
-
'language': lang_code # Usamos el parámetro directamente
|
| 66 |
-
}
|
| 67 |
-
|
| 68 |
-
# Insertar en MongoDB
|
| 69 |
-
result = insert_document(COLLECTION_NAME, analysis_document)
|
| 70 |
-
if result:
|
| 71 |
-
logger.info(f"Análisis semántico guardado para {username}")
|
| 72 |
-
return True
|
| 73 |
-
|
| 74 |
-
logger.error("No se pudo insertar el documento en MongoDB")
|
| 75 |
-
return False
|
| 76 |
-
|
| 77 |
-
except Exception as e:
|
| 78 |
-
logger.error(f"Error al guardar el análisis semántico: {str(e)}", exc_info=True)
|
| 79 |
-
return False
|
| 80 |
-
|
| 81 |
-
####################################################################################
|
| 82 |
-
def get_student_semantic_analysis(username, limit=10):
|
| 83 |
-
"""
|
| 84 |
-
Recupera los análisis semánticos de un estudiante.
|
| 85 |
-
"""
|
| 86 |
-
try:
|
| 87 |
-
|
| 88 |
-
collection
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
"
|
| 102 |
-
"
|
| 103 |
-
"
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
try:
|
| 108 |
-
cursor = collection.find(query, projection).sort("timestamp", -1)
|
| 109 |
-
if limit:
|
| 110 |
-
cursor = cursor.limit(limit)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
results
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
""
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
]
|
|
|
|
| 1 |
+
#/modules/database/semantic_mongo_db.py
|
| 2 |
+
|
| 3 |
+
# Importaciones estándar
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
# Importaciones de terceros
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
|
| 12 |
+
# Importaciones locales
|
| 13 |
+
from .mongo_db import (
|
| 14 |
+
get_collection,
|
| 15 |
+
insert_document,
|
| 16 |
+
find_documents,
|
| 17 |
+
update_document,
|
| 18 |
+
delete_document
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Configuración del logger
|
| 22 |
+
logger = logging.getLogger(__name__) # Cambiado de name a __name__
|
| 23 |
+
COLLECTION_NAME = 'student_semantic_analysis'
|
| 24 |
+
|
| 25 |
+
####################################################################
|
| 26 |
+
# modules/database/semantic_mongo_db.py
|
| 27 |
+
|
| 28 |
+
# modules/database/semantic_mongo_db.py
|
| 29 |
+
|
| 30 |
+
def store_student_semantic_result(username, text, analysis_result, lang_code='en'):
|
| 31 |
+
"""
|
| 32 |
+
Guarda el resultado del análisis semántico en MongoDB.
|
| 33 |
+
Args:
|
| 34 |
+
username: Nombre del usuario
|
| 35 |
+
text: Texto completo analizado
|
| 36 |
+
analysis_result: Diccionario con los resultados del análisis
|
| 37 |
+
lang_code: Código de idioma (opcional, default 'en')
|
| 38 |
+
"""
|
| 39 |
+
try:
|
| 40 |
+
# Verificar datos mínimos requeridos
|
| 41 |
+
if not username or not text or not analysis_result:
|
| 42 |
+
logger.error("Datos insuficientes para guardar el análisis")
|
| 43 |
+
return False
|
| 44 |
+
|
| 45 |
+
# Preparar el gráfico conceptual
|
| 46 |
+
concept_graph_data = None
|
| 47 |
+
if 'concept_graph' in analysis_result and analysis_result['concept_graph'] is not None:
|
| 48 |
+
try:
|
| 49 |
+
if isinstance(analysis_result['concept_graph'], bytes):
|
| 50 |
+
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8')
|
| 51 |
+
else:
|
| 52 |
+
logger.warning("El gráfico conceptual no está en formato bytes")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error(f"Error al codificar gráfico conceptual: {str(e)}")
|
| 55 |
+
|
| 56 |
+
# Crear documento para MongoDB
|
| 57 |
+
analysis_document = {
|
| 58 |
+
'username': username,
|
| 59 |
+
'timestamp': datetime.now(timezone.utc),
|
| 60 |
+
'text': text,
|
| 61 |
+
'analysis_type': 'semantic',
|
| 62 |
+
'key_concepts': analysis_result.get('key_concepts', []),
|
| 63 |
+
'concept_centrality': analysis_result.get('concept_centrality', {}),
|
| 64 |
+
'concept_graph': concept_graph_data,
|
| 65 |
+
'language': lang_code # Usamos el parámetro directamente
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# Insertar en MongoDB
|
| 69 |
+
result = insert_document(COLLECTION_NAME, analysis_document)
|
| 70 |
+
if result:
|
| 71 |
+
logger.info(f"Análisis semántico guardado para {username}")
|
| 72 |
+
return True
|
| 73 |
+
|
| 74 |
+
logger.error("No se pudo insertar el documento en MongoDB")
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.error(f"Error al guardar el análisis semántico: {str(e)}", exc_info=True)
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
####################################################################################
|
| 82 |
+
def get_student_semantic_analysis(username, limit=10):
|
| 83 |
+
"""
|
| 84 |
+
Recupera los análisis semánticos de un estudiante.
|
| 85 |
+
"""
|
| 86 |
+
try:
|
| 87 |
+
collection = get_collection(COLLECTION_NAME)
|
| 88 |
+
if collection is None:
|
| 89 |
+
logger.error("No se pudo obtener la colección semantic")
|
| 90 |
+
return []
|
| 91 |
+
|
| 92 |
+
query = {
|
| 93 |
+
"username": username,
|
| 94 |
+
"analysis_type": "semantic"
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
# Actualizar la proyección para incluir todos los campos necesarios
|
| 98 |
+
projection = {
|
| 99 |
+
"timestamp": 1,
|
| 100 |
+
"text": 1, # Añadir este campo
|
| 101 |
+
"key_concepts": 1, # Añadir este campo
|
| 102 |
+
"entities": 1, # Añadir este campo
|
| 103 |
+
"concept_graph": 1,
|
| 104 |
+
"_id": 1
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
cursor = collection.find(query, projection).sort("timestamp", -1)
|
| 109 |
+
if limit:
|
| 110 |
+
cursor = cursor.limit(limit)
|
| 111 |
+
|
| 112 |
+
results = list(cursor)
|
| 113 |
+
logger.info(f"Recuperados {len(results)} análisis semánticos para {username}")
|
| 114 |
+
return results
|
| 115 |
+
|
| 116 |
+
except Exception as db_error:
|
| 117 |
+
logger.error(f"Error en la consulta a MongoDB: {str(db_error)}")
|
| 118 |
+
return []
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
logger.error(f"Error recuperando análisis semántico: {str(e)}")
|
| 122 |
+
return []
|
| 123 |
+
####################################################################################################
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def update_student_semantic_analysis(analysis_id, update_data):
|
| 127 |
+
"""
|
| 128 |
+
Actualiza un análisis semántico existente.
|
| 129 |
+
Args:
|
| 130 |
+
analysis_id: ID del análisis a actualizar
|
| 131 |
+
update_data: Datos a actualizar
|
| 132 |
+
"""
|
| 133 |
+
query = {"_id": analysis_id}
|
| 134 |
+
update = {"$set": update_data}
|
| 135 |
+
return update_document(COLLECTION_NAME, query, update)
|
| 136 |
+
|
| 137 |
+
def delete_student_semantic_analysis(analysis_id):
|
| 138 |
+
"""
|
| 139 |
+
Elimina un análisis semántico.
|
| 140 |
+
Args:
|
| 141 |
+
analysis_id: ID del análisis a eliminar
|
| 142 |
+
"""
|
| 143 |
+
query = {"_id": analysis_id}
|
| 144 |
+
return delete_document(COLLECTION_NAME, query)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
############################################################################
|
| 148 |
+
def get_student_semantic_data(username):
|
| 149 |
+
"""
|
| 150 |
+
Obtiene todos los análisis semánticos de un estudiante.
|
| 151 |
+
Args:
|
| 152 |
+
username: Nombre del usuario
|
| 153 |
+
Returns:
|
| 154 |
+
dict: Diccionario con todos los análisis del estudiante
|
| 155 |
+
"""
|
| 156 |
+
try:
|
| 157 |
+
analyses = get_student_semantic_analysis(username, limit=None)
|
| 158 |
+
|
| 159 |
+
formatted_analyses = []
|
| 160 |
+
for analysis in analyses:
|
| 161 |
+
# Asegurarse de que los campos existan antes de acceder a ellos
|
| 162 |
+
formatted_analysis = {
|
| 163 |
+
'timestamp': analysis.get('timestamp'),
|
| 164 |
+
'text': analysis.get('text', ''), # Usar get() con valor por defecto
|
| 165 |
+
'key_concepts': analysis.get('key_concepts', []),
|
| 166 |
+
'entities': analysis.get('entities', []),
|
| 167 |
+
'concept_graph': analysis.get('concept_graph') # Mantener el gráfico
|
| 168 |
+
}
|
| 169 |
+
formatted_analyses.append(formatted_analysis)
|
| 170 |
+
|
| 171 |
+
return {
|
| 172 |
+
'username': username,
|
| 173 |
+
'entries': formatted_analyses,
|
| 174 |
+
'count': len(formatted_analyses),
|
| 175 |
+
'status': 'success'
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
except Exception as e:
|
| 179 |
+
logger.error(f"Error al obtener datos semánticos para {username}: {str(e)}")
|
| 180 |
+
return {
|
| 181 |
+
'username': username,
|
| 182 |
+
'entries': [],
|
| 183 |
+
'count': 0,
|
| 184 |
+
'status': 'error',
|
| 185 |
+
'error': str(e)
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
##########################################################################
|
| 190 |
+
# Exportar las funciones necesarias
|
| 191 |
+
__all__ = [
|
| 192 |
+
'store_student_semantic_result',
|
| 193 |
+
'get_student_semantic_analysis',
|
| 194 |
+
'update_student_semantic_analysis',
|
| 195 |
+
'delete_student_semantic_analysis',
|
| 196 |
+
'get_student_semantic_data'
|
| 197 |
]
|