Update modules/database/discourse_mongo_db.py
Browse files
modules/database/discourse_mongo_db.py
CHANGED
@@ -1,11 +1,12 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
#/modules/database/discoruse_mongo_db.py
|
4 |
from .mongo_db import insert_document, find_documents, update_document, delete_document
|
5 |
from datetime import datetime, timezone
|
6 |
import logging
|
|
|
|
|
7 |
|
8 |
logger = logging.getLogger(__name__)
|
|
|
9 |
COLLECTION_NAME = 'student_discourse_analysis'
|
10 |
|
11 |
def store_student_discourse_result(username, text1, text2, analysis_result):
|
@@ -15,29 +16,46 @@ def store_student_discourse_result(username, text1, text2, analysis_result):
|
|
15 |
username: Nombre del usuario
|
16 |
text1: Primer texto analizado (patrón)
|
17 |
text2: Segundo texto analizado (comparación)
|
18 |
-
analysis_result: Resultado del análisis
|
19 |
-
- key_concepts1: Lista de conceptos clave y frecuencias del primer texto
|
20 |
-
- key_concepts2: Lista de conceptos clave y frecuencias del segundo texto
|
21 |
-
- graph1: Gráfico del primer texto
|
22 |
-
- graph2: Gráfico del segundo texto
|
23 |
"""
|
24 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
analysis_document = {
|
26 |
'username': username,
|
27 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
28 |
'text1': text1,
|
29 |
'text2': text2,
|
30 |
'analysis_type': 'discourse',
|
31 |
-
'key_concepts1': analysis_result
|
32 |
-
'key_concepts2': analysis_result
|
33 |
-
'graph1':
|
34 |
-
'graph2':
|
35 |
}
|
36 |
-
|
|
|
37 |
result = insert_document(COLLECTION_NAME, analysis_document)
|
|
|
38 |
if result:
|
39 |
logger.info(f"Análisis del discurso guardado con ID: {result} para el usuario: {username}")
|
40 |
return True
|
|
|
|
|
41 |
return False
|
42 |
|
43 |
except Exception as e:
|
@@ -46,66 +64,61 @@ def store_student_discourse_result(username, text1, text2, analysis_result):
|
|
46 |
|
47 |
def get_student_discourse_analysis(username, limit=10):
|
48 |
"""
|
49 |
-
Recupera los análisis
|
50 |
-
Args:
|
51 |
-
username: Nombre del usuario
|
52 |
-
limit: Número máximo de análisis a retornar
|
53 |
-
Returns:
|
54 |
-
list: Lista de análisis semánticos
|
55 |
"""
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
-
def
|
60 |
"""
|
61 |
-
|
62 |
-
Args:
|
63 |
-
analysis_id: ID del análisis a actualizar
|
64 |
-
update_data: Datos a actualizar
|
65 |
"""
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
-
def
|
71 |
"""
|
72 |
-
|
73 |
-
Args:
|
74 |
-
analysis_id: ID del análisis a eliminar
|
75 |
"""
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
-
def
|
80 |
"""
|
81 |
-
|
82 |
-
Args:
|
83 |
-
username: Nombre del usuario
|
84 |
-
Returns:
|
85 |
-
dict: Diccionario con todos los análisis del estudiante
|
86 |
"""
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
'text': analysis['text'],
|
94 |
-
'key_concepts': analysis['key_concepts'],
|
95 |
-
'entities': analysis['entities']
|
96 |
-
# No incluimos los gráficos en el resumen general
|
97 |
-
}
|
98 |
-
formatted_analyses.append(formatted_analysis)
|
99 |
-
|
100 |
-
return {
|
101 |
-
'entries': formatted_analyses
|
102 |
-
}
|
103 |
-
|
104 |
-
# Exportar las funciones necesarias
|
105 |
-
__all__ = [
|
106 |
-
'store_student_discourse_result',
|
107 |
-
'get_student_discourse_analysis',
|
108 |
-
'update_student_discourse_analysis',
|
109 |
-
'delete_student_discourse_analysis',
|
110 |
-
'get_student_discourse_data'
|
111 |
-
]
|
|
|
1 |
+
# modules/database/discourse_mongo_db.py
|
|
|
|
|
2 |
from .mongo_db import insert_document, find_documents, update_document, delete_document
|
3 |
from datetime import datetime, timezone
|
4 |
import logging
|
5 |
+
import io
|
6 |
+
import base64
|
7 |
|
8 |
logger = logging.getLogger(__name__)
|
9 |
+
|
10 |
COLLECTION_NAME = 'student_discourse_analysis'
|
11 |
|
12 |
def store_student_discourse_result(username, text1, text2, analysis_result):
|
|
|
16 |
username: Nombre del usuario
|
17 |
text1: Primer texto analizado (patrón)
|
18 |
text2: Segundo texto analizado (comparación)
|
19 |
+
analysis_result: Resultado del análisis
|
|
|
|
|
|
|
|
|
20 |
"""
|
21 |
try:
|
22 |
+
# Convertir gráficos a formato base64 si existen
|
23 |
+
graph1_data = None
|
24 |
+
graph2_data = None
|
25 |
+
|
26 |
+
if 'graph1' in analysis_result:
|
27 |
+
buf = io.BytesIO()
|
28 |
+
analysis_result['graph1'].savefig(buf, format='png')
|
29 |
+
buf.seek(0)
|
30 |
+
graph1_data = base64.b64encode(buf.getvalue()).decode('utf-8')
|
31 |
+
|
32 |
+
if 'graph2' in analysis_result:
|
33 |
+
buf = io.BytesIO()
|
34 |
+
analysis_result['graph2'].savefig(buf, format='png')
|
35 |
+
buf.seek(0)
|
36 |
+
graph2_data = base64.b64encode(buf.getvalue()).decode('utf-8')
|
37 |
+
|
38 |
+
# Crear documento para MongoDB
|
39 |
analysis_document = {
|
40 |
'username': username,
|
41 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
42 |
'text1': text1,
|
43 |
'text2': text2,
|
44 |
'analysis_type': 'discourse',
|
45 |
+
'key_concepts1': analysis_result.get('key_concepts1', []),
|
46 |
+
'key_concepts2': analysis_result.get('key_concepts2', []),
|
47 |
+
'graph1': graph1_data,
|
48 |
+
'graph2': graph2_data
|
49 |
}
|
50 |
+
|
51 |
+
# Insertar en MongoDB
|
52 |
result = insert_document(COLLECTION_NAME, analysis_document)
|
53 |
+
|
54 |
if result:
|
55 |
logger.info(f"Análisis del discurso guardado con ID: {result} para el usuario: {username}")
|
56 |
return True
|
57 |
+
|
58 |
+
logger.error("No se pudo insertar el documento en MongoDB")
|
59 |
return False
|
60 |
|
61 |
except Exception as e:
|
|
|
64 |
|
65 |
def get_student_discourse_analysis(username, limit=10):
|
66 |
"""
|
67 |
+
Recupera los análisis del discurso de un estudiante.
|
|
|
|
|
|
|
|
|
|
|
68 |
"""
|
69 |
+
try:
|
70 |
+
query = {
|
71 |
+
"username": username,
|
72 |
+
"analysis_type": "discourse"
|
73 |
+
}
|
74 |
+
return find_documents(COLLECTION_NAME, query, sort=[("timestamp", -1)], limit=limit)
|
75 |
+
except Exception as e:
|
76 |
+
logger.error(f"Error al recuperar análisis del discurso: {str(e)}")
|
77 |
+
return []
|
78 |
|
79 |
+
def get_student_discourse_data(username):
|
80 |
"""
|
81 |
+
Obtiene un resumen de los análisis del discurso de un estudiante.
|
|
|
|
|
|
|
82 |
"""
|
83 |
+
try:
|
84 |
+
analyses = get_student_discourse_analysis(username, limit=None)
|
85 |
+
formatted_analyses = []
|
86 |
+
|
87 |
+
for analysis in analyses:
|
88 |
+
formatted_analysis = {
|
89 |
+
'timestamp': analysis['timestamp'],
|
90 |
+
'text1': analysis.get('text1', ''),
|
91 |
+
'text2': analysis.get('text2', ''),
|
92 |
+
'key_concepts1': analysis.get('key_concepts1', []),
|
93 |
+
'key_concepts2': analysis.get('key_concepts2', [])
|
94 |
+
}
|
95 |
+
formatted_analyses.append(formatted_analysis)
|
96 |
+
|
97 |
+
return {'entries': formatted_analyses}
|
98 |
+
|
99 |
+
except Exception as e:
|
100 |
+
logger.error(f"Error al obtener datos del discurso: {str(e)}")
|
101 |
+
return {'entries': []}
|
102 |
|
103 |
+
def update_student_discourse_analysis(analysis_id, update_data):
|
104 |
"""
|
105 |
+
Actualiza un análisis del discurso existente.
|
|
|
|
|
106 |
"""
|
107 |
+
try:
|
108 |
+
query = {"_id": analysis_id}
|
109 |
+
update = {"$set": update_data}
|
110 |
+
return update_document(COLLECTION_NAME, query, update)
|
111 |
+
except Exception as e:
|
112 |
+
logger.error(f"Error al actualizar análisis del discurso: {str(e)}")
|
113 |
+
return False
|
114 |
|
115 |
+
def delete_student_discourse_analysis(analysis_id):
|
116 |
"""
|
117 |
+
Elimina un análisis del discurso.
|
|
|
|
|
|
|
|
|
118 |
"""
|
119 |
+
try:
|
120 |
+
query = {"_id": analysis_id}
|
121 |
+
return delete_document(COLLECTION_NAME, query)
|
122 |
+
except Exception as e:
|
123 |
+
logger.error(f"Error al eliminar análisis del discurso: {str(e)}")
|
124 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|