JeCabrera commited on
Commit
17a4050
·
verified ·
1 Parent(s): 2704d1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -222
app.py CHANGED
@@ -1,223 +1,174 @@
1
- system_prompt = """You are an expert in creating ideal customer profiles, and your task is to help me create the perfect avatar for my product or service. You need to identify the customer who is attracted to my skills or the product/service I offer. This customer should be willing to invest in what I offer, keeping in mind their problems, frustrations, and desires.
2
-
3
- STEPS TO COMPLETE THE TASK:
4
-
5
- 1. **Determine the customer profile and their problems:**
6
- - First, understand who your ideal customer is through demographic data (age, gender, education, occupation, location) and psychographic information (values, beliefs, aspirations).
7
- - Identify what interests, hobbies, and activities they enjoy that relate to your product/service.
8
- - Determine what skills or interests you share with them that create a connection beyond the product itself.
9
- - Focus on **urgent** and specific problems that your product/service can solve for this customer.
10
- - The problem is what drives the purchase; identifying it will help niche the offer.
11
-
12
- 2. **Analyze their needs and decision-making process:**
13
- - Identify the **symptoms** that indicate the customer is facing the problem.
14
- - Understand their challenges and frustrations that make them seek your solution.
15
- - Determine what benefits they see in your offering and why your specific approach resonates with them.
16
- - Analyze their purchasing power and price sensitivity: How much can they spend? Are they willing to pay premium prices?
17
- - Examine how they make buying decisions: Do they research extensively? Are they influenced by reviews or recommendations?
18
-
19
- 3. **Create a comprehensive buyer persona:**
20
- - Use the information gathered from the previous steps to create a **detailed profile of the ideal customer**.
21
- - Include their motivations for buying and what they value most (price, quality, effectiveness, convenience).
22
- - Here are the points to follow:
23
-
24
- **[VARIABLES]**
25
- **Problems:**
26
- [Copy and paste the problem you are solving, usually the painful one]
27
-
28
- **[INSTRUCTION]**
29
- Create a buyer persona in the following format.
30
- Write the personality type (using their initials) from the 12 archetypes of Carlos Gustav Jung, what they value, what excites them, how they are, their fears, insecurities, guilt, frustrations, and problems, where they can be found, what they are willing to invest in, their interests, their desires, and what they really want.
31
-
32
- **IMPORTANT:**
33
- If there is a variable in **[VARIABLES]**, replace it in the format.
34
- Base your answers on real-life situations that the avatar would experience in their daily life.
35
- Use a natural, conversational language that feels authentic and relatable.
36
- Give the reasons why they want what they want. Use **[WHAT WE REALLY WANT]** to answer that section.
37
- Use Markdown formatting for the presentation.
38
- **[WHAT WE REALLY WANT]**
39
- - Increase our potential
40
- - Escape danger
41
- - Free ourselves from fear and guilt
42
- - Silence those who doubt us
43
- - Validate our feelings
44
- - Power over others
45
- - Advantages over our rivals
46
- - Be free from the consequences
47
- - Have more time dedicated to what we love
48
- - Less time dedicated to what we hate
49
- - Happiness and satisfaction
50
- - Prove we are right
51
- - Prove our detractors wrong
52
- - Be attractive and charming to others
53
- - Leave a lasting legacy
54
- - Higher status among our peers
55
- - Have a life full of comforts and luxuries
56
- - Be accepted by a social group or community
57
- - Be respected and admired for our intelligence, skills, or talents
58
- - Be true to ourselves and reach our full potential
59
- - Climb the social hierarchy
60
- - Establish close and lasting relationships with friends and family
61
- - Feel part of a group or community and be valued and appreciated by others
62
- - Be appreciated for our actions and receive gratitude from others
63
-
64
- **[FORMAT]**
65
- La persona **"[nombre del avatar]"** es **[género]** entre **[rango de edad]** que busca [lo que está buscando]. Es [lo que es y quiere].
66
-
67
- **Personalidad**: [su tipo de personalidad]
68
-
69
- **Valores**: [lo que valora]
70
-
71
- **Qué le emociona**: [lo que le emociona]
72
-
73
- **¿Cómo es?**: [cómo es]
74
-
75
- **Miedos**: [sus miedos]
76
-
77
- **Inseguridades**: [sus inseguridades]
78
-
79
- **Culpa**: [su culpa]
80
-
81
- **Problemas**: [sus problemas]
82
-
83
- **Frustraciones**: [sus frustraciones]
84
-
85
- **¿En qué está dispuesto/a a invertir?**: [en qué está dispuesto/a a invertir]
86
-
87
- **Intereses**: [sus intereses]
88
-
89
- **Deseos**: [sus deseos]
90
-
91
- **Lo que realmente quiere**: [lo que realmente quiere]
92
-
93
- **[EXAMPLE]**
94
- La persona **"Emprendedora Inspirada"** es una **mujer** entre **30 y 40 años** que busca alcanzar el éxito tanto en su vida personal como profesional. Es una **emprendedora independiente** que constantemente se esfuerza por construir su marca y hacer crecer su negocio, pero también está abierta a colaborar con otros para lograr sus objetivos.
95
-
96
- **Personalidad**: MAGA (MAG)
97
-
98
- **Valores**: ambición, innovación, aprendizaje continuo y autenticidad.
99
-
100
- **Qué le emociona**: su trabajo y encontrar siempre formas de mejorar tanto ella misma como su negocio. Le apasiona el emprendimiento y disfruta aprendiendo sobre estrategias de negocios, marketing digital y desarrollo personal. Se entusiasma cuando descubre nuevas tendencias que puede implementar.
101
-
102
- **¿Cómo es?**: Es una líder natural con una fuerte ética de trabajo y dedicación para alcanzar sus metas. Tiene un fuerte deseo de éxito y reconocimiento. No teme al trabajo duro y está dispuesta a asumir riesgos calculados en busca del éxito. Es metódica pero creativa, organizada pero flexible cuando la situación lo requiere.
103
-
104
- **Miedos**:
105
- - Observa cómo sus competidores crecen más rápido mientras ella siente que avanza lentamente
106
- - Revisa constantemente su agenda y se angustia al ver que no ha cumplido todos sus objetivos trimestrales
107
- - Pospone decisiones importantes por temor a equivocarse y perder lo construido
108
- - Cancela planes familiares para atender emergencias laborales, sintiendo que su vida personal se desvanece
109
- - Se compara con referentes de su industria y siente que nunca alcanzará su nivel de éxito
110
-
111
- **Inseguridades**:
112
- - Duda de sus capacidades cuando un cliente potencial elige a la competencia
113
- - Reescribe correos importantes múltiples veces antes de enviarlos
114
- - Evita hablar de ciertos temas en reuniones por miedo a no parecer suficientemente experta
115
- - Minimiza sus logros cuando recibe elogios, atribuyéndolos a la suerte o circunstancias externas
116
- - Posterga el lanzamiento de nuevos productos hasta que los considera "perfectos"
117
-
118
- **Culpa**:
119
- - Siente remordimiento cuando toma un fin de semana libre mientras sus competidores siguen trabajando
120
- - Se reprocha cuando invierte en un curso y no lo completa por falta de tiempo
121
- - Experimenta culpa al delegar tareas y luego revisa obsesivamente el trabajo realizado
122
- - Se siente mal cuando prioriza su bienestar sobre las demandas de clientes exigentes
123
- - Se castiga mentalmente por no haber implementado antes estrategias que ahora ve funcionando en otros negocios
124
-
125
- **Problemas**:
126
- - Sufre episodios de insomnio pensando en pendientes y estrategias para el día siguiente
127
- - Experimenta tensión en sus relaciones personales por su constante disponibilidad al trabajo
128
- - Acumula tareas operativas que podría delegar pero no confía en que otros las hagan correctamente
129
- - Posterga decisiones importantes sobre expansión por miedo a perder el control de la calidad
130
- - Se resiste a implementar cambios tecnológicos necesarios por temor a desestabilizar lo que ya funciona
131
- **Frustraciones**: Falta de progreso o crecimiento en su negocio o carrera, falta de reconocimiento o validación, desequilibrio entre su vida personal y profesional, falta de oportunidades para aprender y crecer, y falta de apoyo o colaboración. Le frustra cuando invierte tiempo y recursos en estrategias que no dan los resultados esperados.
132
-
133
- **¿En qué está dispuesta a invertir?**: En ella misma y en su negocio, ya sea tomando cursos, contratando coaches o consultores, o adquiriendo nuevas herramientas y tecnologías que le permitan optimizar su tiempo y mejorar sus resultados. Valora especialmente las inversiones que ofrecen un retorno claro y medible.
134
-
135
- **Intereses**: Mantenerse al día con las tendencias en su sector y adelantarse a la competencia. Le interesan los podcasts de negocios, libros de desarrollo personal, conferencias de emprendimiento y networking estratégico.
136
-
137
- **Deseos**: Tener un impacto positivo en el mundo, ya sea a través de su negocio o actividades personales. Aspira a crear un legado que trascienda lo económico y genere un cambio significativo en su industria o comunidad.
138
-
139
- **Lo que realmente quiere**: Lograr el éxito tanto en su vida personal como profesional para aumentar su potencial, vivir una vida llena de comodidades y lujos, ser respetada y admirada por sus habilidades y talentos, tener más tiempo para lo que ama y menos tiempo para lo que odia, ascender en la jerarquía social, y establecer relaciones cercanas y duraderas con amigos y familia. También busca validar sus sentimientos y demostrar que tiene razón a través de su éxito, escapar del peligro, y liberarse del miedo y la culpa que pueden impedirle alcanzar sus metas. Desea dejar un legado duradero y ser aceptada y apreciada por un grupo social o comunidad que comparta sus valores y aspiraciones.
140
-
141
- ---
142
- **Validation Questions for Your Ideal Customer Profile:**
143
-
144
- Have you addressed these essential aspects in your buyer persona?
145
-
146
- 1. **Demographics and Background:**
147
- - Have you defined their age, gender, education level, and location?
148
- - What is their current occupation and professional background?
149
- - What is their socioeconomic status and lifestyle?
150
-
151
- 2. **Psychographics and Values:**
152
- - What are their core values and beliefs?
153
- - What aspirations drive their decisions?
154
- - Which activities and interests align with your offering?
155
- - How do their interests overlap with your expertise?
156
-
157
- 3. **Problems and Needs:**
158
- - What specific problems are they trying to solve?
159
- - Which pain points are most urgent for them?
160
- - What frustrations are driving them to seek a solution?
161
- - How does your solution address their specific challenges?
162
-
163
- 4. **Purchase Behavior:**
164
- - What is their typical budget for similar solutions?
165
- - How do they evaluate purchase decisions?
166
- - What factors influence their buying choices?
167
- - Are they willing to invest in premium solutions?
168
-
169
- 5. **Decision-Making Process:**
170
- - Do they research thoroughly before buying?
171
- - What information sources do they trust?
172
- - How do reviews and recommendations influence them?
173
- - What convinces them of a product's value?
174
-
175
- Ensure your buyer persona thoroughly addresses these questions to create an accurate profile of someone who will value and invest in your offering.
176
- ---
177
-
178
- This prompt ensures the ideal customer aligns with your interests and skills and will be a good prospect for your products/services."""
179
- def create_instruction(product_service, skills, target_audience=None):
180
- # Preparar la información del público objetivo si se proporciona
181
- target_audience_info = ""
182
- if target_audience:
183
- target_audience_info = f"\n\nEl público objetivo específico es: {target_audience}. Asegúrate de que el perfil del cliente ideal se alinee con este público objetivo."
184
 
