Update modules/database/discourse_mongo_db.py
Browse files
modules/database/discourse_mongo_db.py
CHANGED
@@ -21,68 +21,50 @@ logger = logging.getLogger(__name__)
|
|
21 |
COLLECTION_NAME = 'student_discourse_analysis'
|
22 |
|
23 |
########################################################################
|
|
|
24 |
def store_student_discourse_result(username, text1, text2, analysis_result):
|
25 |
"""
|
26 |
Guarda el resultado del análisis de discurso en MongoDB.
|
27 |
-
Los gráficos ya deben venir en formato bytes.
|
28 |
"""
|
29 |
try:
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
# Codificar graph1 si existe
|
38 |
-
if 'graph1' in analysis_result and analysis_result['graph1'] is not None:
|
39 |
-
try:
|
40 |
-
graph1_data = base64.b64encode(analysis_result['graph1']).decode('utf-8')
|
41 |
-
logger.info(f"Graph1 codificado en base64 ({len(graph1_data)} caracteres)")
|
42 |
-
except Exception as e:
|
43 |
-
logger.error(f"Error al codificar gráfico 1: {str(e)}")
|
44 |
-
|
45 |
-
# Codificar graph2 si existe
|
46 |
-
if 'graph2' in analysis_result and analysis_result['graph2'] is not None:
|
47 |
-
try:
|
48 |
-
graph2_data = base64.b64encode(analysis_result['graph2']).decode('utf-8')
|
49 |
-
logger.info(f"Graph2 codificado en base64 ({len(graph2_data)} caracteres)")
|
50 |
-
except Exception as e:
|
51 |
-
logger.error(f"Error al codificar gráfico 2: {str(e)}")
|
52 |
-
|
53 |
-
# Codificar combined_graph si existe
|
54 |
-
if 'combined_graph' in analysis_result and analysis_result['combined_graph'] is not None:
|
55 |
-
try:
|
56 |
-
combined_graph_data = base64.b64encode(analysis_result['combined_graph']).decode('utf-8')
|
57 |
-
logger.info(f"Combined_graph codificado en base64 ({len(combined_graph_data)} caracteres)")
|
58 |
-
except Exception as e:
|
59 |
-
logger.error(f"Error al codificar gráfico combinado: {str(e)}")
|
60 |
-
|
61 |
-
# Crear documento para MongoDB
|
62 |
-
analysis_document = {
|
63 |
'username': username,
|
64 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
65 |
'text1': text1,
|
66 |
'text2': text2,
|
67 |
-
'analysis_type': 'discourse',
|
68 |
'key_concepts1': analysis_result.get('key_concepts1', []),
|
69 |
-
'key_concepts2': analysis_result.get('key_concepts2', [])
|
70 |
-
'graph1': graph1_data,
|
71 |
-
'graph2': graph2_data,
|
72 |
-
'combined_graph': combined_graph_data
|
73 |
}
|
74 |
-
|
75 |
-
#
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
except Exception as e:
|
85 |
-
logger.error(f"Error
|
86 |
return False
|
87 |
|
88 |
#################################################################################
|
@@ -94,59 +76,30 @@ def get_student_discourse_analysis(username, limit=10):
|
|
94 |
Recupera los análisis del discurso de un estudiante.
|
95 |
"""
|
96 |
try:
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
logger.error("No se pudo obtener la colección discourse")
|
101 |
return []
|
102 |
-
|
103 |
-
# Consulta
|
104 |
-
query = {
|
105 |
-
"username": username,
|
106 |
-
"analysis_type": "discourse"
|
107 |
-
}
|
108 |
-
|
109 |
-
# NO usar projection - recuperar todos los campos
|
110 |
-
|
111 |
-
# Ejecutar consulta
|
112 |
-
cursor = collection.find(query).sort("timestamp", -1)
|
113 |
-
if limit:
|
114 |
-
cursor = cursor.limit(limit)
|
115 |
-
|
116 |
-
# Convertir cursor a lista
|
117 |
-
results = list(cursor)
|
118 |
-
logger.info(f"Recuperados {len(results)} análisis del discurso para {username}")
|
119 |
-
|
120 |
-
# Decodificar gráficos de base64 a bytes para su uso en la aplicación
|
121 |
-
for result in results:
|
122 |
-
# Decodificar graph1
|
123 |
-
if 'graph1' in result and result['graph1']:
|
124 |
-
try:
|
125 |
-
result['graph1'] = base64.b64decode(result['graph1'])
|
126 |
-
except Exception as e:
|
127 |
-
logger.error(f"Error decodificando graph1: {str(e)}")
|
128 |
-
result['graph1'] = None
|
129 |
-
|
130 |
-
# Decodificar graph2
|
131 |
-
if 'graph2' in result and result['graph2']:
|
132 |
-
try:
|
133 |
-
result['graph2'] = base64.b64decode(result['graph2'])
|
134 |
-
except Exception as e:
|
135 |
-
logger.error(f"Error decodificando graph2: {str(e)}")
|
136 |
-
result['graph2'] = None
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
-
return results
|
147 |
-
|
148 |
except Exception as e:
|
149 |
-
logger.error(f"Error recuperando análisis
|
150 |
return []
|
151 |
|
152 |
#####################################################################################
|
|
|
21 |
COLLECTION_NAME = 'student_discourse_analysis'
|
22 |
|
23 |
########################################################################
|
24 |
+
|
25 |
def store_student_discourse_result(username, text1, text2, analysis_result):
|
26 |
"""
|
27 |
Guarda el resultado del análisis de discurso en MongoDB.
|
|
|
28 |
"""
|
29 |
try:
|
30 |
+
# Verificar que el resultado contenga bytes de gráficos
|
31 |
+
if not analysis_result.get('success', False):
|
32 |
+
logger.error("No se puede guardar un análisis fallido")
|
33 |
+
return False
|
34 |
+
|
35 |
+
# Preparar el documento para MongoDB
|
36 |
+
document = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
'username': username,
|
38 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
39 |
'text1': text1,
|
40 |
'text2': text2,
|
|
|
41 |
'key_concepts1': analysis_result.get('key_concepts1', []),
|
42 |
+
'key_concepts2': analysis_result.get('key_concepts2', [])
|
|
|
|
|
|
|
43 |
}
|
44 |
+
|
45 |
+
# Codificar gráficos a base64
|
46 |
+
if 'graph1' in analysis_result and isinstance(analysis_result['graph1'], bytes):
|
47 |
+
document['graph1'] = base64.b64encode(analysis_result['graph1']).decode('utf-8')
|
48 |
+
|
49 |
+
if 'graph2' in analysis_result and isinstance(analysis_result['graph2'], bytes):
|
50 |
+
document['graph2'] = base64.b64encode(analysis_result['graph2']).decode('utf-8')
|
51 |
+
|
52 |
+
# Crear un gráfico combinado si se desea (opcional)
|
53 |
+
if 'graph1' in document and 'graph2' in document:
|
54 |
+
document['combined_graph'] = document['graph1'] # O alguna combinación
|
55 |
+
|
56 |
+
# Guardar en MongoDB
|
57 |
+
collection = get_collection('student_discourse_analysis')
|
58 |
+
if not collection:
|
59 |
+
logger.error("No se pudo obtener la colección")
|
60 |
+
return False
|
61 |
+
|
62 |
+
result = collection.insert_one(document)
|
63 |
+
logger.info(f"Análisis de discurso guardado con ID: {result.inserted_id}")
|
64 |
+
return True
|
65 |
+
|
66 |
except Exception as e:
|
67 |
+
logger.error(f"Error guardando análisis de discurso: {str(e)}")
|
68 |
return False
|
69 |
|
70 |
#################################################################################
|
|
|
76 |
Recupera los análisis del discurso de un estudiante.
|
77 |
"""
|
78 |
try:
|
79 |
+
collection = get_collection('student_discourse_analysis')
|
80 |
+
if not collection:
|
81 |
+
logger.error("No se pudo obtener la colección")
|
|
|
82 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
+
query = {"username": username}
|
85 |
+
documents = list(collection.find(query).sort("timestamp", -1).limit(limit))
|
86 |
+
|
87 |
+
# Decodificar gráficos de base64 a bytes
|
88 |
+
for doc in documents:
|
89 |
+
try:
|
90 |
+
if 'graph1' in doc and doc['graph1']:
|
91 |
+
doc['graph1'] = base64.b64decode(doc['graph1'])
|
92 |
+
if 'graph2' in doc and doc['graph2']:
|
93 |
+
doc['graph2'] = base64.b64decode(doc['graph2'])
|
94 |
+
if 'combined_graph' in doc and doc['combined_graph']:
|
95 |
+
doc['combined_graph'] = base64.b64decode(doc['combined_graph'])
|
96 |
+
except Exception as decode_error:
|
97 |
+
logger.error(f"Error decodificando gráficos: {str(decode_error)}")
|
98 |
+
|
99 |
+
return documents
|
100 |
|
|
|
|
|
101 |
except Exception as e:
|
102 |
+
logger.error(f"Error recuperando análisis de discurso: {str(e)}")
|
103 |
return []
|
104 |
|
105 |
#####################################################################################
|