AIdeaText commited on
Commit
c78e82d
verified
1 Parent(s): 7dc23a0

Update modules/database/semantic_mongo_live_db.py

Browse files
modules/database/semantic_mongo_live_db.py CHANGED
@@ -23,96 +23,83 @@ COLLECTION_NAME = 'student_semantic_live_analysis'
23
  def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'):
24
  """
25
  Versi贸n corregida con:
26
- - Mejor verificaci贸n de colecci贸n
27
- - Logs m谩s detallados
28
- - Validaci贸n de inserci贸n mejorada
29
  """
30
  try:
31
- # 1. Verificaci贸n de colecci贸n
32
  collection = get_collection(COLLECTION_NAME)
33
- if not collection:
34
- logger.error(f"No se pudo acceder a la colecci贸n {COLLECTION_NAME}")
35
  return False
36
 
37
- # 2. Validaci贸n de par谩metros extendida
38
  if not all([username, text, analysis_result]):
39
  logger.error("Par谩metros incompletos para guardar an谩lisis")
40
  return False
41
 
42
- # 3. Preparaci贸n del documento con m谩s logging
43
  analysis_document = {
44
- 'username': str(username),
45
  'timestamp': datetime.now(timezone.utc),
46
- 'text': str(text)[:50000], # Limitar tama帽o
47
  'analysis_type': 'semantic_live',
48
- 'language': str(lang_code),
49
  'key_concepts': analysis_result.get('key_concepts', [])[:50],
50
- 'concept_centrality': analysis_result.get('concept_centrality', {}),
51
- 'metadata': {
52
- 'version': '1.1',
53
- 'source': 'live_interface_v2'
54
- }
55
  }
56
 
57
- # 4. Manejo del gr谩fico con m谩s controles
58
- if 'concept_graph' in analysis_result:
59
  try:
60
- graph_data = analysis_result['concept_graph']
61
- if isinstance(graph_data, bytes):
62
- analysis_document['concept_graph'] = base64.b64encode(graph_data).decode('utf-8')
63
- elif isinstance(graph_data, str) and graph_data:
64
- analysis_document['concept_graph'] = graph_data
65
  except Exception as e:
66
- logger.warning(f"Error procesando gr谩fico: {str(e)}")
67
 
68
- # 5. Inserci贸n con verificaci贸n expl铆cita
69
  try:
70
  result = collection.insert_one(analysis_document)
71
  if result.inserted_id:
72
  logger.info(f"An谩lisis guardado. ID: {result.inserted_id}")
73
  return True
74
-
75
  logger.error("Inserci贸n fallida - Sin ID devuelto")
76
  return False
77
-
78
  except PyMongoError as e:
79
  logger.error(f"Error de MongoDB: {str(e)}")
80
  return False
81
 
82
  except Exception as e:
83
- logger.error(f"Error cr铆tico: {str(e)}", exc_info=True)
84
  return False
85
 
86
  ##########################################
87
  ##########################################
88
  def get_student_semantic_live_analysis(username, limit=10):
89
  """
90
- Recupera los an谩lisis sem谩nticos en vivo de un estudiante.
91
- Versi贸n corregida con consulta adecuada.
92
  """
93
  try:
94
- query = {
95
- "username": username,
96
- "analysis_type": "semantic_live" # Corregido a semantic_live
97
- }
 
 
98
 
99
- projection = {
 
100
  "timestamp": 1,
101
- "text": {"$substr": ["$text", 0, 200]}, # Solo primeros 200 chars
102
  "key_concepts": 1,
103
  "concept_graph": 1,
104
  "_id": 1
105
- }
106
-
107
- results = find_documents(
108
- COLLECTION_NAME,
109
- query,
110
- projection=projection,
111
- sort=[("timestamp", -1)],
112
- limit=limit
113
- )
114
 
115
- logger.info(f"Recuperados {len(results)} an谩lisis en vivo para {username}")
 
116
  return results
117
 
118
  except PyMongoError as e:
@@ -122,6 +109,8 @@ def get_student_semantic_live_analysis(username, limit=10):
122
  logger.error(f"Error inesperado: {str(e)}")
123
  return []
124
 
 
 
125
  def update_student_semantic_live_analysis(analysis_id, update_data):
126
  """Actualiza un an谩lisis existente con manejo de errores"""
127
  try:
@@ -132,6 +121,8 @@ def update_student_semantic_live_analysis(analysis_id, update_data):
132
  logger.error(f"Error al actualizar: {str(e)}")
133
  return False
134
 
 
 
135
  def delete_student_semantic_live_analysis(analysis_id):
136
  """Elimina un an谩lisis con manejo de errores"""
137
  try:
@@ -141,6 +132,8 @@ def delete_student_semantic_live_analysis(analysis_id):
141
  logger.error(f"Error al eliminar: {str(e)}")
142
  return False
143
 
 
 
144
  def get_student_semantic_live_data(username):
