JeCabrera commited on
Commit
59c0e42
·
verified ·
1 Parent(s): 2a0a982

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -180
app.py CHANGED
@@ -1,197 +1,102 @@
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_area("¿Qué producto o servicio ofreces?",
86
- value=st.session_state.producto,
87
- placeholder="Ejemplo: Curso de Inglés",
88
- key="producto_input",
89
- height=70)
90
- st.session_state.producto = producto
91
-
92
- habilidades = st.text_area("¿Cuáles son tus habilidades principales?",
93
- value=st.session_state.habilidades,
94
- placeholder="Ejemplo: Enseñanza, comunicación, diseño de contenidos",
95
- key="habilidades_input",
96
- height=70)
97
- st.session_state.habilidades = habilidades
98
-
99
- # Crear un acordeón para las opciones de personalización
100
- with st.expander("Personaliza Tu Cliente Ideal Soñado"):
101
- # Nuevo campo para público objetivo
102
- if 'publico_objetivo' not in st.session_state:
103
- st.session_state.publico_objetivo = ""
104
-
105
- publico_objetivo = st.text_area("¿Cuál es tu público objetivo? (opcional)",
106
- value=st.session_state.publico_objetivo,
107
- placeholder="Ejemplo: Profesionales entre 25-40 años interesados en desarrollo personal",
108
- key="publico_objetivo_input",
109
- height=70)
110
- st.session_state.publico_objetivo = publico_objetivo
111
-
112
- # Nivel de creatividad con slider
113
- creatividad = st.slider("Nivel de creatividad",
114
- min_value=0.0,
115
- max_value=2.0,
116
- value=st.session_state.creatividad,
117
- step=0.1,
118
- key="creatividad_slider")
119
- st.session_state.creatividad = creatividad
120
-
121
- # Botón para generar
122
- submit = st.button("GENERAR PERFIL DE CLIENTE IDEAL", on_click=update_profile)
123
 
124
- # Columna de resultados
125
  with col2:
126
- # Verificar si se ha enviado el formulario
127
- if 'submitted' in st.session_state and st.session_state.submitted:
128
- if st.session_state.producto and st.session_state.habilidades:
129
- with st.spinner("Creando tu Cliente Ideal Soñado..."):
130
- # Generar el perfil del cliente
131
- perfil_cliente = generate_buyer_persona(
132
- st.session_state.producto,
133
- st.session_state.habilidades,
134
- st.session_state.publico_objetivo,
135
- st.session_state.creatividad
136
- )
137
- # Guardar en session_state
138
- st.session_state.perfil_cliente = perfil_cliente
139
- # Resetear el estado de envío
140
- st.session_state.submitted = False
141
 
142
- # Mostrar resultados
143
- if not isinstance(st.session_state.perfil_cliente, str):
144
- st.error("Error al generar el perfil de cliente ideal")
145
- else:
146
- # Crear un contenedor con estilo personalizado
147
- st.markdown(f"""
148
- <style>
149
- .results-box {{
150
- padding: 15px;
151
- border: 1px solid #ddd;
152
- border-radius: 8px;
153
- margin-bottom: 20px;
154
- }}
155
- </style>
156
- """, unsafe_allow_html=True)
157
 
158
- # Usar un expander sin título para contener todo el resultado
159
- with st.expander("", expanded=True):
160
- st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
161
- st.markdown(st.session_state.perfil_cliente)
162
-
163
- # Opción para descargar
164
- st.download_button(
165
- label="Descargar Perfil",
166
- data=st.session_state.perfil_cliente,
167
- file_name="cliente_ideal.txt",
168
- mime="text/plain"
169
- )
170
- else:
171
- st.warning("Por favor, completa los campos de producto y habilidades antes de generar el perfil.")
172
- # Mostrar resultados anteriores si existen
173
- elif st.session_state.perfil_cliente:
174
- # Crear un contenedor con estilo personalizado
175
- st.markdown(f"""
176
- <style>
177
- .results-box {{
178
- padding: 15px;
179
- border: 1px solid #ddd;
180
- border-radius: 8px;
181
- margin-bottom: 20px;
182
- }}
183
- </style>
184
- """, unsafe_allow_html=True)
185
-
186
- # Usar un expander sin título para contener todo el resultado
187
- with st.expander("", expanded=True):
188
- st.markdown("<h3>Tu Cliente Ideal</h3>", unsafe_allow_html=True)
189
- st.markdown(st.session_state.perfil_cliente)
190
-
191
- # Opción para descargar
192
- st.download_button(
193
- label="Descargar Perfil",
194
- data=st.session_state.perfil_cliente,
195
- file_name="cliente_ideal.md",
196
- mime="text/markdown"
197
- )
 
 
1
  import streamlit as st
 
