JeCabrera commited on
Commit
6f7d8a1
·
verified ·
1 Parent(s): 6088248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -358
app.py CHANGED
@@ -1,363 +1,253 @@
1
- buyer_persona_formats = {
2
- "Jung's_Avatar": {
3
- "template": """
4
- La persona **"[nombre del avatar]"** es **[género]** entre **[rango de edad]** que busca [lo que está buscando]. Es [lo que es y quiere].
5
-
6
- **Arquetipo principal (Jung)**: [Especificar uno de los 12 arquetipos principales] - [Explicar cómo se manifiesta este arquetipo en su personalidad]
7
-
8
- **Arquetipo secundario**: [Especificar un segundo arquetipo que complemente al principal] - [Explicar cómo este arquetipo secundario matiza o complementa al principal]
9
-
10
- **Sombra**: [Describir los aspectos reprimidos o negados de su personalidad según la teoría junguiana]
11
-
12
- **Valores fundamentales**: [3-5 valores centrales que guían sus decisiones]
13
-
14
- **Qué le emociona**: [Lo que le genera entusiasmo y motivación profunda]
15
-
16
- **Nivel de conciencia**: [Nivel de conciencia sobre su problema]
17
-
18
- **Miedos**:
19
- • [Miedo principal relacionado con su arquetipo]
20
-
21
- • [Miedo secundario]
22
-
23
- • [Miedo terciario]
24
-
25
- **Inseguridades**:
26
- • [Inseguridad principal relacionada con su sombra]
27
-
28
- • [Inseguridad secundaria]
29
-
30
- • [Inseguridad terciaria]
31
-
32
- **Culpa**:
33
- • [Sentimiento de culpa principal]
34
-
35
- • [Sentimiento de culpa secundario]
36
-
37
- • [Sentimiento de culpa terciario]
38
-
39
- **Problemas**:
40
- • [Problema principal que enfrenta]
41
-
42
- • [Problema secundario]
43
-
44
- • [Problema terciario]
45
-
46
- **Frustraciones**:
47
- • [Frustración principal relacionada con su arquetipo]
48
-
49
- • [Frustración secundaria]
50
-
51
- • [Frustración terciaria]
52
-
53
- **Dónde encontrarlo**: [Lugares físicos y digitales donde se puede encontrar a este cliente ideal]
54
-
55
- **Dispuesto a invertir en**: [Productos, servicios o experiencias en los que está dispuesto a gastar dinero]
56
-
57
- **Intereses**: [Intereses y actividades que reflejan su arquetipo principal y secundario]
58
-
59
- **Deseos conscientes**:
60
- • [Deseo principal que expresa abiertamente]
61
-
62
- • [Deseo secundario]
63
-
64
- • [Deseo terciario]
65
-
66
- **Lo que realmente quiere**:
67
-
68
- **Su gran deseo profundo**: [El deseo arquetípico fundamental que impulsa a esta persona a nivel emocional profundo]
69
-
70
- **Sus 7 motivaciones ocultas**:
71
- 1. [Motivación relacionada con su arquetipo principal]
72
- 2. [Motivación relacionada con su arquetipo secundario]
73
- 3. [Motivación relacionada con su sombra]
74
- 4. [Motivación relacionada con su búsqueda de individuación]
75
- 5. [Motivación relacionada con sus miedos]
76
- 6. [Motivación relacionada con sus aspiraciones]
77
- 7. [Motivación relacionada con su necesidad de pertenencia o reconocimiento]
78
- """,
79
- "description": """
80
- **Formato Jung Avatar**
81
-
82
- Este formato se basa en la psicología analítica de Carl Jung y utiliza arquetipos para crear un perfil profundo y psicológicamente fundamentado del cliente ideal.
83
-
84
- **Características principales:**
85
- - Incorpora arquetipos junguianos para entender las motivaciones profundas
86
- - Explora la "sombra" o aspectos reprimidos de la personalidad
87
- - Analiza valores, miedos e inseguridades desde una perspectiva psicológica
88
- - Identifica tanto deseos conscientes como motivaciones inconscientes
89
-
90
- **Ideal para:**
91
- - Productos o servicios que abordan necesidades emocionales profundas
92
- - Ofertas premium que requieren una conexión psicológica fuerte
93
- - Cuando necesitas entender las motivaciones inconscientes de tus clientes
94
- """,
95
- "example": """
96
- La persona **"Carlos"** es **hombre** entre **35-45 años** que busca mejorar su inglés para avanzar en su carrera profesional. Es un profesional ambicioso pero inseguro sobre sus habilidades lingüísticas.
97
-
98
- **Arquetipo principal (Jung)**: Héroe - Se manifiesta en su determinación para superar obstáculos y en su deseo constante de probarse a sí mismo en el ámbito profesional. Busca el reconocimiento a través del logro y la superación personal.
99
-
100
- **Arquetipo secundario**: Sabio - Complementa su naturaleza heroica con una genuina sed de conocimiento. Valora la información y el aprendizaje como herramientas para alcanzar sus metas.
101
-
102
- **Sombra**: Miedo al fracaso que puede manifestarse como procrastinación o excusas para no practicar inglés. Cuando está estresado, puede volverse arrogante para ocultar sus inseguridades.
103
-
104
- **Valores fundamentales**: Excelencia, crecimiento profesional, reconocimiento, seguridad económica, aprendizaje continuo.
105
-
106
- **Qué le emociona**: Los avances tangibles en su dominio del inglés, recibir reconocimiento de colegas y superiores, imaginar nuevas oportunidades profesionales.
107
-
108
- **Nivel de conciencia**: Consciente del problema - Reconoce que su falta de fluidez en inglés está limitando su crecimiento profesional, pero no sabe exactamente cómo resolverlo de manera efectiva.
109
-
110
- **Miedos**:
111
- • Quedarse estancado profesionalmente por no dominar el inglés
112
-
113
- • Hacer el ridículo al hablar inglés en reuniones importantes
114
-
115
- • Invertir tiempo y dinero sin obtener resultados
116
-
117
- **Inseguridades**:
118
- • Cree que es "malo para los idiomas" por experiencias pasadas
119
-
120
- • Siente que es demasiado mayor para aprender un nuevo idioma efectivamente
121
-
122
- • Duda de su capacidad para mantener la disciplina necesaria
123
-
124
- **Culpa**:
125
- • No haber aprovechado oportunidades previas para aprender inglés
126
-
127
- • Haber rechazado proyectos internacionales por su limitación con el idioma
128
-
129
- • Sentir que está defraudando a su familia al no alcanzar su potencial
130
-
131
- **Problemas**:
132
- • No puede acceder a mejores posiciones que requieren inglés fluido
133
-
134
- • Se siente excluido en reuniones con clientes o colegas internacionales
135
-
136
- • Pierde oportunidades de networking en eventos globales
137
-
138
- **Frustraciones**:
139
- • Métodos tradicionales que ha probado no han funcionado
140
-
141
- • Falta de tiempo para estudiar con su agenda ocupada
142
-
143
- • Progreso lento a pesar de sus esfuerzos
144
-
145
- **Dónde encontrarlo**: LinkedIn, grupos de networking profesional, conferencias de su industria, plataformas de e-learning, podcasts de desarrollo profesional.
146
-
147
- **Dispuesto a invertir en**: Cursos que prometan resultados rápidos y aplicables, coaching personalizado, herramientas tecnológicas que faciliten el aprendizaje, programas que se adapten a su agenda.
148
-
149
- **Intereses**: Desarrollo profesional, tecnología, tendencias de su industria, podcasts de negocios, aplicaciones de productividad.
150
-
151
- **Deseos conscientes**:
152
- • Hablar inglés con fluidez en contextos profesionales
153
-
154
- • Conseguir un ascenso o mejor posición laboral
155
-
156
- • Aumentar su red de contactos internacionales
157
-
158
- **Lo que realmente quiere**:
159
-
160
- **Su gran deseo profundo**: Sentirse competente y valioso en un mundo globalizado. Más allá de hablar inglés, Carlos anhela profundamente validar su valía profesional y personal. El idioma representa para él la llave que abre la puerta a un sentido de pertenencia en el ámbito profesional internacional que admira. Su lucha con el inglés simboliza una batalla más profunda contra sus inseguridades y su temor de no estar a la altura de sus propias expectativas y las de los demás.
161
-
162
- **Sus 7 motivaciones ocultas**:
163
- 1. Demostrar a sí mismo y a quienes dudaron de él que puede superar cualquier obstáculo
164
- 2. Obtener la admiración y respeto de colegas y superiores al dominar una habilidad que percibe como difícil
165
- 3. Liberarse del sentimiento de inferioridad cuando interactúa en ambientes internacionales
166
- 4. Reconciliar su autoimagen como persona capaz y exitosa con sus limitaciones actuales
167
- 5. Protegerse del miedo a la obsolescencia profesional en un mercado cada vez más globalizado
168
- 6. Satisfacer su necesidad de control sobre su futuro profesional
169
- 7. Alcanzar un sentido de pertenencia en círculos profesionales de mayor prestigio
170
- """
171
- }
172
- }
173
 
