Spaces:
Sleeping
Sleeping
Create claude_recommendations_mongo_db.py
Browse files
modules/database/claude_recommendations_mongo_db.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modules/database/claude_recommendations_mongo_db.py
|
| 2 |
+
from datetime import datetime, timezone, timedelta
|
| 3 |
+
import logging
|
| 4 |
+
from .mongo_db import get_collection
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
COLLECTION_NAME = 'student_claude_recommendations'
|
| 8 |
+
|
| 9 |
+
def store_claude_recommendation(username, text, metrics, text_type, recommendations):
|
| 10 |
+
"""
|
| 11 |
+
Guarda las recomendaciones generadas por Claude AI.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
username: Nombre del usuario
|
| 15 |
+
text: Texto analizado
|
| 16 |
+
metrics: M茅tricas del an谩lisis
|
| 17 |
+
text_type: Tipo de texto (academic_article, university_work, general_communication)
|
| 18 |
+
recommendations: Recomendaciones generadas por Claude
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
bool: True si se guard贸 correctamente, False en caso contrario
|
| 22 |
+
"""
|
| 23 |
+
try:
|
| 24 |
+
# Verificar par谩metros
|
| 25 |
+
if not all([username, text, recommendations]):
|
| 26 |
+
logger.error("Faltan par谩metros requeridos para guardar recomendaciones de Claude")
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
collection = get_collection(COLLECTION_NAME)
|
| 30 |
+
if collection is None:
|
| 31 |
+
logger.error("No se pudo obtener la colecci贸n de recomendaciones de Claude")
|
| 32 |
+
return False
|
| 33 |
+
|
| 34 |
+
# Crear documento
|
| 35 |
+
document = {
|
| 36 |
+
'username': username,
|
| 37 |
+
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 38 |
+
'text': text,
|
| 39 |
+
'metrics': metrics or {},
|
| 40 |
+
'text_type': text_type,
|
| 41 |
+
'recommendations': recommendations,
|
| 42 |
+
'analysis_type': 'claude_recommendation'
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Insertar documento
|
| 46 |
+
result = collection.insert_one(document)
|
| 47 |
+
if result.inserted_id:
|
| 48 |
+
logger.info(f"""
|
| 49 |
+
Recomendaciones de Claude guardadas:
|
| 50 |
+
- Usuario: {username}
|
| 51 |
+
- ID: {result.inserted_id}
|
| 52 |
+
- Tipo de texto: {text_type}
|
| 53 |
+
- Longitud del texto: {len(text)}
|
| 54 |
+
""")
|
| 55 |
+
|
| 56 |
+
# Verificar almacenamiento
|
| 57 |
+
storage_verified = verify_recommendation_storage(username)
|
| 58 |
+
if not storage_verified:
|
| 59 |
+
logger.warning("Verificaci贸n de almacenamiento de recomendaciones fall贸")
|
| 60 |
+
|
| 61 |
+
return True
|
| 62 |
+
|
| 63 |
+
logger.error("No se pudo insertar el documento de recomendaciones")
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"Error guardando recomendaciones de Claude: {str(e)}")
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
def verify_recommendation_storage(username):
|
| 71 |
+
"""
|
| 72 |
+
Verifica que las recomendaciones se est谩n guardando correctamente.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
username: Nombre del usuario
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
bool: True si la verificaci贸n es exitosa, False en caso contrario
|
| 79 |
+
"""
|
| 80 |
+
try:
|
| 81 |
+
collection = get_collection(COLLECTION_NAME)
|
| 82 |
+
if collection is None:
|
| 83 |
+
logger.error("No se pudo obtener la colecci贸n para verificaci贸n de recomendaciones")
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
# Buscar documentos recientes del usuario
|
| 87 |
+
timestamp_threshold = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
|
| 88 |
+
recent_docs = collection.find({
|
| 89 |
+
'username': username,
|
| 90 |
+
'timestamp': {'$gte': timestamp_threshold}
|
| 91 |
+
}).sort('timestamp', -1).limit(1)
|
| 92 |
+
|
| 93 |
+
docs = list(recent_docs)
|
| 94 |
+
if docs:
|
| 95 |
+
logger.info(f"""
|
| 96 |
+
脷ltimo documento de recomendaciones guardado:
|
| 97 |
+
- ID: {docs[0]['_id']}
|
| 98 |
+
- Timestamp: {docs[0]['timestamp']}
|
| 99 |
+
- Tipo de texto: {docs[0].get('text_type', 'N/A')}
|
| 100 |
+
""")
|
| 101 |
+
return True
|
| 102 |
+
|
| 103 |
+
logger.warning(f"No se encontraron documentos recientes de recomendaciones para {username}")
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logger.error(f"Error verificando almacenamiento de recomendaciones: {str(e)}")
|
| 108 |
+
return False
|
| 109 |
+
|
| 110 |
+
def get_claude_recommendations(username, limit=10):
|
| 111 |
+
"""
|
| 112 |
+
Obtiene las recomendaciones m谩s recientes de Claude para un usuario.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
username: Nombre del usuario
|
| 116 |
+
limit: N煤mero m谩ximo de recomendaciones a recuperar
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
list: Lista de recomendaciones
|
| 120 |
+
"""
|
| 121 |
+
try:
|
| 122 |
+
collection = get_collection(COLLECTION_NAME)
|
| 123 |
+
if collection is None:
|
| 124 |
+
logger.error("No se pudo obtener la colecci贸n de recomendaciones")
|
| 125 |
+
return []
|
| 126 |
+
|
| 127 |
+
results = collection.find(
|
| 128 |
+
{'username': username}
|
| 129 |
+
).sort('timestamp', -1).limit(limit)
|
| 130 |
+
|
| 131 |
+
recommendations = list(results)
|
| 132 |
+
logger.info(f"Recuperadas {len(recommendations)} recomendaciones de Claude para {username}")
|
| 133 |
+
return recommendations
|
| 134 |
+
|
| 135 |
+
except Exception as e:
|
| 136 |
+
logger.error(f"Error obteniendo recomendaciones de Claude: {str(e)}")
|
| 137 |
+
return []
|