JeCabrera commited on
Commit
f99dda4
·
verified ·
1 Parent(s): 58cd336

Upload 9 files

Browse files
Files changed (1) hide show
  1. app.py +98 -12
app.py CHANGED
@@ -16,7 +16,7 @@ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
16
  # Fórmulas con ejemplos y explicaciones
17
  # headline_formulas dictionary has been moved to formulas/headline_formulas.py
18
 
19
- def generate_headlines(number_of_headlines, target_audience, product, temperature, selected_formula, selected_angle):
20
  # Crear la configuración del modelo
21
  generation_config = {
22
  "temperature": temperature,
@@ -72,6 +72,15 @@ IMPORTANT:
72
  # Iniciar el prompt con las instrucciones del sistema
73
  headlines_instruction = f"{system_prompt}\n\n"
74
 
 
 
 
 
 
 
 
 
 
75
  # Añadir instrucciones de ángulo solo si no es "NINGUNO"
76
  if selected_angle != "NINGUNO":
77
  headlines_instruction += f"""
@@ -151,16 +160,31 @@ GENERA AHORA:
151
  Crea {number_of_headlines} titulares que sigan fielmente el estilo y estructura de los ejemplos mostrados.
152
  """
153
 
154
- chat_session = model.start_chat(
155
- history=[
156
- {
157
- "role": "user",
158
- "parts": [headlines_instruction],
159
- },
160
- ]
161
- )
162
-
163
- response = chat_session.send_message("Genera los titulares siguiendo exactamente el estilo de los ejemplos mostrados.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  return response.text
165
 
166
  # Configurar la interfaz de usuario con Streamlit
@@ -209,6 +233,65 @@ with col1:
209
  "Selecciona el ángulo para tus titulares",
210
  options=angle_keys
211
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
  selected_formula = headline_formulas[selected_formula_key]
214
 
@@ -225,7 +308,10 @@ if submit:
225
  product,
226
  temperature,
227
  selected_formula,
228
- selected_angle # Agregar el ángulo seleccionado
 
 
 
229
  )
230
  col2.markdown(f"""
231
  <div class="results-container">
 
16
  # Fórmulas con ejemplos y explicaciones
17
  # headline_formulas dictionary has been moved to formulas/headline_formulas.py
18
 
19
+ def generate_headlines(number_of_headlines, target_audience, product, temperature, selected_formula, selected_angle, file_content="", image_parts=None, is_image=False):
20
  # Crear la configuración del modelo
21
  generation_config = {
22
  "temperature": temperature,
 
72
  # Iniciar el prompt con las instrucciones del sistema
73
  headlines_instruction = f"{system_prompt}\n\n"
74
 
75
+ # Añadir contenido del archivo si existe
76
+ if file_content:
77
+ headlines_instruction += f"""
78
+ CONTENIDO DE REFERENCIA:
79
+ Utiliza el siguiente contenido como referencia para generar los titulares:
80
+ {file_content[:3000]} # Limitamos a 3000 caracteres para evitar tokens excesivos
81
+
82
+ """
83
+
84
  # Añadir instrucciones de ángulo solo si no es "NINGUNO"
85
  if selected_angle != "NINGUNO":
86
  headlines_instruction += f"""
 
160
  Crea {number_of_headlines} titulares que sigan fielmente el estilo y estructura de los ejemplos mostrados.
161
  """
162
 
163
+ # Modificar la forma de enviar el mensaje según si hay imagen o no
164
+ if is_image and image_parts:
165
+ chat_session = model.start_chat(
166
+ history=[
167
+ {
168
+ "role": "user",
169
+ "parts": [
170
+ headlines_instruction,
171
+ image_parts
172
+ ],
173
+ },
174
+ ]
175
+ )
176
+ response = chat_session.send_message("Genera los titulares siguiendo exactamente el estilo de los ejemplos mostrados, inspirándote en la imagen proporcionada.")
177
+ else:
178
+ chat_session = model.start_chat(
179
+ history=[
180
+ {
181
+ "role": "user",
182
+ "parts": [headlines_instruction],
183
+ },
184
+ ]
185
+ )
186
+ response = chat_session.send_message("Genera los titulares siguiendo exactamente el estilo de los ejemplos mostrados.")
187
+
188
  return response.text
189
 
190
  # Configurar la interfaz de usuario con Streamlit
 
233
  "Selecciona el ángulo para tus titulares",
234
  options=angle_keys
235
  )
236
+
237
+ # Añadir cargador de archivos dentro del acordeón
238
+ uploaded_file = st.file_uploader("📄 Archivo o imagen de referencia",
239
+ type=['txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'])
240
+
241
+ file_content = ""
242
+ is_image = False
243
+ image_parts = None
244
+
245
+ if uploaded_file is not None:
246
+ file_type = uploaded_file.name.split('.')[-1].lower()
247
+
248
+ # Manejar archivos de texto
249
+ if file_type in ['txt', 'pdf', 'docx']:
250
+ if file_type == 'txt':
251
+ try:
252
+ file_content = uploaded_file.read().decode('utf-8')
253
+ st.success(f"Archivo TXT cargado correctamente: {uploaded_file.name}")
254
+ except Exception as e:
255
+ st.error(f"Error al leer el archivo TXT: {str(e)}")
256
+ file_content = ""
257
+
258
+ elif file_type == 'pdf':
259
+ try:
260
+ import PyPDF2
261
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
262
+ file_content = ""
263
+ for page in pdf_reader.pages:
264
+ file_content += page.extract_text() + "\n"
265
+ st.success(f"Archivo PDF cargado correctamente: {uploaded_file.name}")
266
+ except Exception as e:
267
+ st.error(f"Error al leer el archivo PDF: {str(e)}")
268
+ file_content = ""
269
+
270
+ elif file_type == 'docx':
271
+ try:
272
+ import docx
273
+ doc = docx.Document(uploaded_file)
274
+ file_content = "\n".join([para.text for para in doc.paragraphs])
275
+ st.success(f"Archivo DOCX cargado correctamente: {uploaded_file.name}")
276
+ except Exception as e:
277
+ st.error(f"Error al leer el archivo DOCX: {str(e)}")
278
+ file_content = ""
279
+
280
+ # Manejar archivos de imagen
281
+ elif file_type in ['jpg', 'jpeg', 'png']:
282
+ try:
283
+ from PIL import Image
284
+ image = Image.open(uploaded_file)
285
+ image_bytes = uploaded_file.getvalue()
286
+ image_parts = {
287
+ "mime_type": uploaded_file.type,
288
+ "data": image_bytes
289
+ }
290
+ is_image = True
291
+ st.image(image, caption="Imagen cargada", use_column_width=True)
292
+ except Exception as e:
293
+ st.error(f"Error al procesar la imagen: {str(e)}")
294
+ is_image = False
295
 
296
  selected_formula = headline_formulas[selected_formula_key]
297
 
 
308
  product,
309
  temperature,
310
  selected_formula,
311
+ selected_angle,
312
+ file_content if 'file_content' in locals() else "",
313
+ image_parts if 'image_parts' in locals() else None,
314
+ is_image if 'is_image' in locals() else False
315
  )
316
  col2.markdown(f"""
317
  <div class="results-container">