Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,8 +5,7 @@ import joblib
|
|
| 5 |
import streamlit as st
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
from streamlit.runtime.scriptrunner import get_script_run_ctx
|
| 8 |
-
from system_prompts import
|
| 9 |
-
from reel_formulas import reel_formulas
|
| 10 |
from session_state import (
|
| 11 |
SessionState,
|
| 12 |
DEFAULT_GEMINI_MODEL,
|
|
@@ -98,65 +97,20 @@ def handle_chat_title(prompt):
|
|
| 98 |
state.chat_title = past_chats[state.chat_id]
|
| 99 |
joblib.dump(past_chats, user_past_chats_list_path)
|
| 100 |
|
| 101 |
-
def detect_formula_selection(prompt):
|
| 102 |
-
"""Detecta si el usuario eligió una fórmula por nombre o por número."""
|
| 103 |
-
normalized_prompt = prompt.lower().strip()
|
| 104 |
-
formula_names = list(reel_formulas.keys())
|
| 105 |
-
|
| 106 |
-
# Selección por número (1, 2, 3...)
|
| 107 |
-
if normalized_prompt.isdigit():
|
| 108 |
-
formula_index = int(normalized_prompt) - 1
|
| 109 |
-
if 0 <= formula_index < len(formula_names):
|
| 110 |
-
return formula_names[formula_index]
|
| 111 |
-
|
| 112 |
-
# Selección por nombre parcial/completo
|
| 113 |
-
for formula_name in formula_names:
|
| 114 |
-
if formula_name.lower() in normalized_prompt:
|
| 115 |
-
return formula_name
|
| 116 |
-
|
| 117 |
-
return None
|
| 118 |
-
|
| 119 |
-
def get_user_context_for_formula(max_user_messages=6):
|
| 120 |
-
"""Recupera contexto reciente del usuario para rellenar la fórmula elegida."""
|
| 121 |
-
recent_user_messages = [
|
| 122 |
-
m['content'] for m in state.messages
|
| 123 |
-
if m.get('role') == 'user'
|
| 124 |
-
][-max_user_messages:]
|
| 125 |
-
return "\n".join(f"- {message}" for message in recent_user_messages)
|
| 126 |
-
|
| 127 |
-
def build_formula_prompt(formula_name):
|
| 128 |
-
"""Construye un prompt estricto usando la fórmula del diccionario."""
|
| 129 |
-
formula_data = reel_formulas[formula_name]
|
| 130 |
-
formula_description = formula_data.get('description', '').strip()
|
| 131 |
-
user_context = get_user_context_for_formula()
|
| 132 |
-
|
| 133 |
-
return f"""
|
| 134 |
-
El usuario eligió explícitamente esta fórmula: "{formula_name}".
|
| 135 |
-
|
| 136 |
-
APLICA ESTRICTAMENTE la siguiente estructura:
|
| 137 |
-
{formula_description}
|
| 138 |
-
|
| 139 |
-
Contexto real del usuario (úsalo para personalizar el guion):
|
| 140 |
-
{user_context if user_context else '- Sin contexto previo suficiente.'}
|
| 141 |
-
|
| 142 |
-
Instrucciones obligatorias de salida:
|
| 143 |
-
1) Devuelve SOLO el texto final del Reel (sin encabezados ni etiquetas).
|
| 144 |
-
2) Respeta el orden y los pasos de la fórmula elegida.
|
| 145 |
-
3) Incluye un gancho potente y un cierre con llamado a la acción.
|
| 146 |
-
4) Que tenga longitud aproximada de 60 segundos al leer.
|
| 147 |
-
"""
|
| 148 |
-
|
| 149 |
def get_enhanced_prompt(prompt, is_example):
|
| 150 |
"""Genera el prompt mejorado según el tipo de mensaje"""
|
| 151 |
-
selected_formula = detect_formula_selection(prompt)
|
| 152 |
-
if selected_formula:
|
| 153 |
-
st.session_state.selected_formula = selected_formula
|
| 154 |
-
return build_formula_prompt(selected_formula)
|
| 155 |
-
|
| 156 |
if is_greeting(prompt):
|
| 157 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
elif is_example:
|
| 159 |
-
return
|
|
|
|
|
|
|
|
|
|
| 160 |
return prompt
|
| 161 |
|
| 162 |
def stream_response(response, message_placeholder, typing_indicator, stream_settings):
|
|
@@ -233,7 +187,7 @@ def display_initial_header():
|
|
| 233 |
# Título con diseño responsivo (eliminado el símbolo ∞)
|
| 234 |
st.markdown("""
|
| 235 |
<div style='text-align: center; margin-top: -35px; width: 100%;'>
|
| 236 |
-
<h1 class='robocopy-title' style='width: 100%; text-align: center; color: white !important; font-size: clamp(2.5em, 5vw, 4em); line-height: 1.2;'>
|
| 237 |
</div>
|
| 238 |
""", unsafe_allow_html=True)
|
| 239 |
|
|
@@ -248,7 +202,7 @@ def display_initial_header():
|
|
| 248 |
st.markdown("""
|
| 249 |
<div style='text-align: center; width: 100%;'>
|
| 250 |
<p style='font-size: 16px; background-color: transparent; padding: 12px; border-radius: 8px; margin-top: -20px; color: white; width: 100%; text-align: center;'>
|
| 251 |
-
|
| 252 |
</p>
|
| 253 |
</div>
|
| 254 |
""", unsafe_allow_html=True)
|
|
@@ -256,10 +210,10 @@ def display_initial_header():
|
|
| 256 |
# Función para mostrar ejemplos de preguntas
|
| 257 |
def display_examples():
|
| 258 |
ejemplos = [
|
| 259 |
-
{"texto": "
|
| 260 |
-
{"texto": "Ideas
|
| 261 |
-
{"texto": "
|
| 262 |
-
{"texto": "
|
| 263 |
]
|
| 264 |
|
| 265 |
# Crear los botones de ejemplo
|
|
@@ -351,7 +305,7 @@ elif st.session_state.active_chat_id != state.chat_id:
|
|
| 351 |
st.session_state.hide_initial_menu = state.has_messages()
|
| 352 |
|
| 353 |
# Inicializar el modelo y el chat
|
| 354 |
-
system_prompt =
|
| 355 |
state.initialize_model(DEFAULT_GEMINI_MODEL, api_key=GOOGLE_API_KEY)
|
| 356 |
state.initialize_chat(system_instruction=system_prompt) # Siempre inicializar el chat después del modelo
|
| 357 |
|
|
@@ -364,7 +318,7 @@ for message in state.messages:
|
|
| 364 |
st.markdown(message['content'])
|
| 365 |
|
| 366 |
# Capturar entrada del usuario antes de renderizar el menú inicial
|
| 367 |
-
user_prompt = st.chat_input('
|
| 368 |
|
| 369 |
if state.has_messages():
|
| 370 |
st.session_state.hide_initial_menu = True
|
|
|
|
| 5 |
import streamlit as st
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
from streamlit.runtime.scriptrunner import get_script_run_ctx
|
| 8 |
+
from system_prompts import get_unified_email_prompt
|
|
|
|
| 9 |
from session_state import (
|
| 10 |
SessionState,
|
| 11 |
DEFAULT_GEMINI_MODEL,
|
|
|
|
| 97 |
state.chat_title = past_chats[state.chat_id]
|
| 98 |
joblib.dump(past_chats, user_past_chats_list_path)
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
def get_enhanced_prompt(prompt, is_example):
|
| 101 |
"""Genera el prompt mejorado según el tipo de mensaje"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
if is_greeting(prompt):
|
| 103 |
+
return (
|
| 104 |
+
"Responde ÚNICAMENTE con esta frase, sin agregar nada más: "
|
| 105 |
+
"\"Estoy listo para crear tu email. Por favor, proporcióname dos cosas: "
|
| 106 |
+
"1. La anécdota, situación u observación que quieres usar. "
|
| 107 |
+
"2. El producto que quieres promover.\""
|
| 108 |
+
)
|
| 109 |
elif is_example:
|
| 110 |
+
return (
|
| 111 |
+
f"El usuario ha seleccionado un ejemplo: '{prompt}'. "
|
| 112 |
+
"Primero solicita anécdota y producto. No generes el email final hasta tener ambos."
|
| 113 |
+
)
|
| 114 |
return prompt
|
| 115 |
|
| 116 |
def stream_response(response, message_placeholder, typing_indicator, stream_settings):
|
|
|
|
| 187 |
# Título con diseño responsivo (eliminado el símbolo ∞)
|
| 188 |
st.markdown("""
|
| 189 |
<div style='text-align: center; margin-top: -35px; width: 100%;'>
|
| 190 |
+
<h1 class='robocopy-title' style='width: 100%; text-align: center; color: white !important; font-size: clamp(2.5em, 5vw, 4em); line-height: 1.2;'>Email Story Creator</h1>
|
| 191 |
</div>
|
| 192 |
""", unsafe_allow_html=True)
|
| 193 |
|
|
|
|
| 202 |
st.markdown("""
|
| 203 |
<div style='text-align: center; width: 100%;'>
|
| 204 |
<p style='font-size: 16px; background-color: transparent; padding: 12px; border-radius: 8px; margin-top: -20px; color: white; width: 100%; text-align: center;'>
|
| 205 |
+
✉️ Experto en emails narrativos que conectan historias con ventas de forma natural
|
| 206 |
</p>
|
| 207 |
</div>
|
| 208 |
""", unsafe_allow_html=True)
|
|
|
|
| 210 |
# Función para mostrar ejemplos de preguntas
|
| 211 |
def display_examples():
|
| 212 |
ejemplos = [
|
| 213 |
+
{"texto": "Estructura base de email ✍️", "prompt": "Enséñame la estructura ideal para un email de storytelling que convierta sin sonar a venta agresiva"},
|
| 214 |
+
{"texto": "Ideas de anécdotas 💡", "prompt": "Ayúdame a encontrar anécdotas cotidianas que pueda transformar en emails de marketing"},
|
| 215 |
+
{"texto": "Mejorar mi CTA 📩", "prompt": "Quiero llamadas a la acción contextuales y naturales para cerrar mejor mis emails"},
|
| 216 |
+
{"texto": "Conectar historia y producto 🔗", "prompt": "Muéstrame cómo construir un puente narrativo lógico entre una historia y mi producto"}
|
| 217 |
]
|
| 218 |
|
| 219 |
# Crear los botones de ejemplo
|
|
|
|
| 305 |
st.session_state.hide_initial_menu = state.has_messages()
|
| 306 |
|
| 307 |
# Inicializar el modelo y el chat
|
| 308 |
+
system_prompt = get_unified_email_prompt()
|
| 309 |
state.initialize_model(DEFAULT_GEMINI_MODEL, api_key=GOOGLE_API_KEY)
|
| 310 |
state.initialize_chat(system_instruction=system_prompt) # Siempre inicializar el chat después del modelo
|
| 311 |
|
|
|
|
| 318 |
st.markdown(message['content'])
|
| 319 |
|
| 320 |
# Capturar entrada del usuario antes de renderizar el menú inicial
|
| 321 |
+
user_prompt = st.chat_input('Comparte tu anécdota y el producto que quieres promover...')
|
| 322 |
|
| 323 |
if state.has_messages():
|
| 324 |
st.session_state.hide_initial_menu = True
|