185
- return (
186
- f"{system_prompt}\n\n"
187
- f"Create a detailed buyer persona for someone who would be interested in {product_service} and would resonate with my skills in {skills}. Focus on identifying the ideal customer "
188
- f"who would value both the offering and my expertise.{target_audience_info}\n\n"
189
- f"Follow the format specified below, which integrates the Jungian archetypes more deeply into the persona structure. "
190
- f"Use the [EXAMPLE] as your base format but enhance it with the following structure:\n\n"
191
- f"**[FORMAT]**\n"
192
- f"## \"[Nombre basado en Arquetipo]\"\n\n"
193
- f"**Perfil Demográfico:** [género], [rango de edad], [ubicación], [educación], [ocupación], [nivel de ingresos]\n\n"
194
- f"**Arquetipo Junguiano:** [Arquetipo primario] con elementos de [Arquetipo secundario]\n"
195
- f"*[Breve explicación de cómo este arquetipo se manifiesta en su vida diaria y toma de decisiones]*\n\n"
196
- f"**Valores y Creencias Fundamentales:** [3-5 valores clave que impulsan sus decisiones]\n\n"
197
- f"**Escenarios de Vida Diaria:**\n"
198
- f"- *Mañana:* [Describe un escenario matutino típico que revele sus desafíos]\n"
199
- f"- *Jornada Laboral:* [Describe escenarios relacionados con el trabajo que destacan sus problemas]\n"
200
- f"- *Noche:* [Describe actividades nocturnas que muestran sus aspiraciones]\n\n"
201
- f"**Perfil Psicológico:**\n"
202
- f"- **Miedos:** [5 escenarios específicos donde se manifiestan sus miedos]\n"
203
- f"- **Inseguridades:** [5 comportamientos específicos que demuestran sus inseguridades]\n"
204
- f"- **Culpa:** [5 situaciones que desencadenan sentimientos de culpa]\n"
205
- f"- **Problemas:** [5 problemas concretos que enfrentan diariamente relacionados con {product_service}]\n"
206
- f"- **Frustraciones:** [5 frustraciones específicas que experimentan]\n\n"
207
- f"**Proceso de Toma de Decisiones:**\n"
208
- f"- **Hábitos de Investigación:** [Cómo recopilan información]\n"
209
- f"- **Factores de Confianza:** [Qué construye su confianza en una solución]\n"
210
- f"- **Objeciones:** [Objeciones comunes que podrían tener]\n"
211
- f"- **Disposición a Invertir:** [En qué están dispuestos a invertir y por qué]\n\n"
212
- f"**Viaje Arquetípico:**\n"
213
- f"- **Estado Actual:** [Dónde se encuentran ahora en su viaje del héroe]\n"
214
- f"- **Estado Deseado:** [Dónde quieren estar]\n"
215
- f"- **Obstáculos:** [Qué se interpone en su camino]\n"
216
- f"- **Ayudantes que Buscan:** [Qué tipo de guía/mentor necesitan]\n\n"
217
- f"**Lo que Realmente Quieren:** [Motivaciones psicológicas profundas de la lista [WHAT WE REALLY WANT], "
218
- f"conectadas explícitamente con su arquetipo]\n\n"
219
- f"IMPORTANTE: Presenta esto como una narrativa cohesiva que se sienta como una persona real, no solo una lista de atributos. "
220
- f"Establece conexiones específicas entre su arquetipo junguiano y sus comportamientos, problemas y deseos. "
221
- f"Proporciona SOLO el perfil del avatar del comprador sin análisis o comentarios adicionales. "
222
- f"La respuesta debe estar completamente en español."
223
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import streamlit as st
3
+ import os
4
+ import google.generativeai as genai
5
+ from style import styles
6
+ from prompts import create_instruction
7
+
8
+ # Cargar las variables de entorno
9
+ load_dotenv()
10
+
11
+ # Configurar la API de Google
12
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
13
+
14
+ # Inicializar variables de estado en session_state si no existen
15
+ if 'perfil_cliente' not in st.session_state:
16
+ st.session_state.perfil_cliente = None
17
+ if 'producto' not in st.session_state:
18
+ st.session_state.producto = ""
19
+ if 'habilidades' not in st.session_state:
20
+ st.session_state.habilidades = ""
21
+ if 'creatividad' not in st.session_state:
22
+ st.session_state.creatividad = 1.0
23
+
24
+ # Función para generar el perfil de cliente ideal
25
+ @st.cache_resource
26
+ def get_model(temperature):
27
+ generation_config = {
28
+ "temperature": temperature,
29
+ }
30
+ return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config)
31
+
32
+ def generate_buyer_persona(product, skills, target_audience, temperature):
33
+ if not product or not skills:
34
+ return "Por favor, completa los campos de producto y habilidades."
35
+
36
+ model = get_model(temperature)
37
+ instruction = create_instruction(
38
+ product_service=product,
39
+ skills=skills,
40
+ target_audience=target_audience
41
+ )
42
+
43
+ # Añadir instrucción explícita para respuesta en español
44
+ instruction += "\n\nIMPORTANTE: La respuesta debe estar completamente en español."
45
+
46
+ response = model.generate_content([instruction], generation_config={"temperature": temperature})
47
+ return response.parts[0].text if response and response.parts else "Error generando el perfil de cliente ideal."
48
+
49
+ # Modificar la función update_profile para que no use spinner
50
+ def update_profile():
51
+ # Solo actualizar la variable de sesión
52
+ st.session_state.submitted = True
53
+
54
+ # Configurar la interfaz de usuario con Streamlit
55
+ st.set_page_config(page_title="Generador de Cliente Ideal", page_icon="👤", layout="wide")
56
+
57
+ # Leer el contenido del archivo manual.md si existe
58
+ try:
59
+ with open("manual.md", "r", encoding="utf-8") as file:
60
+ manual_content = file.read()
61
+ # Mostrar el contenido del manual en el sidebar
62
+ st.sidebar.markdown(manual_content)
63
+ except FileNotFoundError:
64
+ st.sidebar.warning("Manual not found. Please create a manual.md file.")
65
+ except Exception as e:
66
+ st.sidebar.error(f"Error loading manual: {str(e)}")
67
+
68
+ # Ocultar elementos de la interfaz
69
+ st.markdown(styles["main_layout"], unsafe_allow_html=True)
70
+
71
+ # Centrar el título y el subtítulo
72
+ st.markdown("<h1 style='text-align: center;'>Generador de Perfil de Cliente Ideal</h1>", unsafe_allow_html=True)
73
+ 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)
74
+
75
+ # Añadir CSS personalizado para el botón
76
+ st.markdown(styles["button"], unsafe_allow_html=True)
77
+ # Añadir CSS personalizado para el botón de descarga
78
+ st.markdown(styles["download_button"], unsafe_allow_html=True)
79
+
80
+ # Crear columnas
81
+ col1, col2 = st.columns([1, 2])
82
+
83
+ # Columna de entrada
84
+ with col1:
85
+ producto = st.text_input("¿Qué producto o servicio ofreces?",
86
+ value=st.session_state.producto,
87
+ placeholder="Ejemplo: Curso de Inglés",
88
+ key="producto_input")
89
+ st.session_state.producto = producto
90
+
91
+ habilidades = st.text_input("¿Cuáles son tus habilidades principales?",
92
+ value=st.session_state.habilidades,
93
+ placeholder="Ejemplo: Enseñanza, comunicación, diseño de contenidos",
94
+ key="habilidades_input")
95
+ st.session_state.habilidades = habilidades
96
+
97
+ # Crear un acordeón para las opciones de personalización
98
+ with st.expander("Personaliza Tu Cliente Ideal Soñado"):
99
+ # Nuevo campo para público objetivo
100
+ if 'publico_objetivo' not in st.session_state:
101
+ st.session_state.publico_objetivo = ""
102
+
103
+ publico_objetivo = st.text_input("¿Cuál es tu público objetivo? (opcional)",
104
+ value=st.session_state.publico_objetivo,
105
+ placeholder="Ejemplo: Profesionales entre 25-40 años interesados en desarrollo personal",
106
+ key="publico_objetivo_input")
107
+ st.session_state.publico_objetivo = publico_objetivo
108
+
109
+ # Nivel de creatividad con slider
110
+ creatividad = st.slider("Nivel de creatividad",
111
+ min_value=0.0,
112
+ max_value=2.0,
113
+ value=st.session_state.creatividad,
114
+ step=0.1,
115
+ key="creatividad_slider")
116
+ st.session_state.creatividad = creatividad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ # Botón para generar
119
+ submit = st.button("GENERAR PERFIL DE CLIENTE IDEAL", on_click=update_profile)
120
+
121
+ # Columna de resultados
122
+ with col2:
123
+ # Verificar si se ha enviado el formulario
124
+ if 'submitted' in st.session_state and st.session_state.submitted:
125
+ if st.session_state.producto and st.session_state.habilidades:
126
+ with st.spinner("Creando tu Cliente Ideal Soñado..."):
127
+ # Generar el perfil del cliente
128
+ perfil_cliente = generate_buyer_persona(
129
+ st.session_state.producto,
130
+ st.session_state.habilidades,
131
+ st.session_state.publico_objetivo,
132
+ st.session_state.creatividad
133
+ )
134
+ # Guardar en session_state
135
+ st.session_state.perfil_cliente = perfil_cliente
136
+ # Resetear el estado de envío
137
+ st.session_state.submitted = False
138
+
139
+ # Mostrar resultados
140
+ if not isinstance(st.session_state.perfil_cliente, str):
141
+ st.error("Error al generar el perfil de cliente ideal")
142
+ else:
143
+ st.markdown(f"""
144
+ <div style="{styles['results_container']}">
145
+ <h3>Tu Cliente Ideal</h3>
146
+ {st.session_state.perfil_cliente}
147
+ </div>
148
+ """, unsafe_allow_html=True)
149
+
150
+ # Opción para descargar
151
+ st.download_button(
152
+ label="Descargar Perfil",
153
+ data=st.session_state.perfil_cliente,
154
+ file_name="cliente_ideal.md",
155
+ mime="text/markdown"
156
+ )
157
+ else:
158
+ st.warning("Por favor, completa los campos de producto y habilidades antes de generar el perfil.")
159
+ # Mostrar resultados anteriores si existen
160
+ elif st.session_state.perfil_cliente:
161
+ st.markdown(f"""
162
+ <div style="{styles['results_container']}">
163
+ <h3>Tu Cliente Ideal</h3>
164
+ {st.session_state.perfil_cliente}
165
+ </div>
166
+ """, unsafe_allow_html=True)
167
+
168
+ # Opción para descargar
169
+ st.download_button(
170
+ label="Descargar Perfil",
171
+ data=st.session_state.perfil_cliente,
172
+ file_name="cliente_ideal.md",
173
+ mime="text/markdown"
174
+ )