2
  import google.generativeai as genai
3
+ import os
4
+ from dotenv import load_dotenv
5
+ from styles import get_custom_css
 
 
 
 
 
6
 
7
+ # Set page to wide mode to use full width
8
+ st.set_page_config(layout="wide")
 
 
 
 
 
 
 
9
 
10
+ # Load environment variables
11
+ load_dotenv()
 
 
 
 
 
12
 
13
+ # Configure Google Gemini API
14
+ genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
15
+ model = genai.GenerativeModel('gemini-2.0-flash')
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Initialize session state variables if they don't exist
18
+ if 'submitted' not in st.session_state:
19
+ st.session_state.submitted = False
20
+ if 'offer_result' not in st.session_state:
21
+ st.session_state.offer_result = ""
22
 
23
+ # Hide Streamlit menu and footer
24
+ st.markdown("""
25
+ <style>
26
+ #MainMenu {visibility: hidden;}
27
+ footer {visibility: hidden;}
28
+ header {visibility: hidden;}
29
+ </style>
30
+ """, unsafe_allow_html=True)
31
 
32
+ # Custom CSS
33
+ st.markdown(get_custom_css(), unsafe_allow_html=True)
 
 
 
 
 
 
 
 
34
 
35
+ # App title and description
36
+ st.title('🚀 Great Offer Generator')
37
+ st.markdown('''### Transform your skills into compelling offers!''')
38
 
39
+ # Create two columns for layout - left column 40%, right column 60%
40
+ col1, col2 = st.columns([4, 6])
 
41
 
42
+ # Main input section in left column
43
+ with col1:
44
+ skills = st.text_area('💪 Your Skills', height=70,
45
+ help='List your key skills and expertise')
46
+ product_service = st.text_area('🎯 Product/Service', height=70,
47
+ help='Describe your product or service')
48
 
49
+ # Accordion for additional settings
50
+ with st.expander('⚙️ Advanced Settings'):
51
+ target_audience = st.text_area('👥 Target Audience', height=70,
52
+ help='Describe your ideal customer or client')
53
+ temperature = st.slider('🌡️ Creativity Level', min_value=0.0, max_value=2.0, value=0.7,
54
+ help='Higher values make the output more creative but less focused')
55
 
56
+ # Generate button with callback
57
+ def generate_offer():
58
+ if not skills or not product_service:
59
+ st.error('Please fill in both Skills and Product/Service fields')
60
+ else:
61
+ # Set submitted flag to True
62
+ st.session_state.submitted = True
63
+ # Store input values in session state
64
+ st.session_state.skills = skills
65
+ st.session_state.product_service = product_service
66
+ st.session_state.target_audience = target_audience
67
+ st.session_state.temperature = temperature
68
+
69
+ st.button('Generate Offer 🎉', on_click=generate_offer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # Results column
72
  with col2:
73
+ # Check if form has been submitted
74
+ if st.session_state.submitted:
75
+ with st.spinner('Creating your perfect offer...'):
76
+ prompt = f"""Based on the following information, create a compelling offer:
77
+ Skills: {st.session_state.skills}
78
+ Product/Service: {st.session_state.product_service}
79
+ Target Audience: {st.session_state.target_audience if st.session_state.target_audience else 'General audience'}
80
+
81
+ Please create a professional and engaging offer that highlights the value proposition
82
+ and appeals to the target audience. Include a clear call to action."""
83
+
84
+ try:
85
+ # Create generation config with temperature
86
+ generation_config = genai.GenerationConfig(temperature=st.session_state.temperature)
 
87
 
88
+ # Pass the generation config to generate_content
89
+ response = model.generate_content(prompt, generation_config=generation_config)
90
+ st.session_state.offer_result = response.text
91
+ st.success('✨ Your offer is ready!')
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ # Display result
94
+ st.markdown('### 📝 Generated Offer')
95
+ st.markdown(st.session_state.offer_result)
96
+ except Exception as e:
97
+ st.error(f'An error occurred: {str(e)}')
98
+ st.session_state.submitted = False
99
+
100
+ # Footer
101
+ st.markdown('---')
102
+ st.markdown('Made with ❤️ by Jesús Cabrera')