File size: 6,311 Bytes
3657e14 dd8f18a c9030f8 3657e14 dd8f18a c9030f8 3657e14 7dc23a0 3657e14 7dc23a0 c78e82d 3657e14 c78e82d 7dc23a0 c78e82d 3657e14 c78e82d 7dc23a0 c9030f8 c78e82d 3657e14 c78e82d 3657e14 c78e82d 3657e14 c78e82d 7dc23a0 c78e82d 3657e14 c78e82d 7dc23a0 c78e82d 7dc23a0 c78e82d c9030f8 c78e82d c9030f8 7dc23a0 c9030f8 7dc23a0 c9030f8 dd8f18a c9030f8 3657e14 c78e82d 3657e14 7dc23a0 3657e14 c78e82d 3657e14 c78e82d 3657e14 c78e82d 3657e14 c78e82d dd8f18a 3657e14 dd8f18a c78e82d dd8f18a c78e82d dd8f18a c9030f8 c78e82d dd8f18a c9030f8 c78e82d dd8f18a c9030f8 c78e82d dd8f18a 3657e14 dd8f18a 3657e14 c78e82d 3657e14 dd8f18a 3657e14 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 180 181 182 |
# modules/database/semantic_mongo_live_db.py
import logging
import base64
from datetime import datetime, timezone
from pymongo.errors import PyMongoError
# Importaciones locales
from .mongo_db import (
get_collection,
insert_document,
find_documents,
update_document,
delete_document
)
# Configuraci贸n del logger
logger = logging.getLogger(__name__)
COLLECTION_NAME = 'student_semantic_live_analysis'
##########################################
##########################################
def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'):
"""
Versi贸n corregida con:
- Verificaci贸n correcta de colecci贸n
- Manejo de proyecci贸n alternativo
- Mejor manejo de errores
"""
try:
# 1. Obtener colecci贸n con verificaci贸n correcta
collection = get_collection(COLLECTION_NAME)
if collection is None: # Cambiado de 'if not collection'
logger.error(f"No se pudo obtener la colecci贸n {COLLECTION_NAME}")
return False
# 2. Validaci贸n de par谩metros
if not all([username, text, analysis_result]):
logger.error("Par谩metros incompletos para guardar an谩lisis")
return False
# 3. Preparar documento
analysis_document = {
'username': username,
'timestamp': datetime.now(timezone.utc),
'text': text[:50000],
'analysis_type': 'semantic_live',
'language': lang_code,
'key_concepts': analysis_result.get('key_concepts', [])[:50],
'concept_centrality': analysis_result.get('concept_centrality', {})
}
# 4. Manejo del gr谩fico
if 'concept_graph' in analysis_result and analysis_result['concept_graph']:
try:
if isinstance(analysis_result['concept_graph'], bytes):
analysis_document['concept_graph'] = base64.b64encode(
analysis_result['concept_graph']).decode('utf-8')
except Exception as e:
logger.error(f"Error procesando gr谩fico: {str(e)}")
# 5. Insertar documento
try:
result = collection.insert_one(analysis_document)
if result.inserted_id:
logger.info(f"An谩lisis guardado. ID: {result.inserted_id}")
return True
logger.error("Inserci贸n fallida - Sin ID devuelto")
return False
except PyMongoError as e:
logger.error(f"Error de MongoDB: {str(e)}")
return False
except Exception as e:
logger.error(f"Error inesperado: {str(e)}", exc_info=True)
return False
##########################################
##########################################
def get_student_semantic_live_analysis(username, limit=10):
"""
Versi贸n corregida sin usar projection
"""
try:
collection = get_collection(COLLECTION_NAME)
if collection is None:
logger.error("No se pudo obtener la colecci贸n")
return []
query = {"username": username, "analysis_type": "semantic_live"}
# Versi贸n alternativa sin projection
cursor = collection.find(query, {
"timestamp": 1,
"text": 1,
"key_concepts": 1,
"concept_graph": 1,
"_id": 1
}).sort("timestamp", -1).limit(limit)
results = list(cursor)
logger.info(f"Recuperados {len(results)} an谩lisis para {username}")
return results
except PyMongoError as e:
logger.error(f"Error de MongoDB: {str(e)}")
return []
except Exception as e:
logger.error(f"Error inesperado: {str(e)}")
return []
#######################################################
#######################################################
def update_student_semantic_live_analysis(analysis_id, update_data):
"""Actualiza un an谩lisis existente con manejo de errores"""
try:
query = {"_id": analysis_id}
update = {"$set": update_data}
return update_document(COLLECTION_NAME, query, update) > 0
except PyMongoError as e:
logger.error(f"Error al actualizar: {str(e)}")
return False
#######################################################
#######################################################
def delete_student_semantic_live_analysis(analysis_id):
"""Elimina un an谩lisis con manejo de errores"""
try:
query = {"_id": analysis_id}
return delete_document(COLLECTION_NAME, query) > 0
except PyMongoError as e:
logger.error(f"Error al eliminar: {str(e)}")
return False
#######################################################
#######################################################
def get_student_semantic_live_data(username):
"""
Obtiene todos los an谩lisis sem谩nticos en vivo de un estudiante.
Versi贸n corregida que usa la funci贸n _live.
"""
try:
analyses = get_student_semantic_live_analysis(username, limit=None)
formatted_analyses = []
for analysis in analyses:
formatted_analysis = {
'timestamp': analysis.get('timestamp'),
'text': analysis.get('text', ''),
'key_concepts': analysis.get('key_concepts', []),
'concept_graph': analysis.get('concept_graph')
}
formatted_analyses.append(formatted_analysis)
return {
'username': username,
'entries': formatted_analyses,
'count': len(formatted_analyses),
'status': 'success'
}
except Exception as e:
logger.error(f"Error al obtener datos: {str(e)}")
return {
'username': username,
'entries': [],
'count': 0,
'status': 'error',
'error': str(e)
}
#######################################################
#######################################################
__all__ = [
'store_student_semantic_live_result',
'get_student_semantic_live_analysis',
'update_student_semantic_live_analysis',
'delete_student_semantic_live_analysis',
'get_student_semantic_live_data'
] |