Update modules/database.py
Browse files- modules/database.py +88 -10
modules/database.py
CHANGED
|
@@ -1,18 +1,48 @@
|
|
| 1 |
# database.py
|
| 2 |
import logging
|
|
|
|
|
|
|
|
|
|
| 3 |
from pymongo import MongoClient
|
| 4 |
import certifi
|
| 5 |
from datetime import datetime
|
|
|
|
|
|
|
| 6 |
|
|
|
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
-
# Variables globales
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
mongo_client = None
|
| 11 |
-
|
| 12 |
analysis_collection = None
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def initialize_mongodb_connection():
|
| 15 |
-
global mongo_client,
|
| 16 |
try:
|
| 17 |
cosmos_mongodb_connection_string = os.getenv("MONGODB_CONNECTION_STRING")
|
| 18 |
if not cosmos_mongodb_connection_string:
|
|
@@ -29,8 +59,8 @@ def initialize_mongodb_connection():
|
|
| 29 |
|
| 30 |
mongo_client.admin.command('ping')
|
| 31 |
|
| 32 |
-
|
| 33 |
-
analysis_collection =
|
| 34 |
|
| 35 |
logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
|
| 36 |
return True
|
|
@@ -38,16 +68,35 @@ def initialize_mongodb_connection():
|
|
| 38 |
logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}", exc_info=True)
|
| 39 |
return False
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def get_student_data(username):
|
| 42 |
if analysis_collection is None:
|
| 43 |
logger.error("La conexi贸n a MongoDB no est谩 inicializada")
|
| 44 |
return None
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
# Buscar los datos del estudiante
|
| 48 |
cursor = analysis_collection.find({"username": username}).sort("timestamp", -1)
|
| 49 |
|
| 50 |
-
# Formatear los datos
|
| 51 |
formatted_data = {
|
| 52 |
"username": username,
|
| 53 |
"entries": [],
|
|
@@ -64,14 +113,12 @@ def get_student_data(username):
|
|
| 64 |
})
|
| 65 |
formatted_data["entries_count"] += 1
|
| 66 |
|
| 67 |
-
# Agregar conteo de palabras
|
| 68 |
for category, count in entry.get("word_count", {}).items():
|
| 69 |
if category in formatted_data["word_count"]:
|
| 70 |
formatted_data["word_count"][category] += count
|
| 71 |
else:
|
| 72 |
formatted_data["word_count"][category] = count
|
| 73 |
|
| 74 |
-
# Agregar diagramas
|
| 75 |
formatted_data["arc_diagrams"].extend(entry.get("arc_diagrams", []))
|
| 76 |
formatted_data["network_diagrams"].append(entry.get("network_diagram", ""))
|
| 77 |
|
|
@@ -80,4 +127,35 @@ def get_student_data(username):
|
|
| 80 |
logger.error(f"Error al obtener datos del estudiante {username}: {str(e)}")
|
| 81 |
return None
|
| 82 |
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# database.py
|
| 2 |
import logging
|
| 3 |
+
import os
|
| 4 |
+
from azure.cosmos import CosmosClient
|
| 5 |
+
from azure.cosmos.exceptions import CosmosHttpResponseError
|
| 6 |
from pymongo import MongoClient
|
| 7 |
import certifi
|
| 8 |
from datetime import datetime
|
| 9 |
+
import io
|
| 10 |
+
import base64
|
| 11 |
|
| 12 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
+
# Variables globales para Cosmos DB SQL API
|
| 16 |
+
cosmos_client = None
|
| 17 |
+
user_database = None
|
| 18 |
+
user_container = None
|
| 19 |
+
|
| 20 |
+
# Variables globales para Cosmos DB MongoDB API
|
| 21 |
mongo_client = None
|
| 22 |
+
mongo_db = None
|
| 23 |
analysis_collection = None
|
| 24 |
|
| 25 |
+
def initialize_cosmos_sql_connection():
|
| 26 |
+
global cosmos_client, user_database, user_container
|
| 27 |
+
try:
|
| 28 |
+
cosmos_endpoint = os.environ.get("COSMOS_ENDPOINT")
|
| 29 |
+
cosmos_key = os.environ.get("COSMOS_KEY")
|
| 30 |
+
|
| 31 |
+
if not cosmos_endpoint or not cosmos_key:
|
| 32 |
+
raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
|
| 33 |
+
|
| 34 |
+
cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
|
| 35 |
+
user_database = cosmos_client.get_database_client("user_database")
|
| 36 |
+
user_container = user_database.get_container_client("users")
|
| 37 |
+
|
| 38 |
+
logger.info("Conexi贸n a Cosmos DB SQL API exitosa")
|
| 39 |
+
return True
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}")
|
| 42 |
+
return False
|
| 43 |
+
|
| 44 |
def initialize_mongodb_connection():
|
| 45 |
+
global mongo_client, mongo_db, analysis_collection
|
| 46 |
try:
|
| 47 |
cosmos_mongodb_connection_string = os.getenv("MONGODB_CONNECTION_STRING")
|
| 48 |
if not cosmos_mongodb_connection_string:
|
|
|
|
| 59 |
|
| 60 |
mongo_client.admin.command('ping')
|
| 61 |
|
| 62 |
+
mongo_db = mongo_client['aideatext_db']
|
| 63 |
+
analysis_collection = mongo_db['text_analysis']
|
| 64 |
|
| 65 |
logger.info("Conexi贸n a Cosmos DB MongoDB API exitosa")
|
| 66 |
return True
|
|
|
|
| 68 |
logger.error(f"Error al conectar con Cosmos DB MongoDB API: {str(e)}", exc_info=True)
|
| 69 |
return False
|
| 70 |
|
| 71 |
+
# Funciones para Cosmos DB SQL API (manejo de usuarios)
|
| 72 |
+
|
| 73 |
+
def get_user(username):
|
| 74 |
+
try:
|
| 75 |
+
query = f"SELECT * FROM c WHERE c.id = '{username}'"
|
| 76 |
+
items = list(user_container.query_items(query=query, enable_cross_partition_query=True))
|
| 77 |
+
return items[0] if items else None
|
| 78 |
+
except Exception as e:
|
| 79 |
+
logger.error(f"Error al obtener usuario {username}: {str(e)}")
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
def create_user(user_data):
|
| 83 |
+
try:
|
| 84 |
+
user_container.create_item(body=user_data)
|
| 85 |
+
return True
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logger.error(f"Error al crear usuario: {str(e)}")
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
# Funciones para Cosmos DB MongoDB API (an谩lisis de texto)
|
| 91 |
+
|
| 92 |
def get_student_data(username):
|
| 93 |
if analysis_collection is None:
|
| 94 |
logger.error("La conexi贸n a MongoDB no est谩 inicializada")
|
| 95 |
return None
|
| 96 |
|
| 97 |
try:
|
|
|
|
| 98 |
cursor = analysis_collection.find({"username": username}).sort("timestamp", -1)
|
| 99 |
|
|
|
|
| 100 |
formatted_data = {
|
| 101 |
"username": username,
|
| 102 |
"entries": [],
|
|
|
|
| 113 |
})
|
| 114 |
formatted_data["entries_count"] += 1
|
| 115 |
|
|
|
|
| 116 |
for category, count in entry.get("word_count", {}).items():
|
| 117 |
if category in formatted_data["word_count"]:
|
| 118 |
formatted_data["word_count"][category] += count
|
| 119 |
else:
|
| 120 |
formatted_data["word_count"][category] = count
|
| 121 |
|
|
|
|
| 122 |
formatted_data["arc_diagrams"].extend(entry.get("arc_diagrams", []))
|
| 123 |
formatted_data["network_diagrams"].append(entry.get("network_diagram", ""))
|
| 124 |
|
|
|
|
| 127 |
logger.error(f"Error al obtener datos del estudiante {username}: {str(e)}")
|
| 128 |
return None
|
| 129 |
|
| 130 |
+
def store_analysis_result(username, text, repeated_words, arc_diagrams, network_diagram):
|
| 131 |
+
if analysis_collection is None:
|
| 132 |
+
logger.error("La conexi贸n a MongoDB no est谩 inicializada")
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
buffer = io.BytesIO()
|
| 137 |
+
network_diagram.savefig(buffer, format='png')
|
| 138 |
+
buffer.seek(0)
|
| 139 |
+
network_diagram_base64 = base64.b64encode(buffer.getvalue()).decode()
|
| 140 |
+
|
| 141 |
+
word_count = {}
|
| 142 |
+
for word, color in repeated_words.items():
|
| 143 |
+
category = color # Asumiendo que 'color' es la categor铆a gramatical
|
| 144 |
+
word_count[category] = word_count.get(category, 0) + 1
|
| 145 |
+
|
| 146 |
+
analysis_document = {
|
| 147 |
+
'username': username,
|
| 148 |
+
'timestamp': datetime.utcnow(),
|
| 149 |
+
'text': text,
|
| 150 |
+
'word_count': word_count,
|
| 151 |
+
'arc_diagrams': arc_diagrams,
|
| 152 |
+
'network_diagram': network_diagram_base64
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
result = analysis_collection.insert_one(analysis_document)
|
| 156 |
+
|
| 157 |
+
logger.info(f"An谩lisis guardado con ID: {result.inserted_id} para el usuario: {username}")
|
| 158 |
+
return True
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.error(f"Error al guardar el an谩lisis para el usuario {username}: {str(e)}")
|
| 161 |
+
return False
|