JeCabrera commited on
Commit
cbb526b
·
verified ·
1 Parent(s): 1eab75b

Upload 11 files

Browse files
Files changed (2) hide show
  1. app.py +94 -4
  2. requirements.txt +3 -1
app.py CHANGED
@@ -2,12 +2,18 @@ from dotenv import load_dotenv
2
  import streamlit as st
3
  import os
4
  import google.generativeai as genai
 
 
5
  from ads_formulas import ads_formulas # Import the ads formulas
6
  from style import styles
7
  from prompts import create_fb_ad_instruction
8
  from emotional_angles import emotional_angles
9
  from copywriter_personas import copywriter_personas
10
  from ad_objectives import ad_objectives # Import ad objectives
 
 
 
 
11
 
12
  # Cargar las variables de entorno
13
  load_dotenv()
@@ -24,7 +30,7 @@ def get_model(temperature):
24
  return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config)
25
 
26
  # Function to generate Facebook ads
27
- def generate_fb_ad(target_audience, product, temperature, selected_formula, selected_angle, selected_persona, story_prompt="", ad_objective=None):
28
  if not target_audience or not product:
29
  return "Por favor, completa todos los campos requeridos."
30
 
@@ -35,6 +41,8 @@ def generate_fb_ad(target_audience, product, temperature, selected_formula, sele
35
  emphasized_story_prompt = story_prompt.strip()
36
 
37
  model = get_model(temperature)
 
 
38
  ad_instruction = create_fb_ad_instruction(
39
  target_audience,
40
  product,
@@ -46,13 +54,22 @@ def generate_fb_ad(target_audience, product, temperature, selected_formula, sele
46
  story_prompt=emphasized_story_prompt # Usar el tema enfatizado
47
  )
48
 
 
 
 
 
49
  # Si hay un tema específico, ajustar la temperatura para mayor coherencia
50
  effective_temperature = temperature
51
  if story_prompt and story_prompt.strip():
52
  # Reducir ligeramente la temperatura para mantener más enfoque en el tema
53
  effective_temperature = max(0.1, temperature * 0.9)
54
 
55
- response = model.generate_content([ad_instruction], generation_config={"temperature": effective_temperature})
 
 
 
 
 
56
  return response.parts[0].text if response and response.parts else "Error generating content."
57
 
58
  # Configurar la interfaz de usuario con Streamlit
@@ -84,7 +101,78 @@ with col1:
84
  ad_product = st.text_input("¿Qué producto tienes en mente?", placeholder="Ejemplo: Curso de gestión del tiempo")
85
  input_prompt = st.text_area("Escribe de qué quieres que trate la historia:", placeholder="Escribe aquí tu idea...")
86
 
87
- # Mover el botón aquí, antes de las opciones avanzadas
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  submit_ad = st.button("GENERAR ANUNCIO")
89
 
90
  with st.expander("Opciones avanzadas"):
@@ -147,7 +235,9 @@ if submit_ad:
147
  emotional_angle,
148
  ad_persona,
149
  input_prompt, # Pass the new story prompt
150
- selected_objective
 
 
151
  )
152
 
153
  if not isinstance(generated_ad, str):
 
2
  import streamlit as st
3
  import os
4
  import google.generativeai as genai
5
+ import time
6
+ import datetime
7
  from ads_formulas import ads_formulas # Import the ads formulas
8
  from style import styles
9
  from prompts import create_fb_ad_instruction
10
  from emotional_angles import emotional_angles
11
  from copywriter_personas import copywriter_personas
12
  from ad_objectives import ad_objectives # Import ad objectives
13
+ import PyPDF2
14
+ import docx
15
+ from PIL import Image
16
+ import io
17
 
18
  # Cargar las variables de entorno
19
  load_dotenv()
 
30
  return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config)
31
 
32
  # Function to generate Facebook ads
33
+ def generate_fb_ad(target_audience, product, temperature, selected_formula, selected_angle, selected_persona, story_prompt="", ad_objective=None, file_content="", image_parts=None):
34
  if not target_audience or not product:
35
  return "Por favor, completa todos los campos requeridos."
36
 
 
41
  emphasized_story_prompt = story_prompt.strip()
42
 
43
  model = get_model(temperature)
44
+
45
+ # Crear la instrucción base
46
  ad_instruction = create_fb_ad_instruction(
47
  target_audience,
48
  product,
 
54
  story_prompt=emphasized_story_prompt # Usar el tema enfatizado
55
  )
56
 
57
+ # Si hay contenido de archivo, añadirlo a la instrucción
58
+ if file_content:
59
+ ad_instruction += f"\n\nAdemás, utiliza la siguiente información como referencia para crear el anuncio:\n\n{file_content[:2000]}"
60
+
61
  # Si hay un tema específico, ajustar la temperatura para mayor coherencia