174
- # Estas variables deben estar fuera del diccionario principal
175
- bullet_format_instructions = """
176
- \n\nIMPORTANT - LIST FORMAT:
177
- For the sections of Fears, Insecurities, Guilt, Problems, and Frustrations, use BULLET POINTS (•) with PROPER PARAGRAPH BREAKS after each item.
178
-
179
- Example:
180
- Miedos:
181
- • Miedo a quedarse atrás en el mercado por no dominar nuevas tecnologías.
182
-
183
- • Temor a perder oportunidades de negocio por barreras de comunicación.
184
-
185
- • Preocupación por no poder expandir su empresa internacionalmente.
186
-
187
- The correct format is (note the empty line between each bullet point):
188
- Culpa:
189
- • Se siente culpable por no pasar suficiente tiempo con su hijo debido al trabajo.
190
-
191
- • Siente remordimiento por no haber aprendido inglés antes y ahora tener que hacerlo a la fuerza.
192
-
193
- • Experimenta culpa al gastar dinero en un curso de inglés en lugar de en otras necesidades de su hijo.
194
-
195
- • Se siente mal por no poder ayudar a su hijo con sus tareas de inglés.
196
-
197
- DO NOT use this incorrect format (without paragraph breaks):
198
- Inseguridades: • Primera inseguridad • Segunda inseguridad • Tercera inseguridad
199
-
200
- ALSO DO NOT use this incorrect format (without empty lines between items):
201
- Problemas:
202
- • Tiene dificultades para encontrar tiempo para estudiar inglés debido a su trabajo y responsabilidades familiares.
203
- • Se siente abrumado por la cantidad de información y recursos disponibles para aprender inglés.
204
- • Le resulta difícil concentrarse y mantenerse motivado para estudiar después de un largo día de trabajo.
205
-
206
- ENSURE there is an EMPTY LINE between each bullet point to create proper paragraph separation.
207
- DO NOT use hyphens (-) or numbers for these lists.
208
- """
209
 
