Spaces:
Running
Running
File size: 11,006 Bytes
2ccbbde 17a4050 59c0e42 2ccbbde 2f6cb9d 17a4050 2ccbbde 59c0e42 17a4050 2ccbbde 17a4050 2ccbbde afffb8f d3dc3cf 230c394 17a4050 2ccbbde 17a4050 afffb8f 2ccbbde bc7102d afffb8f bc7102d 17a4050 2ccbbde 17a4050 2ccbbde 17a4050 2ccbbde 17a4050 2ccbbde 17a4050 2ccbbde 17a4050 2ccbbde 87724f5 dc22d85 87724f5 2ccbbde afffb8f 2ccbbde e70a84a d3dc3cf 350275a 2f6cb9d d3dc3cf 2f6cb9d d3dc3cf e70a84a 2f6cb9d 350275a d3dc3cf 4a74ca7 2ccbbde 17a4050 2ccbbde e70a84a afffb8f 2ccbbde 17a4050 2ccbbde d5cf61a 2ccbbde dc22d85 2ccbbde d3dc3cf 2ccbbde 5a58a0d 2ccbbde bc7102d 2ccbbde |
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 |
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
from style import styles
from prompts import create_instruction
from consciousness_levels import CONSCIOUSNESS_LEVELS
# Cargar las variables de entorno
load_dotenv()
# Configurar la API de Google
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Inicializar variables de estado en session_state si no existen
if 'perfil_cliente' not in st.session_state:
st.session_state.perfil_cliente = None
if 'producto' not in st.session_state:
st.session_state.producto = ""
if 'habilidades' not in st.session_state:
st.session_state.habilidades = ""
if 'creatividad' not in st.session_state:
st.session_state.creatividad = 1.0
if 'formato' not in st.session_state:
st.session_state.formato = "base_format"
if 'nivel_conciencia' not in st.session_state:
# Usar el primer nivel del diccionario como valor predeterminado
first_key = list(CONSCIOUSNESS_LEVELS.keys())[0]
st.session_state.nivel_conciencia = first_key.replace("_", " ")
# Función para generar el perfil de cliente ideal
@st.cache_resource
def get_model(temperature):
generation_config = {
"temperature": temperature,
}
return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config)
def generate_buyer_persona(product, skills, target_audience, temperature, consciousness_level="Ninguno", format_type="base_format"):
if not product or not skills:
return "Por favor, completa los campos de producto y habilidades."
try:
model = get_model(temperature)
instruction = create_instruction(
product_service=product,
skills=skills,
target_audience=target_audience,
consciousness_level=consciousness_level,
format_type=format_type
)
# Añadir instrucción explícita para respuesta en español
instruction += "\n\nIMPORTANTE: La respuesta debe estar completamente en español."
response = model.generate_content([instruction], generation_config={"temperature": temperature})
return response.parts[0].text if response and response.parts else "Error generando el perfil de cliente ideal."
except Exception as e:
return f"Error al generar el perfil: {str(e)}"
# Modificar la función update_profile para que no use spinner
def update_profile():
# Solo actualizar la variable de sesión
st.session_state.submitted = True
# Configurar la interfaz de usuario con Streamlit
st.set_page_config(page_title="Generador de Cliente Ideal", page_icon="👤", layout="wide")
# Leer el contenido del archivo manual.md si existe
try:
with open("manual.md", "r", encoding="utf-8") as file:
manual_content = file.read()
# Mostrar el contenido del manual en el sidebar
st.sidebar.markdown(manual_content)
except FileNotFoundError:
st.sidebar.warning("Manual not found. Please create a manual.md file.")
except Exception as e:
st.sidebar.error(f"Error loading manual: {str(e)}")
# Ocultar elementos de la interfaz
st.markdown(styles["main_layout"], unsafe_allow_html=True)
# Centrar el título y el subtítulo
st.markdown("<h1 style='text-align: center;'>Generador de Perfil de Cliente Ideal</h1>", unsafe_allow_html=True)
st.markdown("<h4 style='text-align: center;'>Crea un perfil detallado de tu cliente ideal basado en tu producto y habilidades.</h4>", unsafe_allow_html=True)
# Añadir CSS personalizado para el botón
st.markdown(styles["button"], unsafe_allow_html=True)
# Añadir CSS personalizado para el botón de descarga
st.markdown(styles["download_button"], unsafe_allow_html=True)
# Crear columnas
col1, col2 = st.columns([1, 2])
# Columna de entrada
with col1:
producto = st.text_area("¿Qué producto o servicio ofreces?",
value=st.session_state.producto,
placeholder="Ejemplo: Curso de Inglés",
key="producto_input",
height=70)
st.session_state.producto = producto
habilidades = st.text_area("¿Cuáles son tus habilidades principales?",
value=st.session_state.habilidades,
placeholder="Ejemplo: Enseñanza, comunicación, diseño de contenidos",
key="habilidades_input",
height=70)
st.session_state.habilidades = habilidades
# Botón para generar - Movido arriba del acordeón
submit = st.button("CREAR MI CLIENTE IDEAL SOÑADO ➤➤", on_click=update_profile)
# Crear un acordeón para las opciones de personalización
with st.expander("Personaliza Tu Cliente Ideal Soñado"):
# Nuevo campo para público objetivo
if 'publico_objetivo' not in st.session_state:
st.session_state.publico_objetivo = ""
publico_objetivo = st.text_area("¿Cuál es tu público objetivo? (opcional)",
value=st.session_state.publico_objetivo,
placeholder="Ejemplo: Profesionales entre 25-40 años interesados en desarrollo personal",
key="publico_objetivo_input",
height=70)
st.session_state.publico_objetivo = publico_objetivo
# Selector de formato
from format.format import buyer_persona_formats
# Obtener directamente las claves que terminan en "_format" del diccionario
format_keys = [key for key in buyer_persona_formats.keys() if key.endswith("_format")]
formato = st.selectbox(
"Formato del perfil",
options=format_keys,
format_func=lambda x: x.replace("_format", "").capitalize() + " format",
index=format_keys.index(st.session_state.formato) if st.session_state.formato in format_keys else 0,
help="Selecciona el formato en el que se presentará el perfil del cliente ideal"
)
st.session_state.formato = formato
# Nivel de creatividad con slider
creatividad = st.slider("Nivel de creatividad",
min_value=0.0,
max_value=2.0,
value=st.session_state.creatividad,
step=0.1,
key="creatividad_slider")
st.session_state.creatividad = creatividad
# Selector de nivel de conciencia
consciousness_options = []
for i, key in enumerate(CONSCIOUSNESS_LEVELS.keys(), 1):
# Replace underscores with spaces in the key
display_name = key.replace("_", " ")
consciousness_options.append(f"Nivel {i} - {display_name}")
nivel_conciencia_display = st.selectbox(
"Nivel de conciencia del cliente ideal",
consciousness_options,
index=0,
help="Selecciona el nivel de conciencia en el que se encuentra tu cliente ideal"
)
# Extract the original key from the display name
level_number = nivel_conciencia_display.split(" - ")[0].replace("Nivel ", "")
original_key = list(CONSCIOUSNESS_LEVELS.keys())[int(level_number) - 1]
nivel_conciencia = original_key.replace("_", " ")
# Get the description from the CONSCIOUSNESS_LEVELS dictionary
if original_key in CONSCIOUSNESS_LEVELS:
nivel_info = CONSCIOUSNESS_LEVELS[original_key]["estado_mental"]
st.info(f"**{nivel_conciencia}**: {nivel_info}")
st.session_state.nivel_conciencia = nivel_conciencia
# Columna de resultados
with col2:
# Verificar si se ha enviado el formulario
if 'submitted' in st.session_state and st.session_state.submitted:
if st.session_state.producto and st.session_state.habilidades:
with st.spinner("Creando tu Cliente Ideal Soñado..."):
# Generar el perfil del cliente
perfil_cliente = generate_buyer_persona(
st.session_state.producto,
st.session_state.habilidades,
st.session_state.publico_objetivo,
st.session_state.creatividad,
st.session_state.nivel_conciencia,
st.session_state.formato
)
# Guardar en session_state
st.session_state.perfil_cliente = perfil_cliente
# Resetear el estado de envío
st.session_state.submitted = False
# Mostrar resultados
if not isinstance(st.session_state.perfil_cliente, str):
st.error("Error al generar el perfil de cliente ideal")
else:
# Crear un contenedor con estilo personalizado
st.markdown(f"""
<style>
.results-box {{
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 20px;
}}
</style>
""", unsafe_allow_html=True)
# Usar un expander sin título para contener todo el resultado
with st.expander("", expanded=True):
st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
st.markdown(st.session_state.perfil_cliente)
# Opción para descargar
st.download_button(
label="DESCARGAR MI CLIENTE SOÑADO ➤➤",
data=st.session_state.perfil_cliente,
file_name="cliente_ideal.txt",
mime="text/plain"
)
else:
st.warning("Por favor, completa los campos de producto y habilidades antes de generar el perfil.")
# Mostrar resultados anteriores si existen
elif st.session_state.perfil_cliente:
# Crear un contenedor con estilo personalizado
st.markdown(f"""
<style>
.results-box {{
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 20px;
}}
</style>
""", unsafe_allow_html=True)
# Usar un expander sin título para contener todo el resultado
with st.expander("", expanded=True):
st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
st.markdown(st.session_state.perfil_cliente)
# Opción para descargar
st.download_button(
label="DESCARGAR MI CLIENTE SOÑADO ➤➤",
data=st.session_state.perfil_cliente,
file_name="cliente_ideal.txt",
mime="text/plain"
) |