Spaces:
Sleeping
Sleeping
Update modules/studentact/claude_recommendations.py
Browse files
modules/studentact/claude_recommendations.py
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
|
|
|
|
|
| 1 |
import anthropic
|
| 2 |
import os
|
| 3 |
import streamlit as st
|
| 4 |
import logging
|
| 5 |
from typing import Dict, Any
|
|
|
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
|
@@ -31,9 +34,16 @@ def generate_claude_recommendations(text: str, metrics: Dict[str, Any], text_typ
|
|
| 31 |
scores = {area: metrics[area]['normalized_score'] for area in areas}
|
| 32 |
weak_areas = sorted(areas, key=lambda x: scores[x])
|
| 33 |
|
| 34 |
-
# Crear un mensaje estructurado para Claude
|
| 35 |
try:
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
# Construir el prompt para Claude
|
| 39 |
prompt = f"""
|
|
@@ -51,105 +61,62 @@ def generate_claude_recommendations(text: str, metrics: Dict[str, Any], text_typ
|
|
| 51 |
{', '.join([area for area in weak_areas[:2]])}
|
| 52 |
|
| 53 |
Texto analizado:
|
| 54 |
-
"{
|
| 55 |
|
| 56 |
Por favor, proporciona:
|
| 57 |
1. Un breve resumen del análisis (2-3 oraciones)
|
| 58 |
-
2. 3-4 recomendaciones específicas para mejorar el texto, identificando problemas concretos
|
| 59 |
-
3.
|
| 60 |
-
4. Un ejemplo concreto de cómo mejorar una frase del texto
|
| 61 |
|
| 62 |
-
Utiliza un tono profesional pero amigable, y estructura tus recomendaciones en HTML simple usando etiquetas <h4>, <p>, <ul>, <li>, y <strong>.
|
| 63 |
"""
|
| 64 |
|
| 65 |
# Llamada a la API de Claude
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
except Exception as e:
|
| 80 |
logger.error(f"Error generando recomendaciones con Claude: {str(e)}")
|
| 81 |
-
|
| 82 |
-
return f"""
|
| 83 |
-
<h4>Recomendaciones para mejorar tu texto</h4>
|
| 84 |
-
<p>Hemos detectado que las áreas de <strong>{weak_areas[0]}</strong> y <strong>{weak_areas[1]}</strong>
|
| 85 |
-
son las que más podrían beneficiarse de mejoras.</p>
|
| 86 |
-
<p>Para obtener recomendaciones más detalladas, utiliza el asistente virtual de Claude AI
|
| 87 |
-
ubicado en la esquina superior izquierda (presiona la flecha junto al logo).</p>
|
| 88 |
-
"""
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
"""
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
"""
|
| 101 |
-
st.markdown("### 📝 Recomendaciones Personalizadas")
|
| 102 |
-
|
| 103 |
-
# Verificar si ya tenemos las recomendaciones en la sesión
|
| 104 |
-
recommendations_key = f"claude_recommendations_{text_type}"
|
| 105 |
-
|
| 106 |
-
# Generar nuevas recomendaciones si no existen o si se ha cambiado el tipo de texto
|
| 107 |
-
if recommendations_key not in st.session_state:
|
| 108 |
-
with st.spinner("Generando recomendaciones personalizadas..."):
|
| 109 |
-
recommendations_html = generate_claude_recommendations(
|
| 110 |
-
text=text,
|
| 111 |
-
metrics=metrics,
|
| 112 |
-
text_type=text_type,
|
| 113 |
-
lang_code=lang_code
|
| 114 |
-
)
|
| 115 |
-
st.session_state[recommendations_key] = recommendations_html
|
| 116 |
-
|
| 117 |
-
# Mostrar las recomendaciones
|
| 118 |
-
st.markdown(
|
| 119 |
-
f"""
|
| 120 |
-
<div style="border: 1px solid #ddd; border-radius: 8px; padding: 20px; background-color: #f9f9f9;">
|
| 121 |
-
{st.session_state[recommendations_key]}
|
| 122 |
-
</div>
|
| 123 |
-
""",
|
| 124 |
-
unsafe_allow_html=True
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
# Mensaje para animar a usar el chatbot
|
| 128 |
-
st.info("💡 **Para seguir mejorando tu texto:** Despliega el asistente virtual (potenciado por Claude AI) ubicado en la parte superior izquierda, presionando la flecha junto al logo.")
|
| 129 |
|
| 130 |
-
|
| 131 |
-
def display_recommendations_section(text_input, current_doc, current_metrics, text_type, lang_code, t):
|
| 132 |
-
"""
|
| 133 |
-
Función principal para mostrar la sección de recomendaciones en la interfaz.
|
| 134 |
-
|
| 135 |
-
Reemplaza a la función display_recommendations_with_actions anterior.
|
| 136 |
"""
|
| 137 |
-
|
| 138 |
-
subtab1, subtab2 = st.tabs(["Diagnóstico", "Recomendaciones"])
|
| 139 |
-
|
| 140 |
-
# Tab de diagnóstico (mantener el radar chart existente)
|
| 141 |
-
with subtab1:
|
| 142 |
-
display_diagnosis(
|
| 143 |
-
metrics=current_metrics,
|
| 144 |
-
text_type=text_type
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
# Tab de recomendaciones personalizadas por Claude
|
| 148 |
-
with subtab2:
|
| 149 |
-
display_personalized_recommendations(
|
| 150 |
-
text=text_input,
|
| 151 |
-
metrics=current_metrics,
|
| 152 |
-
text_type=text_type,
|
| 153 |
-
lang_code=lang_code,
|
| 154 |
-
t=t
|
| 155 |
-
)
|
|
|
|
| 1 |
+
# modules/studentact/claude_recommendations.py
|
| 2 |
+
|
| 3 |
import anthropic
|
| 4 |
import os
|
| 5 |
import streamlit as st
|
| 6 |
import logging
|
| 7 |
from typing import Dict, Any
|
| 8 |
+
import json
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
|
|
|
| 34 |
scores = {area: metrics[area]['normalized_score'] for area in areas}
|
| 35 |
weak_areas = sorted(areas, key=lambda x: scores[x])
|
| 36 |
|
|
|
|
| 37 |
try:
|
| 38 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
| 39 |
+
if not api_key:
|
| 40 |
+
logger.warning("No se encontró ANTHROPIC_API_KEY en las variables de entorno")
|
| 41 |
+
return fallback_recommendations(weak_areas)
|
| 42 |
+
|
| 43 |
+
client = anthropic.Anthropic(api_key=api_key)
|
| 44 |
+
|
| 45 |
+
# Truncar el texto si es muy largo para evitar exceder límites de tokens
|
| 46 |
+
truncated_text = text[:1000] + "..." if len(text) > 1000 else text
|
| 47 |
|
| 48 |
# Construir el prompt para Claude
|
| 49 |
prompt = f"""
|
|
|
|
| 61 |
{', '.join([area for area in weak_areas[:2]])}
|
| 62 |
|
| 63 |
Texto analizado:
|
| 64 |
+
"{truncated_text}"
|
| 65 |
|
| 66 |
Por favor, proporciona:
|
| 67 |
1. Un breve resumen del análisis (2-3 oraciones)
|
| 68 |
+
2. 3-4 recomendaciones específicas para mejorar el texto, identificando problemas concretos que has detectado
|
| 69 |
+
3. Un ejemplo concreto de cómo mejorar una frase del texto (si es posible)
|
|
|
|
| 70 |
|
| 71 |
+
Utiliza un tono profesional pero amigable, y estructura tus recomendaciones en HTML simple usando etiquetas <h4>, <p>, <ul>, <li>, y <strong>.
|
| 72 |
"""
|
| 73 |
|
| 74 |
# Llamada a la API de Claude
|
| 75 |
+
try:
|
| 76 |
+
message = client.messages.create(
|
| 77 |
+
model="claude-3-5-sonnet-20241022",
|
| 78 |
+
max_tokens=1000,
|
| 79 |
+
temperature=0.3,
|
| 80 |
+
system="Eres un asistente experto en análisis textual que proporciona recomendaciones claras y útiles para mejorar textos.",
|
| 81 |
+
messages=[
|
| 82 |
+
{"role": "user", "content": prompt}
|
| 83 |
+
]
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Obtener la respuesta
|
| 87 |
+
response = message.content[0].text
|
| 88 |
+
|
| 89 |
+
# Guardar en caché para uso futuro
|
| 90 |
+
cache_key = f"claude_recommendations_{text_type}_{weak_areas[0]}"
|
| 91 |
+
st.session_state[cache_key] = response
|
| 92 |
+
|
| 93 |
+
return response
|
| 94 |
+
|
| 95 |
+
except Exception as api_error:
|
| 96 |
+
logger.error(f"Error en la llamada a la API de Claude: {str(api_error)}")
|
| 97 |
+
return fallback_recommendations(weak_areas)
|
| 98 |
|
| 99 |
except Exception as e:
|
| 100 |
logger.error(f"Error generando recomendaciones con Claude: {str(e)}")
|
| 101 |
+
return fallback_recommendations(weak_areas)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
def fallback_recommendations(weak_areas):
|
| 104 |
+
"""Recomendaciones de respaldo en caso de fallo con la API"""
|
| 105 |
+
area_names = {
|
| 106 |
+
'vocabulary': 'vocabulario',
|
| 107 |
+
'structure': 'estructura',
|
| 108 |
+
'cohesion': 'cohesión',
|
| 109 |
+
'clarity': 'claridad'
|
| 110 |
+
}
|
| 111 |
|
| 112 |
+
return f"""
|
| 113 |
+
<h4>Recomendaciones para mejorar tu texto</h4>
|
| 114 |
+
<p>Hemos detectado que las áreas de <strong>{area_names.get(weak_areas[0], weak_areas[0])}</strong> y <strong>{area_names.get(weak_areas[1], weak_areas[1])}</strong>
|
| 115 |
+
son las que más podrían beneficiarse de mejoras.</p>
|
| 116 |
+
<p>Para obtener recomendaciones más detalladas, utiliza el asistente virtual de Claude AI
|
| 117 |
+
ubicado en la esquina superior izquierda (presiona la flecha junto al logo).</p>
|
| 118 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
def display_personalized_recommendations(text, metrics, text_type, lang_code, t):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
"""
|
| 122 |
+
Muestra recomendaciones personalizadas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|