210
- # Instrucciones para niveles de conciencia
211
- consciousness_level_instructions = """
212
- \n\nABSOLUTELY CRITICAL - CONSCIOUSNESS LEVEL MAPPING:
213
- You MUST use the EXACT consciousness level from this mapping:
214
-
215
- - If user selects "Desconocido" → Use "Desconocido" in your response
216
- - If user selects "Consciente del problema" → Use "Consciente del problema" in your response
217
- - If user selects "Consciente de la solución" → Use "Consciente de la solución" in your response
218
- - If user selects "Consciente del producto" → Use "Consciente del producto" in your response
219
- - If user selects "Consciente de la compra" → Use "Consciente de la compra" in your response
220
-
221
- DO NOT DEVIATE from this mapping under any circumstances.
222
-
223
- For "Desconocido" level:
224
- - The person is completely unaware they have a problem
225
- - They don't recognize any need for change
226
- - They are not actively looking for solutions
227
- - Their fears and frustrations exist but they don't connect them to this specific problem
228
-
229
- For "Consciente del problema" level:
230
- - The person knows they have a problem
231
- - They feel the pain and recognize the issue
232
- - They don't yet know what solutions exist
233
- - They are beginning to research and understand their problem
234
-
235
- For "Consciente de la solución" level:
236
- - The person knows what type of solution they need
237
- - They are actively comparing different options
238
- - They understand how solutions work but haven't chosen one
239
- - They are evaluating features, benefits, and pricing
240
-
241
- For "Consciente del producto" level:
242
- - The person knows about your specific product/service
243
- - They are considering it but haven't decided to purchase
244
- - They may have objections or concerns about your offering
245
- - They need convincing about your specific solution
246
-
247
- For "Consciente de la compra" level:
248
- - The person is ready to buy
249
- - They need a final push or incentive
250
- - They are looking for validation of their decision
251
- - They may need help with the purchasing process
252
-
253
- The "Nivel de conciencia" section in your response MUST follow this exact format:
254
- **Nivel de conciencia**: [EXACT MAPPED LEVEL] - [explanation consistent with that level]
255
-
256
- ALL other aspects of the persona (fears, problems, etc.) MUST be consistent with the specified consciousness level.
257
- """
258
 
