|
|
|
import logging |
|
from datetime import datetime, timezone |
|
import base64 |
|
|
|
|
|
from .mongo_db import get_collection, insert_document, find_documents |
|
|
|
logger = logging.getLogger(__name__) |
|
COLLECTION_NAME = 'student_semantic_live_analysis' |
|
|
|
def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'): |
|
""" |
|
Guarda el resultado del análisis semántico en vivo en MongoDB. |
|
""" |
|
try: |
|
if not username or not text or not analysis_result: |
|
logger.error("Datos insuficientes para guardar el análisis") |
|
return False |
|
|
|
|
|
concept_graph_data = None |
|
if 'concept_graph' in analysis_result and analysis_result['concept_graph'] is not None: |
|
try: |
|
if isinstance(analysis_result['concept_graph'], bytes): |
|
concept_graph_data = base64.b64encode(analysis_result['concept_graph']).decode('utf-8') |
|
else: |
|
logger.warning("El gráfico conceptual no está en formato bytes") |
|
except Exception as e: |
|
logger.error(f"Error al codificar gráfico conceptual: {str(e)}") |
|
|
|
|
|
analysis_document = { |
|
'username': username, |
|
'timestamp': datetime.now(timezone.utc), |
|
'text': text, |
|
'analysis_type': 'semantic_live', |
|
'key_concepts': analysis_result.get('key_concepts', []), |
|
'concept_centrality': analysis_result.get('concept_centrality', {}), |
|
'concept_graph': concept_graph_data, |
|
'language': lang_code |
|
} |
|
|
|
|
|
result = insert_document(COLLECTION_NAME, analysis_document) |
|
if result: |
|
logger.info(f"Análisis semántico en vivo guardado para {username}") |
|
return True |
|
|
|
logger.error("No se pudo insertar el documento en MongoDB") |
|
return False |
|
|
|
except Exception as e: |
|
logger.error(f"Error al guardar el análisis semántico en vivo: {str(e)}") |
|
return False |
|
|
|
def get_student_semantic_live_analysis(username, limit=10): |
|
""" |
|
Recupera los análisis semánticos en vivo de un estudiante. |
|
""" |
|
try: |
|
query = { |
|
"username": username, |
|
"analysis_type": "semantic_live" |
|
} |
|
|
|
projection = { |
|
"timestamp": 1, |
|
"text": 1, |
|
"key_concepts": 1, |
|
"concept_graph": 1, |
|
"_id": 1 |
|
} |
|
|
|
results = find_documents( |
|
COLLECTION_NAME, |
|
query, |
|
projection=projection, |
|
sort=[("timestamp", -1)], |
|
limit=limit |
|
) |
|
|
|
logger.info(f"Recuperados {len(results)} análisis semánticos en vivo para {username}") |
|
return results |
|
|
|
except Exception as e: |
|
logger.error(f"Error recuperando análisis semántico en vivo: {str(e)}") |
|
return [] |
|
|
|
__all__ = [ |
|
'store_student_semantic_live_result', |
|
'get_student_semantic_live_analysis' |
|
] |