145
  """
146
  Obtiene todos los an谩lisis sem谩nticos en vivo de un estudiante.
@@ -176,6 +169,10 @@ def get_student_semantic_live_data(username):
176
  'error': str(e)
177
  }
178
 
 
 
 
 
179
  __all__ = [
180
  'store_student_semantic_live_result',
181
  'get_student_semantic_live_analysis',
 
23
  def store_student_semantic_live_result(username, text, analysis_result, lang_code='en'):
24
  """
25
  Versi贸n corregida con:
26
+ - Verificaci贸n correcta de colecci贸n
27
+ - Manejo de proyecci贸n alternativo
28
+ - Mejor manejo de errores
29
  """
30
  try:
31
+ # 1. Obtener colecci贸n con verificaci贸n correcta
32
  collection = get_collection(COLLECTION_NAME)
33
+ if collection is None: # Cambiado de 'if not collection'
34
+ logger.error(f"No se pudo obtener la colecci贸n {COLLECTION_NAME}")
35
  return False
36
 
37
+ # 2. Validaci贸n de par谩metros
38
  if not all([username, text, analysis_result]):
39
  logger.error("Par谩metros incompletos para guardar an谩lisis")
40
  return False
41
 
42
+ # 3. Preparar documento
43
  analysis_document = {
44
+ 'username': username,
45
  'timestamp': datetime.now(timezone.utc),
46
+ 'text': text[:50000],
47
  'analysis_type': 'semantic_live',
48
+ 'language': lang_code,
49
  'key_concepts': analysis_result.get('key_concepts', [])[:50],
50
+ 'concept_centrality': analysis_result.get('concept_centrality', {})
 
 
 
 
51
  }
52
 
53
+ # 4. Manejo del gr谩fico
54
+ if 'concept_graph' in analysis_result and analysis_result['concept_graph']:
55
  try:
56
+ if isinstance(analysis_result['concept_graph'], bytes):
57
+ analysis_document['concept_graph'] = base64.b64encode(
58
+ analysis_result['concept_graph']).decode('utf-8')
 
 
59
  except Exception as e:
60
+ logger.error(f"Error procesando gr谩fico: {str(e)}")
61
 
62
+ # 5. Insertar documento
63
  try:
64
  result = collection.insert_one(analysis_document)
65
  if result.inserted_id:
66
  logger.info(f"An谩lisis guardado. ID: {result.inserted_id}")
67
  return True
 
68
  logger.error("Inserci贸n fallida - Sin ID devuelto")
69
  return False
 
70
  except PyMongoError as e:
71
  logger.error(f"Error de MongoDB: {str(e)}")
72
  return False
73
 
74
  except Exception as e:
75
+ logger.error(f"Error inesperado: {str(e)}", exc_info=True)
76
  return False
77
 
78
  ##########################################
79
  ##########################################
80
  def get_student_semantic_live_analysis(username, limit=10):
81
  """
82
+ Versi贸n corregida sin usar projection
 
83
  """
84
  try:
85
+ collection = get_collection(COLLECTION_NAME)
86
+ if collection is None:
87
+ logger.error("No se pudo obtener la colecci贸n")
88
+ return []
89
+
90
+ query = {"username": username, "analysis_type": "semantic_live"}
91
 
92
+ # Versi贸n alternativa sin projection
93
+ cursor = collection.find(query, {
94
  "timestamp": 1,
95
+ "text": 1,
96
  "key_concepts": 1,
97
  "concept_graph": 1,
98
  "_id": 1
99
+ }).sort("timestamp", -1).limit(limit)
 
 
 
 
 
 
 
 
100
 
101
+ results = list(cursor)
102
+ logger.info(f"Recuperados {len(results)} an谩lisis para {username}")
103
  return results
104
 
105
  except PyMongoError as e:
 
109
  logger.error(f"Error inesperado: {str(e)}")
110
  return []
111
 
112
+ #######################################################
113
+ #######################################################
114
  def update_student_semantic_live_analysis(analysis_id, update_data):
115
  """Actualiza un an谩lisis existente con manejo de errores"""
116
  try:
 
121
  logger.error(f"Error al actualizar: {str(e)}")
122
  return False
123
 
124
+ #######################################################
125
+ #######################################################
126
  def delete_student_semantic_live_analysis(analysis_id):
127
  """Elimina un an谩lisis con manejo de errores"""
128
  try:
 
132
  logger.error(f"Error al eliminar: {str(e)}")
133
  return False
134
 
135
+ #######################################################
136
+ #######################################################
137
  def get_student_semantic_live_data(username):
138
  """
139
  Obtiene todos los an谩lisis sem谩nticos en vivo de un estudiante.
 
169
  'error': str(e)
170
  }
171
 
172
+
173
+ #######################################################
174
+ #######################################################
175
+
176
  __all__ = [
177
  'store_student_semantic_live_result',
178
  'get_student_semantic_live_analysis',