259
- # Lo que realmente queremos (motivaciones profundas)
260
- what_we_really_want = {
261
- "list": [
262
- "Increase our potential",
263
- "Escape danger",
264
- "Free ourselves from fear and guilt",
265
- "Silence those who doubt us",
266
- "Validate our feelings",
267
- "Power over others",
268
- "Advantages over our rivals",
269
- "Be free from the consequences",
270
- "Have more time dedicated to what we love",
271
- "Less time dedicated to what we hate",
272
- "Happiness and satisfaction",
273
- "Prove we are right",
274
- "Prove our detractors wrong",
275
- "Be attractive and charming to others",
276
- "Leave a lasting legacy",
277
- "Higher status among our peers",
278
- "Have a life full of comforts and luxuries",
279
- "Be accepted by a social group or community",
280
- "Be respected and admired for our intelligence, skills, or talents",
281
- "Be true to ourselves and reach our full potential",
282
- "Climb the social hierarchy",
283
- "Establish close and lasting relationships with friends and family",
284
- "Feel part of a group or community and be valued and appreciated by others",
285
- "Be appreciated for our actions and receive gratitude from others"
286
- ],
287
- "format": """
288
- **[WHAT WE REALLY WANT]**
289
- - Increase our potential
290
- - Escape danger
291
- - Free ourselves from fear and guilt
292
- - Silence those who doubt us
293
- - Validate our feelings
294
- - Power over others
295
- - Advantages over our rivals
296
- - Be free from the consequences
297
- - Have more time dedicated to what we love
298
- - Less time dedicated to what we hate
299
- - Happiness and satisfaction
300
- - Prove we are right
301
- - Prove our detractors wrong
302
- - Be attractive and charming to others
303
- - Leave a lasting legacy
304
- - Higher status among our peers
305
- - Have a life full of comforts and luxuries
306
- - Be accepted by a social group or community
307
- - Be respected and admired for our intelligence, skills, or talents
308
- - Be true to ourselves and reach our full potential
309
- - Climb the social hierarchy
310
- - Establish close and lasting relationships with friends and family
311
- - Feel part of a group or community and be valued and appreciated by others
312
- - Be appreciated for our actions and receive gratitude from others
313
- """
314
  }
 
315
 