62
  effective_temperature = temperature
63
  if story_prompt and story_prompt.strip():
64
  # Reducir ligeramente la temperatura para mantener más enfoque en el tema
65
  effective_temperature = max(0.1, temperature * 0.9)
66
 
67
+ # Generar el contenido con o sin imagen
68
+ if image_parts:
69
+ response = model.generate_content([ad_instruction, image_parts], generation_config={"temperature": effective_temperature})
70
+ else:
71
+ response = model.generate_content([ad_instruction], generation_config={"temperature": effective_temperature})
72
+
73
  return response.parts[0].text if response and response.parts else "Error generating content."
74
 
75
  # Configurar la interfaz de usuario con Streamlit
 
101
  ad_product = st.text_input("¿Qué producto tienes en mente?", placeholder="Ejemplo: Curso de gestión del tiempo")
102
  input_prompt = st.text_area("Escribe de qué quieres que trate la historia:", placeholder="Escribe aquí tu idea...")
103
 
104
+ # Añadir cargador de archivos
105
+ uploaded_file = st.file_uploader("📄 Sube un archivo o imagen de referencia",
106
+ type=['txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'])
107
+
108
+ file_content = ""
109
+ is_image = False
110
+ image_parts = None
111
+
112
+ if uploaded_file is not None:
113
+ file_type = uploaded_file.name.split('.')[-1].lower()
114
+
115
+ # Manejar archivos de texto
116
+ if file_type in ['txt', 'pdf', 'docx']:
117
+ if file_type == 'txt':
118
+ try:
119
+ file_content = uploaded_file.read().decode('utf-8')
120
+ st.success(f"Archivo TXT cargado: {uploaded_file.name}")
121
+ except Exception as e:
122
+ st.error(f"Error al leer el archivo TXT: {str(e)}")
123
+ file_content = ""
124
+
125
+ elif file_type == 'pdf':
126
+ try:
127
+ import PyPDF2
128
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
129
+ file_content = ""
130
+ for page in pdf_reader.pages:
131
+ file_content += page.extract_text() + "\n"
132
+ st.success(f"Archivo PDF cargado: {uploaded_file.name}")
133
+ except Exception as e:
134
+ st.error(f"Error al leer el archivo PDF: {str(e)}")
135
+ file_content = ""
136
+
137
+ elif file_type == 'docx':
138
+ try:
139
+ import docx
140
+ doc = docx.Document(uploaded_file)
141
+ file_content = "\n".join([para.text for para in doc.paragraphs])
142
+ st.success(f"Archivo DOCX cargado: {uploaded_file.name}")
143
+ except Exception as e:
144
+ st.error(f"Error al leer el archivo DOCX: {str(e)}")
145
+ file_content = ""
146
+
147
+ # Mostrar una vista previa del contenido
148
+ if file_content:
149
+ with st.expander("Vista previa del contenido"):
150
+ st.text(file_content[:500] + "..." if len(file_content) > 500 else file_content)
151
+
152
+ # Manejar archivos de imagen
153
+ elif file_type in ['jpg', 'jpeg', 'png']:
154
+ try:
155
+ from PIL import Image
156
+ image = Image.open(uploaded_file)
157
+
158
+ # Mostrar la imagen
159
+ with st.expander("Vista previa de la imagen"):
160
+ st.image(image, caption="Imagen cargada", use_container_width=True)
161
+
162
+ image_bytes = uploaded_file.getvalue()
163
+ image_parts = [
164
+ {
165
+ "mime_type": uploaded_file.type,
166
+ "data": image_bytes
167
+ }
168
+ ]
169
+ is_image = True
170
+ st.success(f"Imagen cargada: {uploaded_file.name}")
171
+ except Exception as e:
172
+ st.error(f"Error al procesar la imagen: {str(e)}")
173
+ is_image = False
174
+
175
+ # Mover el botón aquí, después del cargador de archivos
176
  submit_ad = st.button("GENERAR ANUNCIO")
177
 
178
  with st.expander("Opciones avanzadas"):
 
235
  emotional_angle,
236
  ad_persona,
237
  input_prompt, # Pass the new story prompt
238
+ selected_objective,
239
+ file_content if 'file_content' in locals() and file_content else "",
240
+ image_parts if 'image_parts' in locals() and is_image else None
241
  )
242
 
243
  if not isinstance(generated_ad, str):
requirements.txt CHANGED
@@ -5,4 +5,6 @@ langchain
5
  PyPDF2
6
  chromadb
7
  pdf2image
8
- faiss-cpu
 
 
 
5
  PyPDF2
6
  chromadb
7
  pdf2image
8
+ faiss-cpu
9
+ python-docx
10
+ Pillow