Spaces:
Runtime error
Runtime error
File size: 12,096 Bytes
c76bbac 348d961 ae5207e 348d961 ae5207e 348d961 ae5207e 348d961 ae5207e 348d961 c76bbac 6d6ad89 c76bbac fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 c76bbac d8f563a 15d4fae d8f563a 6a4a20b c76bbac 6a4a20b c76bbac 6a4a20b c76bbac 6a4a20b c76bbac 6a4a20b c76bbac fa423f3 274e6d4 299bb98 fa423f3 c76bbac 299bb98 c76bbac 299bb98 c76bbac fa423f3 c76bbac fa423f3 299bb98 fa423f3 299bb98 c76bbac fa423f3 299bb98 c76bbac 299bb98 fa423f3 299bb98 15ab203 299bb98 fa423f3 299bb98 15ab203 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 fa423f3 299bb98 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
import time
import os
import joblib
import streamlit as st
import google.generativeai as genai
from dotenv import load_dotenv
# Función para cargar CSS personalizado
def load_css(file_path):
with open(file_path) as f:
st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
# Intentar cargar el CSS personalizado con ruta absoluta para mayor seguridad
try:
css_path = os.path.join(os.path.dirname(__file__), 'static', 'css', 'style.css')
load_css(css_path)
except Exception as e:
print(f"Error al cargar CSS: {e}")
# Si el archivo no existe, crear un estilo básico en línea
st.markdown("""
<style>
.robocopy-title {
color: #4ECDC4 !important;
font-weight: bold;
font-size: 2em;
}
</style>
""", unsafe_allow_html=True)
load_dotenv()
GOOGLE_API_KEY=os.environ.get('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
new_chat_id = f'{time.time()}'
MODEL_ROLE = 'ai'
AI_AVATAR_ICON = '🤖' # Cambia el emoji por uno de robot para coincidir con tu logo
USER_AVATAR_ICON = '👤' # Añade un avatar para el usuario
# Definición del prompt multipersona para el sistema
SYSTEM_PROMPT = """
Eres un equipo colaborativo de expertos de clase mundial trabajando juntos para crear Propuestas Únicas de Valor (PUVs) excepcionales que conviertan a la audiencia en clientes.
EL EQUIPO DE EXPERTOS:
1. ESTRATEGA MAESTRO DE MARKETING:
- Experto en marcos de propuestas de valor y estrategias de conversión
- Asegura que las PUVs sigan la estructura de fórmula seleccionada con precisión
- Se enfoca en la colocación estratégica de elementos clave de conversión
2. COPYWRITER ELITE DE RESPUESTA DIRECTA:
- Crea ganchos, historias y elementos persuasivos convincentes
- Elabora propuestas de valor irresistibles que impulsan conversiones
- Asegura que el lenguaje resuene con la audiencia objetivo
3. ESPECIALISTA EN PSICOLOGÍA DE AUDIENCIA:
- Experto en comprender las motivaciones y objeciones de la audiencia
- Crea contenido que construye conexión genuina y confianza
- Identifica y aborda miedos y deseos ocultos
4. MAESTRO DE DIFERENCIACIÓN:
- Crea propuestas únicas que destacan entre la competencia
- Desarrolla ejemplos y casos de estudio relacionables
- Asegura que las PUVs apoyen la transformación que se ofrece
5. EXPERTO EN CONVERSIÓN:
- Se especializa en crear PUVs que mantengan la atención y generen acción
- Crea elementos interactivos y ganchos de engagement
- Asegura que las PUVs fluyan naturalmente y mantengan el interés alto
"""
# Mensaje de bienvenida mejorado
WELCOME_MESSAGE = """
# 🚀 ¡Bienvenido! Soy RoboCopy, tu creador de PUVs 🚀
Soy un experto en crear **Propuestas Únicas de Valor (PUVs)** que transforman visitantes en clientes.
## 💼 ¿Qué puedo hacer por ti?
Creo PUVs persuasivas que:
- **Capturan la atención** de tu audiencia ideal
- **Comunican claramente** el valor de tu oferta
- **Convierten visitantes** en clientes leales
## 📋 Para ayudarte, necesito conocer:
1️⃣ **Tu producto o servicio**: ¿Qué ofreces exactamente?
2️⃣ **Tu audiencia objetivo**: ¿Quiénes son tus clientes ideales?
3️⃣ **La fórmula que prefieres**:
- **A) Problema-Solución**: "Para [audiencia] con [problema], [producto] proporciona [solución]"
- **B) Antes-Después**: "Transforma [situación actual] en [situación deseada]"
- **C) Beneficio Principal**: "[Producto] te ayuda a [beneficio] sin [obstáculo]"
Analizaré tu audiencia, identificaré los beneficios clave y crearé TRES propuestas de valor potentes.
**¡Comencemos!** Comparte los detalles de tu producto/servicio, audiencia y fórmula preferida.
"""
# Create a data/ folder if it doesn't already exist
try:
os.mkdir('data/')
except:
# data/ folder already exists
pass
# Load past chats (if available)
try:
past_chats: dict = joblib.load('data/past_chats_list')
except:
past_chats = {}
# Sidebar allows a list of past chats
with st.sidebar:
# Centrar el logo y eliminar el título de RoboCopy
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.image("assets/robocopy_logo.png", width=300)
st.write('# Chats Anteriores')
if st.session_state.get('chat_id') is None:
st.session_state.chat_id = st.selectbox(
label='Selecciona un chat anterior',
options=[new_chat_id] + list(past_chats.keys()),
format_func=lambda x: past_chats.get(x, 'Nuevo Chat'),
placeholder='_',
)
else:
# This will happen the first time AI response comes in
st.session_state.chat_id = st.selectbox(
label='Selecciona un chat anterior',
options=[new_chat_id, st.session_state.chat_id] + list(past_chats.keys()),
index=1,
format_func=lambda x: past_chats.get(x, 'Nuevo Chat' if x != st.session_state.chat_id else st.session_state.chat_title),
placeholder='_',
)
# Inicializar el título de chat si es necesario
if st.session_state.get('chat_title') is None:
if st.session_state.chat_id in past_chats:
st.session_state.chat_title = past_chats[st.session_state.chat_id]
else:
st.session_state.chat_title = 'Nuevo Chat'
st.write('# Creador de Propuestas Únicas de Valor')
# Inicializar mensajes y cargar historial
if not st.session_state.get('messages'):
st.session_state.messages = []
# Cargar historial de chat si existe
try:
st.session_state.messages = joblib.load(f'data/{st.session_state.chat_id}-st_messages')
st.session_state.gemini_history = joblib.load(f'data/{st.session_state.chat_id}-gemini_messages')
print('old cache')
except:
if not st.session_state.get('messages'):
st.session_state.messages = []
st.session_state.gemini_history = []
print('new_cache made')
# Configuración del modelo
model = genai.GenerativeModel(model_name='gemini-2.0-flash')
st.session_state.model = model
st.session_state.chat = st.session_state.model.start_chat(history=st.session_state.gemini_history)
# Si es un chat nuevo, enviar el prompt del sistema como primer mensaje
if not st.session_state.gemini_history:
# Enviamos el prompt del sistema como primer mensaje (invisible para el usuario)
st.session_state.chat.send_message(SYSTEM_PROMPT)
st.session_state.gemini_history = st.session_state.chat.history
# Mostrar mensajes del historial
for message in st.session_state.messages:
with st.chat_message(name=message['role'], avatar=message.get('avatar')):
st.markdown(message['content'])
# React to user input
if prompt := st.chat_input('¿En qué puedo ayudarte hoy?'):
# Verificar si es el primer mensaje del usuario
is_first_message = len(st.session_state.messages) == 0
# Guardar información del chat
if st.session_state.chat_id not in past_chats.keys():
# Es una nueva conversación, generamos un título basado en el primer mensaje
temp_title = f'SesiónChat-{st.session_state.chat_id}'
past_chats[st.session_state.chat_id] = temp_title
# Generamos un título basado en el contenido del mensaje
try:
title_generator = genai.GenerativeModel('gemini-2.0-flash')
title_response = title_generator.generate_content(
f"Genera un título corto (máximo 5 palabras) que describa de qué trata esta consulta, sin usar comillas ni puntuación: '{prompt}'")
generated_title = title_response.text.strip()
if generated_title:
st.session_state.chat_title = generated_title
past_chats[st.session_state.chat_id] = generated_title
else:
st.session_state.chat_title = temp_title
except Exception as e:
print(f"Error al generar título: {e}")
st.session_state.chat_title = temp_title
else:
# Ya existe esta conversación, usamos el título guardado
st.session_state.chat_title = past_chats[st.session_state.chat_id]
joblib.dump(past_chats, 'data/past_chats_list')
# Mostrar mensaje del usuario
with st.chat_message('user', avatar=USER_AVATAR_ICON):
st.markdown(prompt)
# Añadir mensaje del usuario al historial
st.session_state.messages.append({
'role': 'user',
'content': prompt,
})
# Si es el primer mensaje, mostrar el mensaje de bienvenida
if is_first_message:
with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
st.markdown(WELCOME_MESSAGE)
st.session_state.messages.append({
'role': MODEL_ROLE,
'content': WELCOME_MESSAGE,
'avatar': AI_AVATAR_ICON,
})
# Guardar el historial actualizado
joblib.dump(st.session_state.messages, f'data/{st.session_state.chat_id}-st_messages')
# Salir de la función para no procesar más este mensaje
st.experimental_rerun()
# Implementación de reintentos con retroceso exponencial
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
# Enviar mensaje al modelo
response = st.session_state.chat.send_message(prompt, stream=True)
# Mostrar respuesta del asistente
with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
message_placeholder = st.empty()
full_response = ''
# Indicador de escritura
typing_indicator = st.empty()
typing_indicator.markdown("*Estoy analizando tu información...*")
# Mostrar respuesta por fragmentos
for chunk in response:
for ch in chunk.text.split(' '):
full_response += ch + ' '
time.sleep(0.1)
message_placeholder.write(full_response + '▌')
# Eliminar indicador y mostrar respuesta completa
typing_indicator.empty()
message_placeholder.write(full_response)
# Añadir respuesta al historial
st.session_state.messages.append({
'role': MODEL_ROLE,
'content': st.session_state.chat.history[-1].parts[0].text,
'avatar': AI_AVATAR_ICON,
})
# Actualizar historial
st.session_state.gemini_history = st.session_state.chat.history
# Guardar historial
joblib.dump(st.session_state.messages, f'data/{st.session_state.chat_id}-st_messages')
joblib.dump(st.session_state.gemini_history, f'data/{st.session_state.chat_id}-gemini_messages')
# Salir del bucle si la solicitud fue exitosa
break
except Exception as e:
retry_count += 1
if retry_count >= max_retries:
# Mostrar mensaje de error si se agotan los reintentos
with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
st.error(f"Lo siento, estoy experimentando problemas para procesar tu solicitud. Por favor, intenta de nuevo más tarde. Error: {str(e)}")
st.session_state.messages.append({
'role': MODEL_ROLE,
'content': f"Lo siento, estoy experimentando problemas para procesar tu solicitud. Por favor, intenta de nuevo más tarde. Error: {str(e)}",
'avatar': AI_AVATAR_ICON,
})
joblib.dump(st.session_state.messages, f'data/{st.session_state.chat_id}-st_messages')
else:
# Esperar antes de reintentar (retroceso exponencial)
wait_time = (2 ** retry_count) + (time.time() % 1)
time.sleep(wait_time) |