Spaces:
Running
Running
| # modules/database/discourse_mongo_db.py | |
| # Importaciones estándar | |
| import io | |
| import base64 | |
| from datetime import datetime, timezone | |
| import logging | |
| # Importaciones de terceros | |
| import matplotlib.pyplot as plt | |
| 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_discourse_analysis' | |
| ######################################################################## | |
| def store_student_discourse_result(username, text1, text2, analysis_result): | |
| """ | |
| Guarda el resultado del análisis de discurso comparativo en MongoDB. | |
| """ | |
| try: | |
| # Los gráficos ya vienen en bytes, solo necesitamos codificar a base64 | |
| graph1_data = None | |
| graph2_data = None | |
| combined_graph_data = None | |
| if 'graph1' in analysis_result and analysis_result['graph1'] is not None: | |
| try: | |
| graph1_data = base64.b64encode(analysis_result['graph1']).decode('utf-8') | |
| except Exception as e: | |
| logger.error(f"Error al codificar gráfico 1: {str(e)}") | |
| if 'graph2' in analysis_result and analysis_result['graph2'] is not None: | |
| try: | |
| graph2_data = base64.b64encode(analysis_result['graph2']).decode('utf-8') | |
| except Exception as e: | |
| logger.error(f"Error al codificar gráfico 2: {str(e)}") | |
| if 'combined_graph' in analysis_result and analysis_result['combined_graph'] is not None: | |
| try: | |
| combined_graph_data = base64.b64encode(analysis_result['combined_graph']).decode('utf-8') | |
| except Exception as e: | |
| logger.error(f"Error al codificar gráfico combinado: {str(e)}") | |
| # Crear documento para MongoDB | |
| analysis_document = { | |
| 'username': username, | |
| 'timestamp': datetime.now(timezone.utc).isoformat(), | |
| 'text1': text1, | |
| 'text2': text2, | |
| 'analysis_type': 'discourse', | |
| 'key_concepts1': analysis_result.get('key_concepts1', []), | |
| 'key_concepts2': analysis_result.get('key_concepts2', []), | |
| 'graph1': graph1_data, | |
| 'graph2': graph2_data, | |
| 'combined_graph': combined_graph_data | |
| } | |
| # Insertar en MongoDB | |
| result = insert_document(COLLECTION_NAME, analysis_document) | |
| if result: | |
| logger.info(f"Análisis del discurso guardado con ID: {result} para el usuario: {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 del discurso: {str(e)}") | |
| return False | |
| ################################################################################# | |
| def get_student_discourse_analysis(username, limit=10): | |
| """ | |
| Recupera los análisis del discurso de un estudiante. | |
| """ | |
| try: | |
| # Obtener la colección | |
| collection = get_collection(COLLECTION_NAME) | |
| if collection is None: # Cambiado de if not collection a if collection is None | |
| logger.error("No se pudo obtener la colección discourse") | |
| return [] | |
| # Consulta | |
| query = { | |
| "username": username, | |
| "analysis_type": "discourse" | |
| } | |
| # Campos a recuperar | |
| projection = { | |
| "timestamp": 1, | |
| "combined_graph": 1, | |
| "_id": 1 | |
| } | |
| # Ejecutar consulta | |
| try: | |
| cursor = collection.find(query, projection).sort("timestamp", -1) | |
| if limit: | |
| cursor = cursor.limit(limit) | |
| # Convertir cursor a lista | |
| results = list(cursor) | |
| logger.info(f"Recuperados {len(results)} análisis del discurso para {username}") | |
| return results | |
| except Exception as db_error: | |
| logger.error(f"Error en la consulta a MongoDB: {str(db_error)}") | |
| return [] | |
| except Exception as e: | |
| logger.error(f"Error recuperando análisis del discurso: {str(e)}") | |
| return [] | |
| ##################################################################################### | |
| def get_student_discourse_data(username): | |
| """ | |
| Obtiene un resumen de los análisis del discurso de un estudiante. | |
| """ | |
| try: | |
| analyses = get_student_discourse_analysis(username, limit=None) | |
| formatted_analyses = [] | |
| for analysis in analyses: | |
| formatted_analysis = { | |
| 'timestamp': analysis['timestamp'], | |
| 'text1': analysis.get('text1', ''), | |
| 'text2': analysis.get('text2', ''), | |
| 'key_concepts1': analysis.get('key_concepts1', []), | |
| 'key_concepts2': analysis.get('key_concepts2', []) | |
| } | |
| formatted_analyses.append(formatted_analysis) | |
| return {'entries': formatted_analyses} | |
| except Exception as e: | |
| logger.error(f"Error al obtener datos del discurso: {str(e)}") | |
| return {'entries': []} | |
| ########################################################################### | |
| def update_student_discourse_analysis(analysis_id, update_data): | |
| """ | |
| Actualiza un análisis del discurso existente. | |
| """ | |
| try: | |
| query = {"_id": analysis_id} | |
| update = {"$set": update_data} | |
| return update_document(COLLECTION_NAME, query, update) | |
| except Exception as e: | |
| logger.error(f"Error al actualizar análisis del discurso: {str(e)}") | |
| return False | |
| ########################################################################### | |
| def delete_student_discourse_analysis(analysis_id): | |
| """ | |
| Elimina un análisis del discurso. | |
| """ | |
| try: | |
| query = {"_id": analysis_id} | |
| return delete_document(COLLECTION_NAME, query) | |
| except Exception as e: | |
| logger.error(f"Error al eliminar análisis del discurso: {str(e)}") | |
| return False |