JeCabrera commited on
Commit
c3a5730
·
verified ·
1 Parent(s): b85b822

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -29
app.py CHANGED
@@ -17,7 +17,7 @@ load_dotenv()
17
 
18
  # Configure Google Gemini API
19
  genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
20
- model = genai.GenerativeModel('gemini-1.5-flash') # Updated to model that supports images
21
 
22
  # Initialize session state variables if they don't exist
23
  if 'submitted' not in st.session_state:
@@ -37,7 +37,7 @@ header {visibility: hidden;}
37
  # Custom CSS
38
  st.markdown(get_custom_css(), unsafe_allow_html=True)
39
 
40
- # App title and description - centered and without emoji
41
  st.markdown('<h1 style="text-align: center;">Great Offer Generator</h1>', unsafe_allow_html=True)
42
  st.markdown('<h3 style="text-align: center;">Transform your skills into compelling offers!</h3>', unsafe_allow_html=True)
43
 
@@ -46,7 +46,6 @@ col1, col2 = st.columns([4, 6])
46
 
47
  # Main input section in left column
48
  with col1:
49
- # Add tabs for different input methods
50
  input_tab1, input_tab2, input_tab3 = st.tabs(["Entrada Manual", "Subir Archivo", "Subir Imagen"])
51
 
52
  with input_tab1:
@@ -58,11 +57,9 @@ with col1:
58
  with input_tab2:
59
  uploaded_file = st.file_uploader("Sube un archivo con tu información", type=['txt', 'pdf', 'docx'])
60
  if uploaded_file is not None:
61
- # Handle different file types
62
  file_type = uploaded_file.name.split('.')[-1].lower()
63
 
64
  if file_type == 'txt':
65
- # Read text file
66
  file_content = uploaded_file.read().decode('utf-8')
67
  st.success(f"Archivo cargado correctamente: {uploaded_file.name}")
68
 
@@ -88,18 +85,15 @@ with col1:
88
  st.error(f"Error al leer el archivo DOCX: {str(e)}")
89
  file_content = ""
90
 
91
- # Display preview of file content
92
  with st.expander("Vista previa del contenido"):
93
  st.write(file_content[:500] + "..." if len(file_content) > 500 else file_content)
94
 
95
  with input_tab3:
96
  uploaded_image = st.file_uploader("Sube una imagen de tu producto o servicio", type=['jpg', 'jpeg', 'png'])
97
  if uploaded_image is not None:
98
- # Display the uploaded image
99
  image = Image.open(uploaded_image)
100
  st.image(image, caption="Imagen cargada", use_container_width=True)
101
 
102
- # Convert to format for Gemini
103
  image_bytes = uploaded_image.getvalue()