316
- validation_questions = {
317
- "buyer_persona": """
318
- ---
319
- **Validation Questions for Your Ideal Customer Profile:**
320
-
321
- Have you addressed these essential aspects in your buyer persona?
322
-
323
- 1. **Demographics and Background:**
324
- - Have you defined their age, gender, education level, and location?
325
- - What is their current occupation and professional background?
326
- - What is their socioeconomic status and lifestyle?
327
-
328
- 2. **Psychographics and Values:**
329
- - What are their core values and beliefs?
330
- - What aspirations drive their decisions?
331
- - Which activities and interests align with your offering?
332
- - How do their interests overlap with your expertise?
333
-
334
- 3. **Problems and Needs:**
335
- - What specific problems are they trying to solve?
336
- - Which pain points are most urgent for them?
337
- - What frustrations are driving them to seek a solution?
338
- - How does your solution address their specific challenges?
339
-
340
- 4. **Purchase Behavior:**
341
- - What is their typical budget for similar solutions?
342
- - How do they evaluate purchase decisions?
343
- - What factors influence their buying choices?
344
- - Are they willing to invest in premium solutions?
345
-
346
- 5. **Decision-Making Process:**
347
- - Do they research thoroughly before buying?
348
- - What information sources do they trust?
349
- - How do reviews and recommendations influence them?
350
- - What convinces them of a product's value?
351
-
352
- 6. **Consciousness Level:**
353
- - Does the avatar clearly reflect one of the five consciousness levels?
354
- - Are their fears, problems, and frustrations consistent with their consciousness level?
355
- - Does their language and way of expressing themselves correspond to their consciousness level about the problem?
356
- - Are their objections and doubts appropriate for their consciousness level?
357
- - Is the type of information they seek consistent with their consciousness level?
358
- - Do their decision criteria adequately reflect their consciousness level?
359
-
360
- Ensure your buyer persona thoroughly addresses these questions to create an accurate profile of someone who will value and invest in your offering.
361
- ---
362
- """
363
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ # Configurar la interfaz de usuario con Streamlit - MUST BE FIRST!
3
+ st.set_page_config(page_title="Generador de Cliente Ideal", page_icon="👤", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ from dotenv import load_dotenv
6
+ import os
7
+ import google.generativeai as genai
8
+ from style import styles
9
+ from prompts import create_instruction
10
+ from consciousness_levels import CONSCIOUSNESS_LEVELS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Cargar las variables de entorno
13
+ load_dotenv()
14
+
15
+ # Configurar la API de Google
16
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Inicializar variables de estado en session_state si no existen
19
+ if 'perfil_cliente' not in st.session_state:
20
+ st.session_state.perfil_cliente = None
21
+ if 'producto' not in st.session_state:
22
+ st.session_state.producto = ""
23
+ if 'habilidades' not in st.session_state:
24
+ st.session_state.habilidades = ""
25
+ if 'creatividad' not in st.session_state:
26
+ st.session_state.creatividad = 1.0
27
+ # Update the default format in session state
28
+ if 'formato' not in st.session_state:
29
+ st.session_state.formato = "Jung's_Avatar" # Changed from previous format name
30
+ if 'nivel_conciencia' not in st.session_state:
31
+ # Usar el primer nivel del diccionario como valor predeterminado
32
+ first_key = list(CONSCIOUSNESS_LEVELS.keys())[0]
33
+ st.session_state.nivel_conciencia = first_key.replace("_", " ")
34
+
35
+ # Función para generar el perfil de cliente ideal
36
+ @st.cache_resource
37
+ def get_model(temperature):
38
+ generation_config = {
39
+ "temperature": temperature,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
+ return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config)
42
 
43
+ # REMOVED: The format selection dropdown that was here
44
+
45
+ def generate_buyer_persona(product, skills, target_audience, temperature, consciousness_level="Ninguno", format_type="Jung's_Avatar"):
46
+ if not product or not skills:
47
+ return "Por favor, completa los campos de producto y habilidades."
48
+
49
+ try:
50
+ model = get_model(temperature)
51
+ instruction = create_instruction(
52
+ product_service=product,
53
+ skills=skills,
54
+ target_audience=target_audience,
55
+ consciousness_level=consciousness_level,
56
+ format_type=format_type
57
+ )
58
+
59
+ # Añadir instrucción explícita para respuesta en español
60
+ instruction += "\n\nIMPORTANTE: La respuesta debe estar completamente en español."
61
+
62
+ response = model.generate_content([instruction], generation_config={"temperature": temperature})
63
+ return response.parts[0].text if response and response.parts else "Error generando el perfil de cliente ideal."
64
+ except Exception as e:
65
+ return f"Error al generar el perfil: {str(e)}"
66
+
67
+ # Modificar la función update_profile para que no use spinner
68
+ def update_profile():
69
+ # Solo actualizar la variable de sesión
70
+ st.session_state.submitted = True
71
+
72
+ # Leer el contenido del archivo manual.md si existe
73
+ try:
74
+ with open("manual.md", "r", encoding="utf-8") as file:
75
+ manual_content = file.read()
76
+ # Mostrar el contenido del manual en el sidebar
77
+ st.sidebar.markdown(manual_content)
78
+ except FileNotFoundError:
79
+ st.sidebar.warning("Manual not found. Please create a manual.md file.")
80
+ except Exception as e:
81
+ st.sidebar.error(f"Error loading manual: {str(e)}")
82
+
83
+ # Ocultar elementos de la interfaz
84
+ st.markdown(styles["main_layout"], unsafe_allow_html=True)
85
+
86
+ # Centrar el título y el subtítulo
87
+ st.markdown("<h1 style='text-align: center;'>Generador de Perfil de Cliente Ideal</h1>", unsafe_allow_html=True)
88
+ 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)
89
+
90
+ # Añadir CSS personalizado para el botón
91
+ st.markdown(styles["button"], unsafe_allow_html=True)
92
+ # Añadir CSS personalizado para el botón de descarga
93
+ st.markdown(styles["download_button"], unsafe_allow_html=True)
94
+
95
+ # Crear columnas
96
+ col1, col2 = st.columns([1, 2])
97
+
98
+ # Columna de entrada
99
+ with col1:
100
+ producto = st.text_area("¿Qué producto o servicio ofreces?",
101
+ value=st.session_state.producto,
102
+ placeholder="Ejemplo: Curso de Inglés",
103
+ key="producto_input",
104
+ height=70)
105
+ st.session_state.producto = producto
106
+
107
+ habilidades = st.text_area("¿Cuáles son tus habilidades principales?",
108
+ value=st.session_state.habilidades,
109
+ placeholder="Ejemplo: Enseñanza, comunicación, diseño de contenidos",
110
+ key="habilidades_input",
111
+ height=70)
112
+ st.session_state.habilidades = habilidades
113
+
114
+ # Botón para generar - Movido arriba del acordeón
115
+ submit = st.button("CREAR MI CLIENTE IDEAL SOÑADO ➤➤", on_click=update_profile)
116
+
117
+ # Crear un acordeón para las opciones de personalización
118
+ with st.expander("Personaliza Tu Cliente Ideal Soñado"):
119
+ # Nuevo campo para público objetivo
120
+ if 'publico_objetivo' not in st.session_state:
121
+ st.session_state.publico_objetivo = ""
122
+
123
+ publico_objetivo = st.text_area("¿Cuál es tu público objetivo? (opcional)",
124
+ value=st.session_state.publico_objetivo,
125
+ placeholder="Ejemplo: Profesionales entre 25-40 años interesados en desarrollo personal",
126
+ key="publico_objetivo_input",
127
+ height=70)
128
+ st.session_state.publico_objetivo = publico_objetivo
129
+
130
+ # Selector de formato
131
+ from format.format import buyer_persona_formats
132
+
133
+ # Usar directamente las claves del diccionario sin filtrar
134
+ formato = st.selectbox(
135
+ "Formato del perfil",
136
+ options=list(buyer_persona_formats.keys()),
137
+ format_func=lambda x: x.capitalize(),
138
+ index=list(buyer_persona_formats.keys()).index(st.session_state.formato) if st.session_state.formato in buyer_persona_formats else 0,
139
+ help="Selecciona el formato en el que se presentará el perfil del cliente ideal"
140
+ )
141
+ st.session_state.formato = formato
142
+
143
+ # Nivel de creatividad con slider
144
+ creatividad = st.slider("Nivel de creatividad",
145
+ min_value=0.0,
146
+ max_value=2.0,
147
+ value=st.session_state.creatividad,
148
+ step=0.1,
149
+ key="creatividad_slider")
150
+ st.session_state.creatividad = creatividad
151
+
152
+ # Selector de nivel de conciencia
153
+ consciousness_options = []
154
+ for i, key in enumerate(CONSCIOUSNESS_LEVELS.keys(), 1):
155
+ # Replace underscores with spaces in the key
156
+ display_name = key.replace("_", " ")
157
+ consciousness_options.append(f"Nivel {i} - {display_name}")
158
+
159
+ nivel_conciencia_display = st.selectbox(
160
+ "Nivel de conciencia del cliente ideal",
161
+ consciousness_options,
162
+ index=0,
163
+ help="Selecciona el nivel de conciencia en el que se encuentra tu cliente ideal"
164
+ )
165
+
166
+ # Extract the original key from the display name
167
+ level_number = nivel_conciencia_display.split(" - ")[0].replace("Nivel ", "")
168
+ original_key = list(CONSCIOUSNESS_LEVELS.keys())[int(level_number) - 1]
169
+ nivel_conciencia = original_key.replace("_", " ")
170
+
171
+ # Get the description from the CONSCIOUSNESS_LEVELS dictionary
172
+ if original_key in CONSCIOUSNESS_LEVELS:
173
+ nivel_info = CONSCIOUSNESS_LEVELS[original_key]["estado_mental"]
174
+ st.info(f"**{nivel_conciencia}**: {nivel_info}")
175
+
176
+ st.session_state.nivel_conciencia = nivel_conciencia
177
+
178
+ # Columna de resultados
179
+ with col2:
180
+ # Verificar si se ha enviado el formulario
181
+ if 'submitted' in st.session_state and st.session_state.submitted:
182
+ if st.session_state.producto and st.session_state.habilidades:
183
+ with st.spinner("Creando tu Cliente Ideal Soñado..."):
184
+ # Generar el perfil del cliente
185
+ perfil_cliente = generate_buyer_persona(
186
+ st.session_state.producto,
187
+ st.session_state.habilidades,
188
+ st.session_state.publico_objetivo,
189
+ st.session_state.creatividad,
190
+ st.session_state.nivel_conciencia,
191
+ st.session_state.formato
192
+ )
193
+ # Guardar en session_state
194
+ st.session_state.perfil_cliente = perfil_cliente
195
+ # Resetear el estado de envío
196
+ st.session_state.submitted = False
197
+
198
+ # Mostrar resultados
199
+ if not isinstance(st.session_state.perfil_cliente, str):
200
+ st.error("Error al generar el perfil de cliente ideal")
201
+ else:
202
+ # Crear un contenedor con estilo personalizado
203
+ st.markdown(f"""
204
+ <style>
205
+ .results-box {{
206
+ padding: 15px;
207
+ border: 1px solid #ddd;
208
+ border-radius: 8px;
209
+ margin-bottom: 20px;
210
+ }}
211
+ </style>
212
+ """, unsafe_allow_html=True)
213
+
214
+ # Usar un expander sin título para contener todo el resultado
215
+ with st.expander("", expanded=True):
216
+ st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
217
+ st.markdown(st.session_state.perfil_cliente)
218
+
219
+ # Opción para descargar
220
+ st.download_button(
221
+ label="DESCARGAR MI CLIENTE SOÑADO ➤➤",
222
+ data=st.session_state.perfil_cliente,
223
+ file_name="cliente_ideal.txt",
224
+ mime="text/plain"
225
+ )
226
+ else:
227
+ st.warning("Por favor, completa los campos de producto y habilidades antes de generar el perfil.")
228
+ # Mostrar resultados anteriores si existen
229
+ elif st.session_state.perfil_cliente:
230
+ # Crear un contenedor con estilo personalizado
231
+ st.markdown(f"""
232
+ <style>
233
+ .results-box {{
234
+ padding: 15px;
235
+ border: 1px solid #ddd;
236
+ border-radius: 8px;
237
+ margin-bottom: 20px;
238
+ }}
239
+ </style>
240
+ """, unsafe_allow_html=True)
241
+
242
+ # Usar un expander sin título para contener todo el resultado
243
+ with st.expander("", expanded=True):
244
+ st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
245
+ st.markdown(st.session_state.perfil_cliente)
246
+
247
+ # Opción para descargar
248
+ st.download_button(
249
+ label="DESCARGAR MI CLIENTE SOÑADO ➤➤",
250
+ data=st.session_state.perfil_cliente,
251
+ file_name="cliente_ideal.txt",
252
+ mime="text/plain"
253
+ )