Spaces:
Sleeping
Sleeping
Update modules/database/semantic_mongo_db.py
Browse files- modules/database/semantic_mongo_db.py +159 -159
modules/database/semantic_mongo_db.py
CHANGED
|
@@ -1,160 +1,160 @@
|
|
| 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 |
-
def store_student_semantic_result(username, text, analysis_result):
|
| 26 |
-
"""
|
| 27 |
-
Guarda el resultado del análisis semántico en MongoDB.
|
| 28 |
-
"""
|
| 29 |
-
try:
|
| 30 |
-
# El gráfico ya viene en bytes, solo necesitamos codificarlo a base64
|
| 31 |
-
concept_graph_data = None
|
| 32 |
-
if 'concept_graph' in analysis_result and analysis_result['concept_graph'] is not None:
|
| 33 |
-
try:
|
| 34 |
-
# Ya está en bytes, solo codificar a base64
|
| 35 |
-
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8')
|
| 36 |
-
except Exception as e:
|
| 37 |
-
logger.error(f"Error al codificar gráfico conceptual: {str(e)}")
|
| 38 |
-
|
| 39 |
-
# Crear documento para MongoDB
|
| 40 |
-
analysis_document = {
|
| 41 |
-
'username': username,
|
| 42 |
-
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 43 |
-
'text': text,
|
| 44 |
-
'analysis_type': 'semantic',
|
| 45 |
-
'key_concepts': analysis_result.get('key_concepts', []),
|
| 46 |
-
'concept_graph': concept_graph_data
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
# Insertar en MongoDB
|
| 50 |
-
result = insert_document(COLLECTION_NAME, analysis_document)
|
| 51 |
-
if result:
|
| 52 |
-
logger.info(f"Análisis semántico guardado con ID: {result} para el usuario: {username}")
|
| 53 |
-
return True
|
| 54 |
-
|
| 55 |
-
logger.error("No se pudo insertar el documento en MongoDB")
|
| 56 |
-
return False
|
| 57 |
-
|
| 58 |
-
except Exception as e:
|
| 59 |
-
logger.error(f"Error al guardar el análisis semántico: {str(e)}")
|
| 60 |
-
return False
|
| 61 |
-
|
| 62 |
-
####################################################################################
|
| 63 |
-
def get_student_semantic_analysis(username, limit=10):
|
| 64 |
-
"""
|
| 65 |
-
Recupera los análisis semánticos de un estudiante.
|
| 66 |
-
"""
|
| 67 |
-
try:
|
| 68 |
-
# Obtener la colección
|
| 69 |
-
collection = get_collection(COLLECTION_NAME)
|
| 70 |
-
if collection is None: # Cambiado de if not collection a if collection is None
|
| 71 |
-
logger.error("No se pudo obtener la colección semantic")
|
| 72 |
-
return []
|
| 73 |
-
|
| 74 |
-
# Consulta
|
| 75 |
-
query = {
|
| 76 |
-
"username": username,
|
| 77 |
-
"analysis_type": "semantic"
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
# Campos a recuperar
|
| 81 |
-
projection = {
|
| 82 |
-
"timestamp": 1,
|
| 83 |
-
"concept_graph": 1,
|
| 84 |
-
"_id": 1
|
| 85 |
-
}
|
| 86 |
-
|
| 87 |
-
# Ejecutar consulta
|
| 88 |
-
try:
|
| 89 |
-
cursor = collection.find(query, projection).sort("timestamp", -1)
|
| 90 |
-
if limit:
|
| 91 |
-
cursor = cursor.limit(limit)
|
| 92 |
-
|
| 93 |
-
# Convertir cursor a lista
|
| 94 |
-
results = list(cursor)
|
| 95 |
-
logger.info(f"Recuperados {len(results)} análisis semánticos para {username}")
|
| 96 |
-
return results
|
| 97 |
-
|
| 98 |
-
except Exception as db_error:
|
| 99 |
-
logger.error(f"Error en la consulta a MongoDB: {str(db_error)}")
|
| 100 |
-
return []
|
| 101 |
-
|
| 102 |
-
except Exception as e:
|
| 103 |
-
logger.error(f"Error recuperando análisis semántico: {str(e)}")
|
| 104 |
-
return []
|
| 105 |
-
####################################################################################################
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def update_student_semantic_analysis(analysis_id, update_data):
|
| 109 |
-
"""
|
| 110 |
-
Actualiza un análisis semántico existente.
|
| 111 |
-
Args:
|
| 112 |
-
analysis_id: ID del análisis a actualizar
|
| 113 |
-
update_data: Datos a actualizar
|
| 114 |
-
"""
|
| 115 |
-
query = {"_id": analysis_id}
|
| 116 |
-
update = {"$set": update_data}
|
| 117 |
-
return update_document(COLLECTION_NAME, query, update)
|
| 118 |
-
|
| 119 |
-
def delete_student_semantic_analysis(analysis_id):
|
| 120 |
-
"""
|
| 121 |
-
Elimina un análisis semántico.
|
| 122 |
-
Args:
|
| 123 |
-
analysis_id: ID del análisis a eliminar
|
| 124 |
-
"""
|
| 125 |
-
query = {"_id": analysis_id}
|
| 126 |
-
return delete_document(COLLECTION_NAME, query)
|
| 127 |
-
|
| 128 |
-
def get_student_semantic_data(username):
|
| 129 |
-
"""
|
| 130 |
-
Obtiene todos los análisis semánticos de un estudiante.
|
| 131 |
-
Args:
|
| 132 |
-
username: Nombre del usuario
|
| 133 |
-
Returns:
|
| 134 |
-
dict: Diccionario con todos los análisis del estudiante
|
| 135 |
-
"""
|
| 136 |
-
analyses = get_student_semantic_analysis(username, limit=None)
|
| 137 |
-
|
| 138 |
-
formatted_analyses = []
|
| 139 |
-
for analysis in analyses:
|
| 140 |
-
formatted_analysis = {
|
| 141 |
-
'timestamp': analysis['timestamp'],
|
| 142 |
-
'text': analysis['text'],
|
| 143 |
-
'key_concepts': analysis['key_concepts'],
|
| 144 |
-
'entities': analysis['entities']
|
| 145 |
-
# No incluimos los gráficos en el resumen general
|
| 146 |
-
}
|
| 147 |
-
formatted_analyses.append(formatted_analysis)
|
| 148 |
-
|
| 149 |
-
return {
|
| 150 |
-
'entries': formatted_analyses
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
# Exportar las funciones necesarias
|
| 154 |
-
__all__ = [
|
| 155 |
-
'store_student_semantic_result',
|
| 156 |
-
'get_student_semantic_analysis',
|
| 157 |
-
'update_student_semantic_analysis',
|
| 158 |
-
'delete_student_semantic_analysis',
|
| 159 |
-
'get_student_semantic_data'
|
| 160 |
]
|
|
|
|
| 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 |
+
def store_student_semantic_result(username, text, analysis_result):
|
| 26 |
+
"""
|
| 27 |
+
Guarda el resultado del análisis semántico en MongoDB.
|
| 28 |
+
"""
|
| 29 |
+
try:
|
| 30 |
+
# El gráfico ya viene en bytes, solo necesitamos codificarlo a base64
|
| 31 |
+
concept_graph_data = None
|
| 32 |
+
if 'concept_graph' in analysis_result and analysis_result['concept_graph'] is not None:
|
| 33 |
+
try:
|
| 34 |
+
# Ya está en bytes, solo codificar a base64
|
| 35 |
+
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8')
|
| 36 |
+
except Exception as e:
|
| 37 |
+
logger.error(f"Error al codificar gráfico conceptual: {str(e)}")
|
| 38 |
+
|
| 39 |
+
# Crear documento para MongoDB
|
| 40 |
+
analysis_document = {
|
| 41 |
+
'username': username,
|
| 42 |
+
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 43 |
+
'text': text,
|
| 44 |
+
'analysis_type': 'semantic',
|
| 45 |
+
'key_concepts': analysis_result.get('key_concepts', []),
|
| 46 |
+
'concept_graph': concept_graph_data
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Insertar en MongoDB
|
| 50 |
+
result = insert_document(COLLECTION_NAME, analysis_document)
|
| 51 |
+
if result:
|
| 52 |
+
logger.info(f"Análisis semántico guardado con ID: {result} para el usuario: {username}")
|
| 53 |
+
return True
|
| 54 |
+
|
| 55 |
+
logger.error("No se pudo insertar el documento en MongoDB")
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Error al guardar el análisis semántico: {str(e)}")
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
####################################################################################
|
| 63 |
+
def get_student_semantic_analysis(username, limit=10):
|
| 64 |
+
"""
|
| 65 |
+
Recupera los análisis semánticos de un estudiante.
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
# Obtener la colección
|
| 69 |
+
collection = get_collection(COLLECTION_NAME)
|
| 70 |
+
if collection is None: # Cambiado de if not collection a if collection is None
|
| 71 |
+
logger.error("No se pudo obtener la colección semantic")
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
# Consulta
|
| 75 |
+
query = {
|
| 76 |
+
"username": username,
|
| 77 |
+
"analysis_type": "semantic"
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
# Campos a recuperar
|
| 81 |
+
projection = {
|
| 82 |
+
"timestamp": 1,
|
| 83 |
+
"concept_graph": 1,
|
| 84 |
+
"_id": 1
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
# Ejecutar consulta
|
| 88 |
+
try:
|
| 89 |
+
cursor = collection.find(query, projection).sort("timestamp", -1)
|
| 90 |
+
if limit:
|
| 91 |
+
cursor = cursor.limit(limit)
|
| 92 |
+
|
| 93 |
+
# Convertir cursor a lista
|
| 94 |
+
results = list(cursor)
|
| 95 |
+
logger.info(f"Recuperados {len(results)} análisis semánticos para {username}")
|
| 96 |
+
return results
|
| 97 |
+
|
| 98 |
+
except Exception as db_error:
|
| 99 |
+
logger.error(f"Error en la consulta a MongoDB: {str(db_error)}")
|
| 100 |
+
return []
|
| 101 |
+
|
| 102 |
+
except Exception as e:
|
| 103 |
+
logger.error(f"Error recuperando análisis semántico: {str(e)}")
|
| 104 |
+
return []
|
| 105 |
+
####################################################################################################
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def update_student_semantic_analysis(analysis_id, update_data):
|
| 109 |
+
"""
|
| 110 |
+
Actualiza un análisis semántico existente.
|
| 111 |
+
Args:
|
| 112 |
+
analysis_id: ID del análisis a actualizar
|
| 113 |
+
update_data: Datos a actualizar
|
| 114 |
+
"""
|
| 115 |
+
query = {"_id": analysis_id}
|
| 116 |
+
update = {"$set": update_data}
|
| 117 |
+
return update_document(COLLECTION_NAME, query, update)
|
| 118 |
+
|
| 119 |
+
def delete_student_semantic_analysis(analysis_id):
|
| 120 |
+
"""
|
| 121 |
+
Elimina un análisis semántico.
|
| 122 |
+
Args:
|
| 123 |
+
analysis_id: ID del análisis a eliminar
|
| 124 |
+
"""
|
| 125 |
+
query = {"_id": analysis_id}
|
| 126 |
+
return delete_document(COLLECTION_NAME, query)
|
| 127 |
+
|
| 128 |
+
def get_student_semantic_data(username):
|
| 129 |
+
"""
|
| 130 |
+
Obtiene todos los análisis semánticos de un estudiante.
|
| 131 |
+
Args:
|
| 132 |
+
username: Nombre del usuario
|
| 133 |
+
Returns:
|
| 134 |
+
dict: Diccionario con todos los análisis del estudiante
|
| 135 |
+
"""
|
| 136 |
+
analyses = get_student_semantic_analysis(username, limit=None)
|
| 137 |
+
|
| 138 |
+
formatted_analyses = []
|
| 139 |
+
for analysis in analyses:
|
| 140 |
+
formatted_analysis = {
|
| 141 |
+
'timestamp': analysis['timestamp'],
|
| 142 |
+
'text': analysis['text'],
|
| 143 |
+
'key_concepts': analysis['key_concepts'],
|
| 144 |
+
'entities': analysis['entities']
|
| 145 |
+
# No incluimos los gráficos en el resumen general
|
| 146 |
+
}
|
| 147 |
+
formatted_analyses.append(formatted_analysis)
|
| 148 |
+
|
| 149 |
+
return {
|
| 150 |
+
'entries': formatted_analyses
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
# Exportar las funciones necesarias
|
| 154 |
+
__all__ = [
|
| 155 |
+
'store_student_semantic_result',
|
| 156 |
+
'get_student_semantic_analysis',
|
| 157 |
+
'update_student_semantic_analysis',
|
| 158 |
+
'delete_student_semantic_analysis',
|
| 159 |
+
'get_student_semantic_data'
|
| 160 |
]
|