104
  image_parts = [
105
  {
@@ -109,40 +103,33 @@ with col1:
109
  ]
110
  st.success(f"Imagen cargada correctamente: {uploaded_image.name}")
111
 
112
- # Accordion for additional settings
113
  with st.expander('⚙️ Configuración Avanzada'):
114
  target_audience = st.text_area('👥 Público Objetivo', height=70,
115
  help='Describe tu cliente o público ideal')
116
 
117
- # Selector de fórmula
118
  formula_type = st.selectbox(
119
  '📋 Tipo de Fórmula',
120
  options=list(offer_formulas.keys()),
121
  help='Selecciona el tipo de fórmula para tu oferta'
122
  )
123
 
124
- # Removed the "Ver detalles de la fórmula" expander section
125
-
126
  temperature = st.slider('🌡️ Nivel de Creatividad', min_value=0.0, max_value=2.0, value=0.7,
127
  help='Valores más altos hacen que el resultado sea más creativo pero menos enfocado')
128
 
129
- # Generate button with callback
130
  def generate_offer():
131
  has_manual_input = bool(skills or product_service)
132
  has_file_input = bool('uploaded_file' in locals() and uploaded_file is not None)
133
  has_image_input = bool('uploaded_image' in locals() and uploaded_image is not None)
134
 
135
- # Simplify validation - just check if we have at least one input type
136
  if not (has_manual_input or has_file_input or has_image_input):
137
  st.error('Por favor proporciona al menos una entrada: texto, archivo o imagen')
138
  return
139
 
140
- # Check for valid combinations
141
  valid_input = (
142
- (has_manual_input and (has_file_input or has_image_input)) or # Text + (file or image)
143
- (not has_manual_input and (has_file_input or has_image_input)) or # Only file or image
144
- has_file_input or # Only file
145
- has_image_input # Only image
146
  )
147
 
148
  if not valid_input:
@@ -155,7 +142,6 @@ with col1:
155
 
156
  st.session_state.submitted = True
157
 
158
- # Store inputs based on what's available
159
  if has_manual_input:
160
  st.session_state.skills = skills if skills else ""
161
  st.session_state.product_service = product_service if product_service else ""
@@ -166,7 +152,6 @@ with col1:
166
  if has_image_input:
167
  st.session_state.image_parts = image_parts
168
 
169
- # Set input type
170
  if has_image_input:
171
  if has_manual_input and has_file_input:
172
  st.session_state.input_type = "all"
@@ -184,7 +169,6 @@ with col1:
184
  elif has_manual_input:
185
  st.session_state.input_type = "manual"
186
 
187
- # Store common settings
188
  st.session_state.target_audience = target_audience
189
  st.session_state.temperature = temperature
190
  st.session_state.formula_type = formula_type
@@ -193,10 +177,8 @@ with col1:
193
 
194
  # Results column
195
  with col2:
196
- # Check if form has been submitted
197
  if st.session_state.submitted:
198
  with st.spinner('Creando tu oferta perfecta...'):
199
- # Determine which input source to use and create appropriate prompt
200
  base_prompt = f"""You are a professional copywriter specializing in creating irresistible offers.
201
  Create a compelling and persuasive offer using the {st.session_state.formula_type} formula.
202
 
@@ -242,7 +224,7 @@ with col2:
242
 
243
  Please analyze both the file content and the visual elements in the image to create a comprehensive offer.
244
  """
245
- else: # all inputs
246
  prompt = base_prompt + f"""
247
  Based on all the following information:
248
  Skills: {st.session_state.skills}
@@ -261,10 +243,8 @@ with col2:
261
  IMPORTANT: Provide ONLY the final offer text. Do not include any explanations, labels, formatting instructions, brackets, or call to action at the end."""
262
 
263
  try:
264
- # Create generation config with temperature
265
  generation_config = genai.GenerationConfig(temperature=st.session_state.temperature)
266
 
267
- # Pass the generation config to generate_content
268
  if "image" in st.session_state.input_type:
269
  response = model.generate_content([prompt, st.session_state.image_parts[0]], generation_config=generation_config)
270
  else:
@@ -272,11 +252,9 @@ with col2:
272
 
273
  st.session_state.offer_result = response.text
274
 
275
- # Display result - without emoji
276
  st.markdown('### Oferta Generada')
277
  st.markdown(st.session_state.offer_result)
278
 
279
- # Add download button below the result with 80% width
280
  col_download, col_empty = st.columns([8, 2])
281
  with col_download:
282
  st.download_button(
 
17
 
18
  # Configure Google Gemini API
19
  genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
20
+ model = genai.GenerativeModel('gemini-1.5-flash')
21
 
22
  # Initialize session state variables if they don't exist
23
  if 'submitted' not in st.session_state:
 
37
  # Custom CSS
38
  st.markdown(get_custom_css(), unsafe_allow_html=True)
39
 
40
+ # App title and description
41
  st.markdown('<h1 style="text-align: center;">Great Offer Generator</h1>', unsafe_allow_html=True)
42
  st.markdown('<h3 style="text-align: center;">Transform your skills into compelling offers!</h3>', unsafe_allow_html=True)
43
 
 
46
 
47
  # Main input section in left column
48
  with col1:
 
49
  input_tab1, input_tab2, input_tab3 = st.tabs(["Entrada Manual", "Subir Archivo", "Subir Imagen"])
50
 
51
  with input_tab1:
 
57
  with input_tab2:
58
  uploaded_file = st.file_uploader("Sube un archivo con tu información", type=['txt', 'pdf', 'docx'])
59
  if uploaded_file is not None:
 
60
  file_type = uploaded_file.name.split('.')[-1].lower()
61
 
62
  if file_type == 'txt':
 
63
  file_content = uploaded_file.read().decode('utf-8')
64
  st.success(f"Archivo cargado correctamente: {uploaded_file.name}")
65
 
 
85
  st.error(f"Error al leer el archivo DOCX: {str(e)}")
86
  file_content = ""
87
 
 
88
  with st.expander("Vista previa del contenido"):
89
  st.write(file_content[:500] + "..." if len(file_content) > 500 else file_content)
90
 
91
  with input_tab3:
92
  uploaded_image = st.file_uploader("Sube una imagen de tu producto o servicio", type=['jpg', 'jpeg', 'png'])
93
  if uploaded_image is not None:
 
94
  image = Image.open(uploaded_image)
95
  st.image(image, caption="Imagen cargada", use_container_width=True)
96
 
 
97
  image_bytes = uploaded_image.getvalue()
98
  image_parts = [
99
  {
 
103
  ]
104
  st.success(f"Imagen cargada correctamente: {uploaded_image.name}")
105
 
 
106
  with st.expander('⚙️ Configuración Avanzada'):
107
  target_audience = st.text_area('👥 Público Objetivo', height=70,
108
  help='Describe tu cliente o público ideal')
109
 
 
110
  formula_type = st.selectbox(
111
  '📋 Tipo de Fórmula',
112
  options=list(offer_formulas.keys()),
113
  help='Selecciona el tipo de fórmula para tu oferta'
114
  )
115
 
 
 
116
  temperature = st.slider('🌡️ Nivel de Creatividad', min_value=0.0, max_value=2.0, value=0.7,
117
  help='Valores más altos hacen que el resultado sea más creativo pero menos enfocado')
118
 
 
119
  def generate_offer():
120
  has_manual_input = bool(skills or product_service)
121
  has_file_input = bool('uploaded_file' in locals() and uploaded_file is not None)
122
  has_image_input = bool('uploaded_image' in locals() and uploaded_image is not None)
123
 
 
124
  if not (has_manual_input or has_file_input or has_image_input):
125
  st.error('Por favor proporciona al menos una entrada: texto, archivo o imagen')
126
  return
127
 
 
128
  valid_input = (
129
+ (has_manual_input and (has_file_input or has_image_input)) or
130
+ (not has_manual_input and (has_file_input or has_image_input)) or
131
+ has_file_input or
132
+ has_image_input
133
  )
134
 
135
  if not valid_input:
 
142
 
143
  st.session_state.submitted = True
144
 
 
145
  if has_manual_input:
146
  st.session_state.skills = skills if skills else ""
147
  st.session_state.product_service = product_service if product_service else ""
 
152
  if has_image_input:
153
  st.session_state.image_parts = image_parts
154
 
 
155
  if has_image_input:
156
  if has_manual_input and has_file_input:
157
  st.session_state.input_type = "all"
 
169
  elif has_manual_input:
170
  st.session_state.input_type = "manual"
171
 
 
172
  st.session_state.target_audience = target_audience
173
  st.session_state.temperature = temperature
174
  st.session_state.formula_type = formula_type
 
177
 
178
  # Results column
179
  with col2:
 
180
  if st.session_state.submitted:
181
  with st.spinner('Creando tu oferta perfecta...'):
 
182
  base_prompt = f"""You are a professional copywriter specializing in creating irresistible offers.
183
  Create a compelling and persuasive offer using the {st.session_state.formula_type} formula.
184
 
 
224
 
225
  Please analyze both the file content and the visual elements in the image to create a comprehensive offer.
226
  """
227
+ else:
228
  prompt = base_prompt + f"""
229
  Based on all the following information:
230
  Skills: {st.session_state.skills}
 
243
  IMPORTANT: Provide ONLY the final offer text. Do not include any explanations, labels, formatting instructions, brackets, or call to action at the end."""
244
 
245
  try:
 
246
  generation_config = genai.GenerationConfig(temperature=st.session_state.temperature)
247
 
 
248
  if "image" in st.session_state.input_type:
249
  response = model.generate_content([prompt, st.session_state.image_parts[0]], generation_config=generation_config)
250
  else:
 
252
 
253
  st.session_state.offer_result = response.text
254
 
 
255
  st.markdown('### Oferta Generada')
256
  st.markdown(st.session_state.offer_result)
257
 
 
258
  col_download, col_empty = st.columns([8, 2])
259
  with col_download:
260
  st.download_button(