AIdeaText commited on
Commit
71da918
verified
1 Parent(s): b66aab1

Update modules/database.py

Browse files
Files changed (1) hide show
  1. modules/database.py +37 -21
modules/database.py CHANGED
@@ -25,6 +25,7 @@ user_container = None
25
  mongo_client = None
26
  mongo_db = None
27
  analysis_collection = None
 
28
 
29
  #####################################################################################33
30
  def initialize_cosmos_sql_connection():
@@ -71,6 +72,10 @@ def initialize_mongodb_connection():
71
 
72
  mongo_db = mongo_client['aideatext_db']
73
  analysis_collection = mongo_db['text_analysis']
 
 
 
 
74
 
75
  logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
76
  return True
@@ -238,6 +243,7 @@ def store_chat_history(username, messages):
238
  }
239
  result = chat_collection.insert_one(chat_document)
240
  logger.info(f"Chat history saved with ID: {result.inserted_id} for user: {username}")
 
241
  return True
242
  except Exception as e:
243
  logger.error(f"Error saving chat history for user {username}: {str(e)}")
@@ -245,24 +251,24 @@ def store_chat_history(username, messages):
245
 
246
  #######################################################################################################
247
  def get_student_data(username):
248
- if analysis_collection is None:
249
  logger.error("La conexi贸n a MongoDB no est谩 inicializada")
250
  return None
251
 
 
 
 
 
 
 
 
 
 
 
252
  try:
253
- logger.info(f"Buscando datos para el usuario: {username}")
254
  cursor = analysis_collection.find({"username": username})
255
 
256
- formatted_data = {
257
- "username": username,
258
- "entries": [],
259
- "entries_count": 0,
260
- "word_count": {},
261
- "semantic_analyses": [],
262
- "discourse_analyses": [],
263
- "chat_history": []
264
- }
265
-
266
  for entry in cursor:
267
  formatted_entry = {
268
  "timestamp": entry.get("timestamp", datetime.utcnow()),
@@ -297,14 +303,24 @@ def get_student_data(username):
297
 
298
  for entry in formatted_data["entries"]:
299
  entry["timestamp"] = entry["timestamp"].isoformat()
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
- # Obtener el historial del chat
302
- chat_cursor = mongo_db.chat_history.find({"username": username})
303
- formatted_data["chat_history"] = list(chat_cursor)
304
-
305
- logger.info(f"Datos formateados para {username}: {formatted_data}")
306
- return formatted_data
307
-
308
  except Exception as e:
309
- logger.error(f"Error al obtener datos del estudiante {username}: {str(e)}")
310
- return None
 
 
 
25
  mongo_client = None
26
  mongo_db = None
27
  analysis_collection = None
28
+ chat_collection = None # Nueva variable global
29
 
30
  #####################################################################################33
31
  def initialize_cosmos_sql_connection():
 
72
 
73
  mongo_db = mongo_client['aideatext_db']
74
  analysis_collection = mongo_db['text_analysis']
75
+ chat_collection = mongo_db['chat_history'] # Inicializar la nueva colecci贸n
76
+
77
+ # Verificar la conexi贸n
78
+ mongo_client.admin.command('ping')
79
 
80
  logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
81
  return True
 
243
  }
244
  result = chat_collection.insert_one(chat_document)
245
  logger.info(f"Chat history saved with ID: {result.inserted_id} for user: {username}")
246
+ logger.debug(f"Chat content: {messages}")
247
  return True
248
  except Exception as e:
249
  logger.error(f"Error saving chat history for user {username}: {str(e)}")
 
251
 
252
  #######################################################################################################
253
  def get_student_data(username):
254
+ if analysis_collection is None or chat_collection is None:
255
  logger.error("La conexi贸n a MongoDB no est谩 inicializada")
256
  return None
257
 
258
+ formatted_data = {
259
+ "username": username,
260
+ "entries": [],
261
+ "entries_count": 0,
262
+ "word_count": {},
263
+ "semantic_analyses": [],
264
+ "discourse_analyses": [],
265
+ "chat_history": []
266
+ }
267
+
268
  try:
269
+ logger.info(f"Buscando datos de an谩lisis para el usuario: {username}")
270
  cursor = analysis_collection.find({"username": username})
271
 
 
 
 
 
 
 
 
 
 
 
272
  for entry in cursor:
273
  formatted_entry = {
274
  "timestamp": entry.get("timestamp", datetime.utcnow()),
 
303
 
304
  for entry in formatted_data["entries"]:
305
  entry["timestamp"] = entry["timestamp"].isoformat()
306
+
307
+ except Exception as e:
308
+ logger.error(f"Error al obtener datos de an谩lisis del estudiante {username}: {str(e)}")
309
+
310
+ try:
311
+ logger.info(f"Buscando historial de chat para el usuario: {username}")
312
+ chat_cursor = chat_collection.find({"username": username})
313
+ for chat in chat_cursor:
314
+ formatted_chat = {
315
+ "timestamp": chat["timestamp"].isoformat(),
316
+ "messages": chat["messages"]
317
+ }
318
+ formatted_data["chat_history"].append(formatted_chat)
319
 
320
+ formatted_data["chat_history"].sort(key=lambda x: x["timestamp"], reverse=True)
321
+
 
 
 
 
 
322
  except Exception as e:
323
+ logger.error(f"Error al obtener historial de chat del estudiante {username}: {str(e)}")
324
+
325
+ logger.info(f"Datos formateados para {username}: {formatted_data}")
326
+ return formatted_data