Upload 9 files
Browse files- README.md +12 -12
- app.py +540 -540
- formulas/email_formulas.py +0 -0
- manual.md +124 -103
README.md
CHANGED
@@ -1,13 +1,13 @@
|
|
1 |
-
---
|
2 |
-
sdk: streamlit
|
3 |
-
colorFrom: yellow
|
4 |
-
colorTo: gray
|
5 |
-
pinned: true
|
6 |
-
title: Email Generator CopyXpert
|
7 |
-
license: afl-3.0
|
8 |
-
emoji: ⚡
|
9 |
-
thumbnail: >-
|
10 |
-
https://cdn-uploads.huggingface.co/production/uploads/66c41fa62777c050701989a9/D4k6XvaEzAaSJkNb01JTU.png
|
11 |
-
short_description: Make emails with AI
|
12 |
-
sdk_version: 1.
|
13 |
---
|
|
|
1 |
+
---
|
2 |
+
sdk: streamlit
|
3 |
+
colorFrom: yellow
|
4 |
+
colorTo: gray
|
5 |
+
pinned: true
|
6 |
+
title: Email Generator CopyXpert
|
7 |
+
license: afl-3.0
|
8 |
+
emoji: ⚡
|
9 |
+
thumbnail: >-
|
10 |
+
https://cdn-uploads.huggingface.co/production/uploads/66c41fa62777c050701989a9/D4k6XvaEzAaSJkNb01JTU.png
|
11 |
+
short_description: Make emails with AI
|
12 |
+
sdk_version: 1.43.2
|
13 |
---
|
app.py
CHANGED
@@ -1,540 +1,540 @@
|
|
1 |
-
from dotenv import load_dotenv
|
2 |
-
import streamlit as st
|
3 |
-
import os
|
4 |
-
import google.generativeai as genai
|
5 |
-
import random
|
6 |
-
from streamlit import session_state as state
|
7 |
-
from formulas import email_formulas
|
8 |
-
from angles import angles
|
9 |
-
import re
|
10 |
-
import datetime
|
11 |
-
import PyPDF2
|
12 |
-
import docx
|
13 |
-
from PIL import Image
|
14 |
-
|
15 |
-
# Cargar las variables de entorno
|
16 |
-
load_dotenv()
|
17 |
-
|
18 |
-
# Configurar la API de Google
|
19 |
-
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
20 |
-
|
21 |
-
# Fórmulas con ejemplos y explicaciones
|
22 |
-
# email_formulas dictionary has been moved to formulas/email_formulas.py
|
23 |
-
|
24 |
-
# Cambiar el nombre de la función
|
25 |
-
def generate_emails(target_audience, product, temperature, selected_formula, selected_angle, file_content="", image_parts=None, is_image=False, emotion="", desired_action="", creative_idea=""):
|
26 |
-
# Crear la configuración del modelo
|
27 |
-
generation_config = {
|
28 |
-
"temperature": temperature,
|
29 |
-
"top_p": 0.65,
|
30 |
-
"top_k": 360,
|
31 |
-
"max_output_tokens": 8196,
|
32 |
-
}
|
33 |
-
|
34 |
-
model = genai.GenerativeModel(
|
35 |
-
model_name="gemini-2.0-flash",
|
36 |
-
generation_config=generation_config,
|
37 |
-
)
|
38 |
-
|
39 |
-
# Definir las instrucciones de formato una sola vez
|
40 |
-
format_instructions = """
|
41 |
-
FORMAT RULES:
|
42 |
-
- Each email must start with "Correo 1", "Correo 2", etc.
|
43 |
-
- Each email must have a clear and attractive subject line
|
44 |
-
- The email body must be persuasive and emotional
|
45 |
-
- Include a clear call to action
|
46 |
-
- Add a professional signature
|
47 |
-
- Separate each email clearly
|
48 |
-
- Do not include greetings like 'Hello [Name]'
|
49 |
-
- Make sure that the postscripts (P.D.) are smaller and more discrete than the main body
|
50 |
-
- IMPORTANT: The first email must be an introduction without referencing any previous communications
|
51 |
-
- Emails 2-5 should build on the sequence in a logical progression
|
52 |
-
"""
|
53 |
-
|
54 |
-
# Incluir las instrucciones del sistema en el prompt principal
|
55 |
-
system_prompt = f"""You are a world-class direct response copywriter trained by Gary Halbert, Gary Bencivenga, and David Ogilvy.
|
56 |
-
|
57 |
-
You have helped many marketers before me persuade their clients through emotional email sequences.
|
58 |
-
Your task is to create a 5-email sequence that makes my [buyer persona] feel [emotion] about my [product/service] and convince them to register/take [desired action].
|
59 |
-
|
60 |
-
{format_instructions}
|
61 |
-
|
62 |
-
IMPORTANT:
|
63 |
-
- Each email must be unique and memorable
|
64 |
-
- Avoid clichés and generalities
|
65 |
-
- Maintain a persuasive but credible tone
|
66 |
-
- Adapt language to the target audience
|
67 |
-
- Focus on transformative benefits"""
|
68 |
-
|
69 |
-
# Iniciar el prompt con las instrucciones del sistema
|
70 |
-
email_instruction = f"{system_prompt}\n\n"
|
71 |
-
|
72 |
-
# Add instructions for using the enhanced formula structure
|
73 |
-
if hasattr(selected_formula, 'get') and selected_formula.get('subject_line_types') and selected_formula.get('email_structure_template'):
|
74 |
-
email_instruction += """
|
75 |
-
ENHANCED FORMULA STRUCTURE:
|
76 |
-
Use the following structure elements to create more effective emails:
|
77 |
-
|
78 |
-
SUBJECT LINE TYPES:
|
79 |
-
"""
|
80 |
-
# Add subject line types with descriptions
|
81 |
-
for subject_type, description in selected_formula.get('subject_line_types', {}).items():
|
82 |
-
email_instruction += f"- {subject_type}: {description}\n"
|
83 |
-
|
84 |
-
# Add technique types (either infotainment or nurturing)
|
85 |
-
technique_key = next((k for k in selected_formula.keys() if k.endswith('_techniques')), None)
|
86 |
-
if technique_key:
|
87 |
-
email_instruction += f"\n{technique_key.upper()}:\n"
|
88 |
-
for technique, description in selected_formula.get(technique_key, {}).items():
|
89 |
-
email_instruction += f"- {technique}: {description}\n"
|
90 |
-
|
91 |
-
# Add email structure template
|
92 |
-
email_instruction += "\nEMAIL STRUCTURE TEMPLATE:\n"
|
93 |
-
for email_num, structure in selected_formula.get('email_structure_template', {}).items():
|
94 |
-
email_instruction += f"\n{email_num.upper()}:\n"
|
95 |
-
email_instruction += f"- Purpose: {structure.get('purpose', '')}\n"
|
96 |
-
email_instruction += f"- Emotional Focus: {structure.get('emotional_focus', '')}\n"
|
97 |
-
|
98 |
-
# Add recommended subject types
|
99 |
-
if structure.get('recommended_subject_types'):
|
100 |
-
email_instruction += "- Recommended Subject Types: " + ", ".join(structure.get('recommended_subject_types', [])) + "\n"
|
101 |
-
|
102 |
-
# Add recommended techniques
|
103 |
-
if structure.get('recommended_techniques'):
|
104 |
-
email_instruction += "- Recommended Techniques: " + ", ".join(structure.get('recommended_techniques', [])) + "\n"
|
105 |
-
|
106 |
-
# Add key elements
|
107 |
-
if structure.get('key_elements'):
|
108 |
-
email_instruction += "- Key Elements:\n"
|
109 |
-
for element in structure.get('key_elements', []):
|
110 |
-
email_instruction += f" * {element}\n"
|
111 |
-
|
112 |
-
# Añadir instrucciones para la idea creativa si existe
|
113 |
-
if creative_idea:
|
114 |
-
email_instruction += f"""
|
115 |
-
CREATIVE CONCEPT:
|
116 |
-
Use the following creative concept as the central theme for all emails in the sequence:
|
117 |
-
"{creative_idea}"
|
118 |
-
|
119 |
-
CREATIVE CONCEPT INSTRUCTIONS:
|
120 |
-
1. This concept should be the unifying theme across all emails
|
121 |
-
2. Use it as a metaphor or analogy throughout the sequence
|
122 |
-
3. Develop different aspects of this concept in each email
|
123 |
-
4. Make sure the concept naturally connects to the product benefits
|
124 |
-
5. The concept should make the emails more memorable and engaging
|
125 |
-
"""
|
126 |
-
|
127 |
-
# Añadir contenido del archivo si existe
|
128 |
-
if file_content:
|
129 |
-
email_instruction += f"""
|
130 |
-
REFERENCE CONTENT:
|
131 |
-
Carefully analyze the following content as a reference for generating emails:
|
132 |
-
{file_content[:3000]}
|
133 |
-
|
134 |
-
ANALYSIS INSTRUCTIONS:
|
135 |
-
1. Extract key information about the product or service mentioned
|
136 |
-
2. Identify the tone, style, and language used
|
137 |
-
3. Detect any data about the target audience or customer avatar
|
138 |
-
4. Look for benefits, features, or pain points mentioned
|
139 |
-
5. Use relevant terms, phrases, or concepts from the content
|
140 |
-
6. Maintain consistency with the brand identity or main message
|
141 |
-
7. Adapt the emails to resonate with the provided content
|
142 |
-
|
143 |
-
IMPORTANT COMBINATIONS:
|
144 |
-
"""
|
145 |
-
# Updated conditions for specific input combinations
|
146 |
-
if product and not target_audience:
|
147 |
-
email_instruction += f"""- FILE + PRODUCT: You have a reference document and product ({product}). Create emails that highlight this specific product's benefits and features using insights from the document. Extract audience information from the document to better target the emails.
|
148 |
-
"""
|
149 |
-
elif target_audience and not product:
|
150 |
-
email_instruction += f"""- FILE + TARGET AUDIENCE: You have a reference document and target audience ({target_audience}). Create emails tailored to this specific audience using language and concepts from the document. Identify products or services from the document that would appeal to this audience.
|
151 |
-
"""
|
152 |
-
elif product and target_audience:
|
153 |
-
email_instruction += f"""- PRODUCT + TARGET AUDIENCE: You have both product ({product}) and target audience ({target_audience}). Create emails that connect this specific product with this specific audience, using insights from the document to strengthen the connection.
|
154 |
-
"""
|
155 |
-
|
156 |
-
email_instruction += """
|
157 |
-
IMPORTANT: Naturally integrate the elements found in the content with the selected formula and angle.
|
158 |
-
"""
|
159 |
-
|
160 |
-
# Preparar instrucciones específicas del ángulo una sola vez
|
161 |
-
angle_instructions = ""
|
162 |
-
if selected_angle != "NINGUNO":
|
163 |
-
angle_instructions = f"""
|
164 |
-
MAIN ANGLE: {selected_angle}
|
165 |
-
SPECIFIC ANGLE INSTRUCTIONS:
|
166 |
-
{angles[selected_angle]["instruction"]}
|
167 |
-
|
168 |
-
IMPORTANT: The angle {selected_angle} must be applied as a "style layer" over the formula structure:
|
169 |
-
1. Keep the base structure of the formula intact
|
170 |
-
2. Apply the tone and style of the {selected_angle} angle
|
171 |
-
3. Ensure each element of the formula reflects the angle
|
172 |
-
4. The angle affects "how" it's said, not "what" is said
|
173 |
-
|
174 |
-
SUCCESSFUL EXAMPLES OF THE {selected_angle} ANGLE:
|
175 |
-
"""
|
176 |
-
for example in angles[selected_angle]["examples"]:
|
177 |
-
angle_instructions += f"- {example}\n"
|
178 |
-
|
179 |
-
# Añadir las instrucciones del ángulo al prompt principal
|
180 |
-
email_instruction += angle_instructions
|
181 |
-
|
182 |
-
# Dentro de la función, actualizar el prompt para incluir emoción y acción deseada
|
183 |
-
email_instruction += (
|
184 |
-
f"\nYour task is to create 5 persuasive emails for {target_audience} "
|
185 |
-
f"that evoke {emotion} and convince them to {desired_action} about {product}. "
|
186 |
-
)
|
187 |
-
|
188 |
-
# Usar la variable angle_instructions para determinar si hay un ángulo seleccionado
|
189 |
-
if angle_instructions:
|
190 |
-
email_instruction += f"IMPORTANT: Each email MUST follow the {selected_angle} angle clearly and consistently."
|
191 |
-
|
192 |
-
email_instruction += "\n\n"
|
193 |
-
|
194 |
-
# Take the first 5 examples (or all if less than 5) in order
|
195 |
-
sequential_examples = selected_formula['examples'][:min(5, len(selected_formula['examples']))]
|
196 |
-
|
197 |
-
email_instruction += "FORMULA EXAMPLES TO FOLLOW:\n"
|
198 |
-
for i, example in enumerate(sequential_examples, 1):
|
199 |
-
email_instruction += f"{i}. {example}\n"
|
200 |
-
|
201 |
-
# Añadir instrucciones específicas sobre cómo seguir los ejemplos
|
202 |
-
email_instruction += "\nSPECIFIC INSTRUCTIONS:\n"
|
203 |
-
email_instruction += "1. Maintain the same structure and length as the previous examples\n"
|
204 |
-
email_instruction += "2. Use the same tone and writing style\n"
|
205 |
-
email_instruction += "3. Replicate the phrase construction patterns\n"
|
206 |
-
email_instruction += "4. Preserve the level of specificity and detail\n"
|
207 |
-
email_instruction += f"5. Adapt the content for {target_audience} while maintaining the essence of the examples\n\n"
|
208 |
-
|
209 |
-
# Añadir instrucciones específicas sobre la temperatura creativa
|
210 |
-
email_instruction += f"\nCREATIVITY LEVEL: {temperature}. Higher values mean more creative and original content.\n\n"
|
211 |
-
|
212 |
-
email_instruction += f"FORMULA TO FOLLOW:\n{selected_formula['description']}\n\n"
|
213 |
-
|
214 |
-
# Consolidar las instrucciones finales en un solo bloque
|
215 |
-
final_reminder = ["Follow the structure of the selected formula"]
|
216 |
-
|
217 |
-
# Add angle-specific instructions only if an angle is selected
|
218 |
-
if selected_angle != "NINGUNO":
|
219 |
-
final_reminder.extend([
|
220 |
-
"Apply the angle as a 'style layer'",
|
221 |
-
"Maintain coherence between formula and angle",
|
222 |
-
"Ensure each email reflects both elements"
|
223 |
-
])
|
224 |
-
|
225 |
-
email_instruction += "\nFINAL REMINDER:\n"
|
226 |
-
for i, reminder in enumerate(final_reminder, 1):
|
227 |
-
email_instruction += f"{i}. {reminder}\n"
|
228 |
-
|
229 |
-
email_instruction += "\nGENERATE NOW:\nCreate 5 emails that faithfully follow the style and structure of the examples shown.\n"
|
230 |
-
|
231 |
-
# Modificar la forma de enviar el mensaje según si hay imagen o no
|
232 |
-
message_parts = [email_instruction]
|
233 |
-
|
234 |
-
# Build instruction text more clearly with conditional components
|
235 |
-
instruction_components = ["Generate the emails in Spanish following exactly the style and structure of the examples shown."]
|
236 |
-
|
237 |
-
# Add the image to the message parts if it exists
|
238 |
-
if is_image and image_parts:
|
239 |
-
message_parts.append(image_parts)
|
240 |
-
instruction_components.append("drawing inspiration from the provided image.")
|
241 |
-
|
242 |
-
# Add final instruction
|
243 |
-
instruction_components.append("Do not include explanations, only the emails.")
|
244 |
-
|
245 |
-
# Join all instruction components with proper spacing
|
246 |
-
instruction_text = " ".join(instruction_components)
|
247 |
-
|
248 |
-
# Create the chat session with the message parts
|
249 |
-
try:
|
250 |
-
chat_session = model.start_chat(
|
251 |
-
history=[
|
252 |
-
{
|
253 |
-
"role": "user",
|
254 |
-
"parts": message_parts,
|
255 |
-
},
|
256 |
-
]
|
257 |
-
)
|
258 |
-
|
259 |
-
# Enviar el mensaje con las instrucciones
|
260 |
-
response = chat_session.send_message(instruction_text)
|
261 |
-
|
262 |
-
return response.text
|
263 |
-
except genai.types.generation_types.StopCandidateException as e:
|
264 |
-
# Handle content filtering/safety issues
|
265 |
-
error_message = f"La generación se detuvo debido a restricciones de contenido: {str(e)}"
|
266 |
-
st.error(error_message)
|
267 |
-
return f"Error: {error_message}"
|
268 |
-
except genai.types.generation_types.BlockedPromptException as e:
|
269 |
-
# Handle blocked prompt issues
|
270 |
-
error_message = f"El prompt fue bloqueado por políticas de contenido: {str(e)}"
|
271 |
-
st.error(error_message)
|
272 |
-
return f"Error: {error_message}"
|
273 |
-
except Exception as e:
|
274 |
-
# Handle general API errors
|
275 |
-
error_message = f"Error al comunicarse con la API de Google: {str(e)}"
|
276 |
-
st.error(error_message)
|
277 |
-
return f"Error: {error_message}"
|
278 |
-
|
279 |
-
# Define the clean_response_text function before it's used
|
280 |
-
def clean_response_text(text):
|
281 |
-
"""Remove extra spaces and normalize whitespace in the response text"""
|
282 |
-
# Replace multiple newlines with just two
|
283 |
-
text = re.sub(r'\n{3,}', '\n\n', text)
|
284 |
-
# Remove leading/trailing whitespace
|
285 |
-
text = text.strip()
|
286 |
-
return text
|
287 |
-
|
288 |
-
# Configurar la interfaz de usuario con Streamlit
|
289 |
-
st.set_page_config(
|
290 |
-
page_title="Email Composer",
|
291 |
-
layout="wide",
|
292 |
-
menu_items={}, # Empty dict removes the three-dot menu
|
293 |
-
initial_sidebar_state="expanded"
|
294 |
-
)
|
295 |
-
|
296 |
-
# Add custom CSS to reduce margins
|
297 |
-
st.markdown("""
|
298 |
-
<style>
|
299 |
-
.main > div {
|
300 |
-
padding-top: 1rem;
|
301 |
-
}
|
302 |
-
</style>
|
303 |
-
""", unsafe_allow_html=True)
|
304 |
-
|
305 |
-
# Leer el contenido del archivo manual.md
|
306 |
-
manual_path = "manual.md"
|
307 |
-
if os.path.exists(manual_path):
|
308 |
-
with open(manual_path, "r", encoding="utf-8") as file:
|
309 |
-
manual_content = file.read()
|
310 |
-
# Mostrar el contenido del manual en el sidebar
|
311 |
-
st.sidebar.markdown(manual_content)
|
312 |
-
else:
|
313 |
-
st.sidebar.warning("Manual file not found.")
|
314 |
-
|
315 |
-
# Load CSS from file
|
316 |
-
css_path = "styles/main.css"
|
317 |
-
if os.path.exists(css_path):
|
318 |
-
with open(css_path, "r") as f:
|
319 |
-
css = f.read()
|
320 |
-
# Apply the CSS
|
321 |
-
st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)
|
322 |
-
else:
|
323 |
-
st.warning("CSS file not found.")
|
324 |
-
|
325 |
-
# Centrar el título y el subtítulo
|
326 |
-
st.markdown("<h1 style='text-align: center;'>Generador de Emails</h1>", unsafe_allow_html=True)
|
327 |
-
st.markdown("<h4 style='text-align: center;'>Transforma tu marketing con emails persuasivos que convierten. Esta aplicación es tu arma secreta para crear emails emocionales de respuesta directa que impulsan a la acción.</h4>", unsafe_allow_html=True)
|
328 |
-
|
329 |
-
# Crear columnas
|
330 |
-
col1, col2 = st.columns([1, 2])
|
331 |
-
|
332 |
-
# Initialize these variables at the top level before the UI components
|
333 |
-
file_content = ""
|
334 |
-
is_image = False
|
335 |
-
image_parts = None
|
336 |
-
|
337 |
-
# Columnas de entrada
|
338 |
-
with col1:
|
339 |
-
target_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Estudiantes Universitarios")
|
340 |
-
product = st.text_input("¿Qué producto/servicio estás promocionando?", placeholder="Ejemplo: Curso de Inglés")
|
341 |
-
|
342 |
-
# Move "Acción deseada" outside the accordion
|
343 |
-
desired_action = st.text_input("Acción deseada", placeholder="Ejemplo: Registrarse para una prueba gratuita")
|
344 |
-
|
345 |
-
# Move formula selection here, right after desired action
|
346 |
-
selected_formula_key = st.selectbox(
|
347 |
-
"Selecciona una fórmula para tus emails",
|
348 |
-
options=list(email_formulas.email_formulas.keys()),
|
349 |
-
key="formula_selectbox" # Add a unique key
|
350 |
-
)
|
351 |
-
|
352 |
-
# Only one submit button with a unique key
|
353 |
-
submit = st.button("Generar Emails", key="generate_emails_button")
|
354 |
-
|
355 |
-
# Crear un único acordeón para fórmula, creatividad y ángulo
|
356 |
-
with st.expander("Personaliza tus emails"):
|
357 |
-
# 1. Idea Creativa al principio con altura de 70px
|
358 |
-
creative_idea = st.text_area("Idea Creativa", placeholder="Ejemplo: Tu curso es como Netflix: ofrece contenido que engancha y soluciones que la gente realmente quiere ver", height=70)
|
359 |
-
|
360 |
-
# 2. Lo demás (cargador de archivos)
|
361 |
-
uploaded_file = st.file_uploader("📄 Archivo o imagen de referencia",
|
362 |
-
type=['txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'])
|
363 |
-
|
364 |
-
file_content = ""
|
365 |
-
is_image = False
|
366 |
-
image_parts = None
|
367 |
-
|
368 |
-
if uploaded_file is not None:
|
369 |
-
# El código para manejar archivos permanece igual
|
370 |
-
file_type = uploaded_file.name.split('.')[-1].lower()
|
371 |
-
|
372 |
-
# Manejar archivos de texto
|
373 |
-
if file_type in ['txt', 'pdf', 'docx']:
|
374 |
-
# El código para manejar archivos de texto permanece igual
|
375 |
-
# ...
|
376 |
-
if file_type == 'txt':
|
377 |
-
try:
|
378 |
-
file_content = uploaded_file.read().decode('utf-8')
|
379 |
-
st.success(f"Archivo TXT cargado correctamente: {uploaded_file.name}")
|
380 |
-
except Exception as e:
|
381 |
-
st.error(f"Error al leer el archivo TXT: {str(e)}")
|
382 |
-
file_content = ""
|
383 |
-
|
384 |
-
elif file_type == 'pdf':
|
385 |
-
try:
|
386 |
-
import PyPDF2
|
387 |
-
pdf_reader = PyPDF2.PdfReader(uploaded_file)
|
388 |
-
file_content = ""
|
389 |
-
for page in pdf_reader.pages:
|
390 |
-
file_content += page.extract_text() + "\n"
|
391 |
-
st.success(f"Archivo PDF cargado correctamente: {uploaded_file.name}")
|
392 |
-
except Exception as e:
|
393 |
-
st.error(f"Error al leer el archivo PDF: {str(e)}")
|
394 |
-
file_content = ""
|
395 |
-
|
396 |
-
elif file_type == 'docx':
|
397 |
-
try:
|
398 |
-
import docx
|
399 |
-
doc = docx.Document(uploaded_file)
|
400 |
-
file_content = "\n".join([para.text for para in doc.paragraphs])
|
401 |
-
st.success(f"Archivo DOCX cargado correctamente: {uploaded_file.name}")
|
402 |
-
except Exception as e:
|
403 |
-
st.error(f"Error al leer el archivo DOCX: {str(e)}")
|
404 |
-
file_content = ""
|
405 |
-
|
406 |
-
# Manejar archivos de imagen
|
407 |
-
elif file_type in ['jpg', 'jpeg', 'png']:
|
408 |
-
try:
|
409 |
-
from PIL import Image
|
410 |
-
image = Image.open(uploaded_file)
|
411 |
-
image_bytes = uploaded_file.getvalue()
|
412 |
-
image_parts = {
|
413 |
-
"mime_type": uploaded_file.type,
|
414 |
-
"data": image_bytes
|
415 |
-
}
|
416 |
-
is_image = True
|
417 |
-
st.image(image, caption="Imagen cargada", use_column_width=True)
|
418 |
-
except Exception as e:
|
419 |
-
st.error(f"Error processing image: {str(e)}")
|
420 |
-
is_image = False
|
421 |
-
|
422 |
-
# 4. Ángulo
|
423 |
-
angle_keys = ["NINGUNO"] + sorted([key for key in angles.keys() if key != "NINGUNO"])
|
424 |
-
selected_angle = st.selectbox(
|
425 |
-
"Selecciona un ángulo para tus emails",
|
426 |
-
options=angle_keys,
|
427 |
-
key="angle_selectbox" # Add a unique key
|
428 |
-
)
|
429 |
-
|
430 |
-
# 5. Emoción
|
431 |
-
emotion = st.selectbox(
|
432 |
-
"¿Qué emoción quieres evocar?",
|
433 |
-
options=["Curiosidad", "Miedo", "Esperanza", "Entusiasmo", "Confianza", "Urgencia"],
|
434 |
-
key="emotion_selectbox" # Add a unique key
|
435 |
-
)
|
436 |
-
|
437 |
-
# 6. Creatividad (slider)
|
438 |
-
temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1)
|
439 |
-
|
440 |
-
selected_formula = email_formulas.email_formulas[selected_formula_key] # Updated reference
|
441 |
-
|
442 |
-
# Removed the submit button from here
|
443 |
-
# Define a function to validate inputs
|
444 |
-
def validate_inputs(file_content, product, target_audience, emotion, desired_action):
|
445 |
-
"""
|
446 |
-
Validates input combinations and returns a tuple of (is_valid, error_message)
|
447 |
-
"""
|
448 |
-
has_file = file_content.strip() != "" if file_content else False
|
449 |
-
has_product = product.strip() != ""
|
450 |
-
has_audience = target_audience.strip() != ""
|
451 |
-
has_emotion = emotion.strip() != "" if emotion else False
|
452 |
-
has_action = desired_action.strip() != "" if desired_action else False
|
453 |
-
|
454 |
-
# Check for valid combinations
|
455 |
-
if has_file and has_product:
|
456 |
-
return True, "" # File + Product is valid
|
457 |
-
elif has_file and has_audience:
|
458 |
-
return True, "" # File + Audience is valid
|
459 |
-
elif has_product and has_audience and has_emotion and has_action:
|
460 |
-
return True, "" # Product + Audience + Emotion + Action is valid
|
461 |
-
|
462 |
-
# If we get here, no valid combination was found
|
463 |
-
if not (has_emotion and has_action):
|
464 |
-
return False, "Por favor especifica la emoción que quieres evocar y la acción deseada."
|
465 |
-
else:
|
466 |
-
return False, "Por favor proporciona al menos una de estas combinaciones: archivo + producto, archivo + público objetivo, o producto + público objetivo + emoción + acción deseada."
|
467 |
-
|
468 |
-
# Mostrar los emails generados
|
469 |
-
if submit:
|
470 |
-
# Validate inputs using the new function
|
471 |
-
is_valid, error_message = validate_inputs(
|
472 |
-
file_content,
|
473 |
-
product,
|
474 |
-
target_audience,
|
475 |
-
emotion,
|
476 |
-
desired_action
|
477 |
-
)
|
478 |
-
|
479 |
-
if is_valid and selected_formula:
|
480 |
-
try:
|
481 |
-
# Use spinner within col2 context
|
482 |
-
with col2:
|
483 |
-
with st.spinner("Creando los emails..."):
|
484 |
-
# Update the function call to include creative_idea
|
485 |
-
generated_emails = generate_emails(
|
486 |
-
target_audience,
|
487 |
-
product,
|
488 |
-
temperature,
|
489 |
-
selected_formula,
|
490 |
-
selected_angle,
|
491 |
-
file_content,
|
492 |
-
image_parts,
|
493 |
-
is_image,
|
494 |
-
emotion,
|
495 |
-
desired_action,
|
496 |
-
creative_idea # Add the creative idea parameter
|
497 |
-
)
|
498 |
-
|
499 |
-
# Check if the response starts with "Error:"
|
500 |
-
if generated_emails.startswith("Error:"):
|
501 |
-
st.error(generated_emails)
|
502 |
-
else:
|
503 |
-
# Clean the response text to remove extra spaces
|
504 |
-
generated_emails = clean_response_text(generated_emails)
|
505 |
-
|
506 |
-
# Get current timestamp for the filename
|
507 |
-
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
508 |
-
|
509 |
-
# Add a download button ABOVE the results
|
510 |
-
st.download_button(
|
511 |
-
label="DESCARGAR EMAILS",
|
512 |
-
data=generated_emails,
|
513 |
-
file_name=f"emails_persuasivos_{timestamp}.txt",
|
514 |
-
mime="text/plain",
|
515 |
-
key="download_top" # Unique key for the top button
|
516 |
-
)
|
517 |
-
|
518 |
-
# Display the generated emails in col2 (still within col2 context)
|
519 |
-
st.markdown(f"""
|
520 |
-
<div class="results-container">
|
521 |
-
<h4>Tus emails persuasivos:</h4>
|
522 |
-
<p>{generated_emails}</p>
|
523 |
-
</div>
|
524 |
-
""", unsafe_allow_html=True)
|
525 |
-
|
526 |
-
# Download button at the bottom (same as before but with a different key)
|
527 |
-
st.download_button(
|
528 |
-
label="DESCARGAR EMAILS",
|
529 |
-
data=generated_emails,
|
530 |
-
file_name=f"emails_persuasivos_{timestamp}.txt",
|
531 |
-
mime="text/plain",
|
532 |
-
key="download_bottom" # Unique key for the bottom button
|
533 |
-
)
|
534 |
-
except Exception as e:
|
535 |
-
col2.error(f"Error: {str(e)}")
|
536 |
-
else:
|
537 |
-
if not selected_formula:
|
538 |
-
col2.error("Por favor selecciona una fórmula.")
|
539 |
-
else:
|
540 |
-
col2.error(error_message)
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
import streamlit as st
|
3 |
+
import os
|
4 |
+
import google.generativeai as genai
|
5 |
+
import random
|
6 |
+
from streamlit import session_state as state
|
7 |
+
from formulas import email_formulas
|
8 |
+
from angles import angles
|
9 |
+
import re
|
10 |
+
import datetime
|
11 |
+
import PyPDF2
|
12 |
+
import docx
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
# Cargar las variables de entorno
|
16 |
+
load_dotenv()
|
17 |
+
|
18 |
+
# Configurar la API de Google
|
19 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
20 |
+
|
21 |
+
# Fórmulas con ejemplos y explicaciones
|
22 |
+
# email_formulas dictionary has been moved to formulas/email_formulas.py
|
23 |
+
|
24 |
+
# Cambiar el nombre de la función
|
25 |
+
def generate_emails(target_audience, product, temperature, selected_formula, selected_angle, file_content="", image_parts=None, is_image=False, emotion="", desired_action="", creative_idea=""):
|
26 |
+
# Crear la configuración del modelo
|
27 |
+
generation_config = {
|
28 |
+
"temperature": temperature,
|
29 |
+
"top_p": 0.65,
|
30 |
+
"top_k": 360,
|
31 |
+
"max_output_tokens": 8196,
|
32 |
+
}
|
33 |
+
|
34 |
+
model = genai.GenerativeModel(
|
35 |
+
model_name="gemini-2.0-flash",
|
36 |
+
generation_config=generation_config,
|
37 |
+
)
|
38 |
+
|
39 |
+
# Definir las instrucciones de formato una sola vez
|
40 |
+
format_instructions = """
|
41 |
+
FORMAT RULES:
|
42 |
+
- Each email must start with "Correo 1", "Correo 2", etc.
|
43 |
+
- Each email must have a clear and attractive subject line
|
44 |
+
- The email body must be persuasive and emotional
|
45 |
+
- Include a clear call to action
|
46 |
+
- Add a professional signature
|
47 |
+
- Separate each email clearly
|
48 |
+
- Do not include greetings like 'Hello [Name]'
|
49 |
+
- Make sure that the postscripts (P.D.) are smaller and more discrete than the main body
|
50 |
+
- IMPORTANT: The first email must be an introduction without referencing any previous communications
|
51 |
+
- Emails 2-5 should build on the sequence in a logical progression
|
52 |
+
"""
|
53 |
+
|
54 |
+
# Incluir las instrucciones del sistema en el prompt principal
|
55 |
+
system_prompt = f"""You are a world-class direct response copywriter trained by Gary Halbert, Gary Bencivenga, and David Ogilvy.
|
56 |
+
|
57 |
+
You have helped many marketers before me persuade their clients through emotional email sequences.
|
58 |
+
Your task is to create a 5-email sequence that makes my [buyer persona] feel [emotion] about my [product/service] and convince them to register/take [desired action].
|
59 |
+
|
60 |
+
{format_instructions}
|
61 |
+
|
62 |
+
IMPORTANT:
|
63 |
+
- Each email must be unique and memorable
|
64 |
+
- Avoid clichés and generalities
|
65 |
+
- Maintain a persuasive but credible tone
|
66 |
+
- Adapt language to the target audience
|
67 |
+
- Focus on transformative benefits"""
|
68 |
+
|
69 |
+
# Iniciar el prompt con las instrucciones del sistema
|
70 |
+
email_instruction = f"{system_prompt}\n\n"
|
71 |
+
|
72 |
+
# Add instructions for using the enhanced formula structure
|
73 |
+
if hasattr(selected_formula, 'get') and selected_formula.get('subject_line_types') and selected_formula.get('email_structure_template'):
|
74 |
+
email_instruction += """
|
75 |
+
ENHANCED FORMULA STRUCTURE:
|
76 |
+
Use the following structure elements to create more effective emails:
|
77 |
+
|
78 |
+
SUBJECT LINE TYPES:
|
79 |
+
"""
|
80 |
+
# Add subject line types with descriptions
|
81 |
+
for subject_type, description in selected_formula.get('subject_line_types', {}).items():
|
82 |
+
email_instruction += f"- {subject_type}: {description}\n"
|
83 |
+
|
84 |
+
# Add technique types (either infotainment or nurturing)
|
85 |
+
technique_key = next((k for k in selected_formula.keys() if k.endswith('_techniques')), None)
|
86 |
+
if technique_key:
|
87 |
+
email_instruction += f"\n{technique_key.upper()}:\n"
|
88 |
+
for technique, description in selected_formula.get(technique_key, {}).items():
|
89 |
+
email_instruction += f"- {technique}: {description}\n"
|
90 |
+
|
91 |
+
# Add email structure template
|
92 |
+
email_instruction += "\nEMAIL STRUCTURE TEMPLATE:\n"
|
93 |
+
for email_num, structure in selected_formula.get('email_structure_template', {}).items():
|
94 |
+
email_instruction += f"\n{email_num.upper()}:\n"
|
95 |
+
email_instruction += f"- Purpose: {structure.get('purpose', '')}\n"
|
96 |
+
email_instruction += f"- Emotional Focus: {structure.get('emotional_focus', '')}\n"
|
97 |
+
|
98 |
+
# Add recommended subject types
|
99 |
+
if structure.get('recommended_subject_types'):
|
100 |
+
email_instruction += "- Recommended Subject Types: " + ", ".join(structure.get('recommended_subject_types', [])) + "\n"
|
101 |
+
|
102 |
+
# Add recommended techniques
|
103 |
+
if structure.get('recommended_techniques'):
|
104 |
+
email_instruction += "- Recommended Techniques: " + ", ".join(structure.get('recommended_techniques', [])) + "\n"
|
105 |
+
|
106 |
+
# Add key elements
|
107 |
+
if structure.get('key_elements'):
|
108 |
+
email_instruction += "- Key Elements:\n"
|
109 |
+
for element in structure.get('key_elements', []):
|
110 |
+
email_instruction += f" * {element}\n"
|
111 |
+
|
112 |
+
# Añadir instrucciones para la idea creativa si existe
|
113 |
+
if creative_idea:
|
114 |
+
email_instruction += f"""
|
115 |
+
CREATIVE CONCEPT:
|
116 |
+
Use the following creative concept as the central theme for all emails in the sequence:
|
117 |
+
"{creative_idea}"
|
118 |
+
|
119 |
+
CREATIVE CONCEPT INSTRUCTIONS:
|
120 |
+
1. This concept should be the unifying theme across all emails
|
121 |
+
2. Use it as a metaphor or analogy throughout the sequence
|
122 |
+
3. Develop different aspects of this concept in each email
|
123 |
+
4. Make sure the concept naturally connects to the product benefits
|
124 |
+
5. The concept should make the emails more memorable and engaging
|
125 |
+
"""
|
126 |
+
|
127 |
+
# Añadir contenido del archivo si existe
|
128 |
+
if file_content:
|
129 |
+
email_instruction += f"""
|
130 |
+
REFERENCE CONTENT:
|
131 |
+
Carefully analyze the following content as a reference for generating emails:
|
132 |
+
{file_content[:3000]}
|
133 |
+
|
134 |
+
ANALYSIS INSTRUCTIONS:
|
135 |
+
1. Extract key information about the product or service mentioned
|
136 |
+
2. Identify the tone, style, and language used
|
137 |
+
3. Detect any data about the target audience or customer avatar
|
138 |
+
4. Look for benefits, features, or pain points mentioned
|
139 |
+
5. Use relevant terms, phrases, or concepts from the content
|
140 |
+
6. Maintain consistency with the brand identity or main message
|
141 |
+
7. Adapt the emails to resonate with the provided content
|
142 |
+
|
143 |
+
IMPORTANT COMBINATIONS:
|
144 |
+
"""
|
145 |
+
# Updated conditions for specific input combinations
|
146 |
+
if product and not target_audience:
|
147 |
+
email_instruction += f"""- FILE + PRODUCT: You have a reference document and product ({product}). Create emails that highlight this specific product's benefits and features using insights from the document. Extract audience information from the document to better target the emails.
|
148 |
+
"""
|
149 |
+
elif target_audience and not product:
|
150 |
+
email_instruction += f"""- FILE + TARGET AUDIENCE: You have a reference document and target audience ({target_audience}). Create emails tailored to this specific audience using language and concepts from the document. Identify products or services from the document that would appeal to this audience.
|
151 |
+
"""
|
152 |
+
elif product and target_audience:
|
153 |
+
email_instruction += f"""- PRODUCT + TARGET AUDIENCE: You have both product ({product}) and target audience ({target_audience}). Create emails that connect this specific product with this specific audience, using insights from the document to strengthen the connection.
|
154 |
+
"""
|
155 |
+
|
156 |
+
email_instruction += """
|
157 |
+
IMPORTANT: Naturally integrate the elements found in the content with the selected formula and angle.
|
158 |
+
"""
|
159 |
+
|
160 |
+
# Preparar instrucciones específicas del ángulo una sola vez
|
161 |
+
angle_instructions = ""
|
162 |
+
if selected_angle != "NINGUNO":
|
163 |
+
angle_instructions = f"""
|
164 |
+
MAIN ANGLE: {selected_angle}
|
165 |
+
SPECIFIC ANGLE INSTRUCTIONS:
|
166 |
+
{angles[selected_angle]["instruction"]}
|
167 |
+
|
168 |
+
IMPORTANT: The angle {selected_angle} must be applied as a "style layer" over the formula structure:
|
169 |
+
1. Keep the base structure of the formula intact
|
170 |
+
2. Apply the tone and style of the {selected_angle} angle
|
171 |
+
3. Ensure each element of the formula reflects the angle
|
172 |
+
4. The angle affects "how" it's said, not "what" is said
|
173 |
+
|
174 |
+
SUCCESSFUL EXAMPLES OF THE {selected_angle} ANGLE:
|
175 |
+
"""
|
176 |
+
for example in angles[selected_angle]["examples"]:
|
177 |
+
angle_instructions += f"- {example}\n"
|
178 |
+
|
179 |
+
# Añadir las instrucciones del ángulo al prompt principal
|
180 |
+
email_instruction += angle_instructions
|
181 |
+
|
182 |
+
# Dentro de la función, actualizar el prompt para incluir emoción y acción deseada
|
183 |
+
email_instruction += (
|
184 |
+
f"\nYour task is to create 5 persuasive emails for {target_audience} "
|
185 |
+
f"that evoke {emotion} and convince them to {desired_action} about {product}. "
|
186 |
+
)
|
187 |
+
|
188 |
+
# Usar la variable angle_instructions para determinar si hay un ángulo seleccionado
|
189 |
+
if angle_instructions:
|
190 |
+
email_instruction += f"IMPORTANT: Each email MUST follow the {selected_angle} angle clearly and consistently."
|
191 |
+
|
192 |
+
email_instruction += "\n\n"
|
193 |
+
|
194 |
+
# Take the first 5 examples (or all if less than 5) in order
|
195 |
+
sequential_examples = selected_formula['examples'][:min(5, len(selected_formula['examples']))]
|
196 |
+
|
197 |
+
email_instruction += "FORMULA EXAMPLES TO FOLLOW:\n"
|
198 |
+
for i, example in enumerate(sequential_examples, 1):
|
199 |
+
email_instruction += f"{i}. {example}\n"
|
200 |
+
|
201 |
+
# Añadir instrucciones específicas sobre cómo seguir los ejemplos
|
202 |
+
email_instruction += "\nSPECIFIC INSTRUCTIONS:\n"
|
203 |
+
email_instruction += "1. Maintain the same structure and length as the previous examples\n"
|
204 |
+
email_instruction += "2. Use the same tone and writing style\n"
|
205 |
+
email_instruction += "3. Replicate the phrase construction patterns\n"
|
206 |
+
email_instruction += "4. Preserve the level of specificity and detail\n"
|
207 |
+
email_instruction += f"5. Adapt the content for {target_audience} while maintaining the essence of the examples\n\n"
|
208 |
+
|
209 |
+
# Añadir instrucciones específicas sobre la temperatura creativa
|
210 |
+
email_instruction += f"\nCREATIVITY LEVEL: {temperature}. Higher values mean more creative and original content.\n\n"
|
211 |
+
|
212 |
+
email_instruction += f"FORMULA TO FOLLOW:\n{selected_formula['description']}\n\n"
|
213 |
+
|
214 |
+
# Consolidar las instrucciones finales en un solo bloque
|
215 |
+
final_reminder = ["Follow the structure of the selected formula"]
|
216 |
+
|
217 |
+
# Add angle-specific instructions only if an angle is selected
|
218 |
+
if selected_angle != "NINGUNO":
|
219 |
+
final_reminder.extend([
|
220 |
+
"Apply the angle as a 'style layer'",
|
221 |
+
"Maintain coherence between formula and angle",
|
222 |
+
"Ensure each email reflects both elements"
|
223 |
+
])
|
224 |
+
|
225 |
+
email_instruction += "\nFINAL REMINDER:\n"
|
226 |
+
for i, reminder in enumerate(final_reminder, 1):
|
227 |
+
email_instruction += f"{i}. {reminder}\n"
|
228 |
+
|
229 |
+
email_instruction += "\nGENERATE NOW:\nCreate 5 emails that faithfully follow the style and structure of the examples shown.\n"
|
230 |
+
|
231 |
+
# Modificar la forma de enviar el mensaje según si hay imagen o no
|
232 |
+
message_parts = [email_instruction]
|
233 |
+
|
234 |
+
# Build instruction text more clearly with conditional components
|
235 |
+
instruction_components = ["Generate the emails in Spanish following exactly the style and structure of the examples shown."]
|
236 |
+
|
237 |
+
# Add the image to the message parts if it exists
|
238 |
+
if is_image and image_parts:
|
239 |
+
message_parts.append(image_parts)
|
240 |
+
instruction_components.append("drawing inspiration from the provided image.")
|
241 |
+
|
242 |
+
# Add final instruction
|
243 |
+
instruction_components.append("Do not include explanations, only the emails.")
|
244 |
+
|
245 |
+
# Join all instruction components with proper spacing
|
246 |
+
instruction_text = " ".join(instruction_components)
|
247 |
+
|
248 |
+
# Create the chat session with the message parts
|
249 |
+
try:
|
250 |
+
chat_session = model.start_chat(
|
251 |
+
history=[
|
252 |
+
{
|
253 |
+
"role": "user",
|
254 |
+
"parts": message_parts,
|
255 |
+
},
|
256 |
+
]
|
257 |
+
)
|
258 |
+
|
259 |
+
# Enviar el mensaje con las instrucciones
|
260 |
+
response = chat_session.send_message(instruction_text)
|
261 |
+
|
262 |
+
return response.text
|
263 |
+
except genai.types.generation_types.StopCandidateException as e:
|
264 |
+
# Handle content filtering/safety issues
|
265 |
+
error_message = f"La generación se detuvo debido a restricciones de contenido: {str(e)}"
|
266 |
+
st.error(error_message)
|
267 |
+
return f"Error: {error_message}"
|
268 |
+
except genai.types.generation_types.BlockedPromptException as e:
|
269 |
+
# Handle blocked prompt issues
|
270 |
+
error_message = f"El prompt fue bloqueado por políticas de contenido: {str(e)}"
|
271 |
+
st.error(error_message)
|
272 |
+
return f"Error: {error_message}"
|
273 |
+
except Exception as e:
|
274 |
+
# Handle general API errors
|
275 |
+
error_message = f"Error al comunicarse con la API de Google: {str(e)}"
|
276 |
+
st.error(error_message)
|
277 |
+
return f"Error: {error_message}"
|
278 |
+
|
279 |
+
# Define the clean_response_text function before it's used
|
280 |
+
def clean_response_text(text):
|
281 |
+
"""Remove extra spaces and normalize whitespace in the response text"""
|
282 |
+
# Replace multiple newlines with just two
|
283 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
284 |
+
# Remove leading/trailing whitespace
|
285 |
+
text = text.strip()
|
286 |
+
return text
|
287 |
+
|
288 |
+
# Configurar la interfaz de usuario con Streamlit
|
289 |
+
st.set_page_config(
|
290 |
+
page_title="Email Composer",
|
291 |
+
layout="wide",
|
292 |
+
menu_items={}, # Empty dict removes the three-dot menu
|
293 |
+
initial_sidebar_state="expanded"
|
294 |
+
)
|
295 |
+
|
296 |
+
# Add custom CSS to reduce margins
|
297 |
+
st.markdown("""
|
298 |
+
<style>
|
299 |
+
.main > div {
|
300 |
+
padding-top: 1rem;
|
301 |
+
}
|
302 |
+
</style>
|
303 |
+
""", unsafe_allow_html=True)
|
304 |
+
|
305 |
+
# Leer el contenido del archivo manual.md
|
306 |
+
manual_path = "manual.md"
|
307 |
+
if os.path.exists(manual_path):
|
308 |
+
with open(manual_path, "r", encoding="utf-8") as file:
|
309 |
+
manual_content = file.read()
|
310 |
+
# Mostrar el contenido del manual en el sidebar
|
311 |
+
st.sidebar.markdown(manual_content)
|
312 |
+
else:
|
313 |
+
st.sidebar.warning("Manual file not found.")
|
314 |
+
|
315 |
+
# Load CSS from file
|
316 |
+
css_path = "styles/main.css"
|
317 |
+
if os.path.exists(css_path):
|
318 |
+
with open(css_path, "r") as f:
|
319 |
+
css = f.read()
|
320 |
+
# Apply the CSS
|
321 |
+
st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)
|
322 |
+
else:
|
323 |
+
st.warning("CSS file not found.")
|
324 |
+
|
325 |
+
# Centrar el título y el subtítulo
|
326 |
+
st.markdown("<h1 style='text-align: center;'>Generador de Emails</h1>", unsafe_allow_html=True)
|
327 |
+
st.markdown("<h4 style='text-align: center;'>Transforma tu marketing con emails persuasivos que convierten. Esta aplicación es tu arma secreta para crear emails emocionales de respuesta directa que impulsan a la acción.</h4>", unsafe_allow_html=True)
|
328 |
+
|
329 |
+
# Crear columnas
|
330 |
+
col1, col2 = st.columns([1, 2])
|
331 |
+
|
332 |
+
# Initialize these variables at the top level before the UI components
|
333 |
+
file_content = ""
|
334 |
+
is_image = False
|
335 |
+
image_parts = None
|
336 |
+
|
337 |
+
# Columnas de entrada
|
338 |
+
with col1:
|
339 |
+
target_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Estudiantes Universitarios")
|
340 |
+
product = st.text_input("¿Qué producto/servicio estás promocionando?", placeholder="Ejemplo: Curso de Inglés")
|
341 |
+
|
342 |
+
# Move "Acción deseada" outside the accordion
|
343 |
+
desired_action = st.text_input("Acción deseada", placeholder="Ejemplo: Registrarse para una prueba gratuita")
|
344 |
+
|
345 |
+
# Move formula selection here, right after desired action
|
346 |
+
selected_formula_key = st.selectbox(
|
347 |
+
"Selecciona una fórmula para tus emails",
|
348 |
+
options=list(email_formulas.email_formulas.keys()),
|
349 |
+
key="formula_selectbox" # Add a unique key
|
350 |
+
)
|
351 |
+
|
352 |
+
# Only one submit button with a unique key
|
353 |
+
submit = st.button("Generar Emails", key="generate_emails_button")
|
354 |
+
|
355 |
+
# Crear un único acordeón para fórmula, creatividad y ángulo
|
356 |
+
with st.expander("Personaliza tus emails"):
|
357 |
+
# 1. Idea Creativa al principio con altura de 70px
|
358 |
+
creative_idea = st.text_area("Idea Creativa", placeholder="Ejemplo: Tu curso es como Netflix: ofrece contenido que engancha y soluciones que la gente realmente quiere ver", height=70)
|
359 |
+
|
360 |
+
# 2. Lo demás (cargador de archivos)
|
361 |
+
uploaded_file = st.file_uploader("📄 Archivo o imagen de referencia",
|
362 |
+
type=['txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'])
|
363 |
+
|
364 |
+
file_content = ""
|
365 |
+
is_image = False
|
366 |
+
image_parts = None
|
367 |
+
|
368 |
+
if uploaded_file is not None:
|
369 |
+
# El código para manejar archivos permanece igual
|
370 |
+
file_type = uploaded_file.name.split('.')[-1].lower()
|
371 |
+
|
372 |
+
# Manejar archivos de texto
|
373 |
+
if file_type in ['txt', 'pdf', 'docx']:
|
374 |
+
# El código para manejar archivos de texto permanece igual
|
375 |
+
# ...
|
376 |
+
if file_type == 'txt':
|
377 |
+
try:
|
378 |
+
file_content = uploaded_file.read().decode('utf-8')
|
379 |
+
st.success(f"Archivo TXT cargado correctamente: {uploaded_file.name}")
|
380 |
+
except Exception as e:
|
381 |
+
st.error(f"Error al leer el archivo TXT: {str(e)}")
|
382 |
+
file_content = ""
|
383 |
+
|
384 |
+
elif file_type == 'pdf':
|
385 |
+
try:
|
386 |
+
import PyPDF2
|
387 |
+
pdf_reader = PyPDF2.PdfReader(uploaded_file)
|
388 |
+
file_content = ""
|
389 |
+
for page in pdf_reader.pages:
|
390 |
+
file_content += page.extract_text() + "\n"
|
391 |
+
st.success(f"Archivo PDF cargado correctamente: {uploaded_file.name}")
|
392 |
+
except Exception as e:
|
393 |
+
st.error(f"Error al leer el archivo PDF: {str(e)}")
|
394 |
+
file_content = ""
|
395 |
+
|
396 |
+
elif file_type == 'docx':
|
397 |
+
try:
|
398 |
+
import docx
|
399 |
+
doc = docx.Document(uploaded_file)
|
400 |
+
file_content = "\n".join([para.text for para in doc.paragraphs])
|
401 |
+
st.success(f"Archivo DOCX cargado correctamente: {uploaded_file.name}")
|
402 |
+
except Exception as e:
|
403 |
+
st.error(f"Error al leer el archivo DOCX: {str(e)}")
|
404 |
+
file_content = ""
|
405 |
+
|
406 |
+
# Manejar archivos de imagen
|
407 |
+
elif file_type in ['jpg', 'jpeg', 'png']:
|
408 |
+
try:
|
409 |
+
from PIL import Image
|
410 |
+
image = Image.open(uploaded_file)
|
411 |
+
image_bytes = uploaded_file.getvalue()
|
412 |
+
image_parts = {
|
413 |
+
"mime_type": uploaded_file.type,
|
414 |
+
"data": image_bytes
|
415 |
+
}
|
416 |
+
is_image = True
|
417 |
+
st.image(image, caption="Imagen cargada", use_column_width=True)
|
418 |
+
except Exception as e:
|
419 |
+
st.error(f"Error processing image: {str(e)}")
|
420 |
+
is_image = False
|
421 |
+
|
422 |
+
# 4. Ángulo
|
423 |
+
angle_keys = ["NINGUNO"] + sorted([key for key in angles.keys() if key != "NINGUNO"])
|
424 |
+
selected_angle = st.selectbox(
|
425 |
+
"Selecciona un ángulo para tus emails",
|
426 |
+
options=angle_keys,
|
427 |
+
key="angle_selectbox" # Add a unique key
|
428 |
+
)
|
429 |
+
|
430 |
+
# 5. Emoción
|
431 |
+
emotion = st.selectbox(
|
432 |
+
"¿Qué emoción quieres evocar?",
|
433 |
+
options=["Curiosidad", "Miedo", "Esperanza", "Entusiasmo", "Confianza", "Urgencia"],
|
434 |
+
key="emotion_selectbox" # Add a unique key
|
435 |
+
)
|
436 |
+
|
437 |
+
# 6. Creatividad (slider)
|
438 |
+
temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1)
|
439 |
+
|
440 |
+
selected_formula = email_formulas.email_formulas[selected_formula_key] # Updated reference
|
441 |
+
|
442 |
+
# Removed the submit button from here
|
443 |
+
# Define a function to validate inputs
|
444 |
+
def validate_inputs(file_content, product, target_audience, emotion, desired_action):
|
445 |
+
"""
|
446 |
+
Validates input combinations and returns a tuple of (is_valid, error_message)
|
447 |
+
"""
|
448 |
+
has_file = file_content.strip() != "" if file_content else False
|
449 |
+
has_product = product.strip() != ""
|
450 |
+
has_audience = target_audience.strip() != ""
|
451 |
+
has_emotion = emotion.strip() != "" if emotion else False
|
452 |
+
has_action = desired_action.strip() != "" if desired_action else False
|
453 |
+
|
454 |
+
# Check for valid combinations
|
455 |
+
if has_file and has_product:
|
456 |
+
return True, "" # File + Product is valid
|
457 |
+
elif has_file and has_audience:
|
458 |
+
return True, "" # File + Audience is valid
|
459 |
+
elif has_product and has_audience and has_emotion and has_action:
|
460 |
+
return True, "" # Product + Audience + Emotion + Action is valid
|
461 |
+
|
462 |
+
# If we get here, no valid combination was found
|
463 |
+
if not (has_emotion and has_action):
|
464 |
+
return False, "Por favor especifica la emoción que quieres evocar y la acción deseada."
|
465 |
+
else:
|
466 |
+
return False, "Por favor proporciona al menos una de estas combinaciones: archivo + producto, archivo + público objetivo, o producto + público objetivo + emoción + acción deseada."
|
467 |
+
|
468 |
+
# Mostrar los emails generados
|
469 |
+
if submit:
|
470 |
+
# Validate inputs using the new function
|
471 |
+
is_valid, error_message = validate_inputs(
|
472 |
+
file_content,
|
473 |
+
product,
|
474 |
+
target_audience,
|
475 |
+
emotion,
|
476 |
+
desired_action
|
477 |
+
)
|
478 |
+
|
479 |
+
if is_valid and selected_formula:
|
480 |
+
try:
|
481 |
+
# Use spinner within col2 context
|
482 |
+
with col2:
|
483 |
+
with st.spinner("Creando los emails..."):
|
484 |
+
# Update the function call to include creative_idea
|
485 |
+
generated_emails = generate_emails(
|
486 |
+
target_audience,
|
487 |
+
product,
|
488 |
+
temperature,
|
489 |
+
selected_formula,
|
490 |
+
selected_angle,
|
491 |
+
file_content,
|
492 |
+
image_parts,
|
493 |
+
is_image,
|
494 |
+
emotion,
|
495 |
+
desired_action,
|
496 |
+
creative_idea # Add the creative idea parameter
|
497 |
+
)
|
498 |
+
|
499 |
+
# Check if the response starts with "Error:"
|
500 |
+
if generated_emails.startswith("Error:"):
|
501 |
+
st.error(generated_emails)
|
502 |
+
else:
|
503 |
+
# Clean the response text to remove extra spaces
|
504 |
+
generated_emails = clean_response_text(generated_emails)
|
505 |
+
|
506 |
+
# Get current timestamp for the filename
|
507 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
508 |
+
|
509 |
+
# Add a download button ABOVE the results
|
510 |
+
st.download_button(
|
511 |
+
label="DESCARGAR EMAILS",
|
512 |
+
data=generated_emails,
|
513 |
+
file_name=f"emails_persuasivos_{timestamp}.txt",
|
514 |
+
mime="text/plain",
|
515 |
+
key="download_top" # Unique key for the top button
|
516 |
+
)
|
517 |
+
|
518 |
+
# Display the generated emails in col2 (still within col2 context)
|
519 |
+
st.markdown(f"""
|
520 |
+
<div class="results-container">
|
521 |
+
<h4>Tus emails persuasivos:</h4>
|
522 |
+
<p>{generated_emails}</p>
|
523 |
+
</div>
|
524 |
+
""", unsafe_allow_html=True)
|
525 |
+
|
526 |
+
# Download button at the bottom (same as before but with a different key)
|
527 |
+
st.download_button(
|
528 |
+
label="DESCARGAR EMAILS",
|
529 |
+
data=generated_emails,
|
530 |
+
file_name=f"emails_persuasivos_{timestamp}.txt",
|
531 |
+
mime="text/plain",
|
532 |
+
key="download_bottom" # Unique key for the bottom button
|
533 |
+
)
|
534 |
+
except Exception as e:
|
535 |
+
col2.error(f"Error: {str(e)}")
|
536 |
+
else:
|
537 |
+
if not selected_formula:
|
538 |
+
col2.error("Por favor selecciona una fórmula.")
|
539 |
+
else:
|
540 |
+
col2.error(error_message)
|
formulas/email_formulas.py
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
manual.md
CHANGED
@@ -1,104 +1,125 @@
|
|
1 |
-
# Manual de Usuario
|
2 |
-
|
3 |
-
### Introducción
|
4 |
-
Bienvenido a Email Generator CopyXpert, tu asistente avanzado para crear secuencias de emails persuasivos. Esta herramienta está diseñada para transformar tus conceptos de marketing en campañas de email que capturan la atención, construyen relaciones y generan conversiones.
|
5 |
-
|
6 |
-
### Guía Rápida de Uso
|
7 |
-
|
8 |
-
#### 1. Información Básica
|
9 |
-
- **Público Objetivo**
|
10 |
-
- Define claramente tu audiencia
|
11 |
-
- Ejemplo: "Emprendedores digitales", "Profesionales freelance", "Clientes de e-commerce"
|
12 |
-
- Sé específico para resultados óptimos
|
13 |
-
|
14 |
-
- **Producto o Servicio**
|
15 |
-
- Describe tu oferta concisamente
|
16 |
-
- Ejemplo: "Curso de yoga online", "Software de productividad", "Servicios de consultoría"
|
17 |
-
- Incluye detalles relevantes sin extenderte
|
18 |
-
|
19 |
-
- **Selección de Fórmula**
|
20 |
-
- Elige entre las fórmulas disponibles según tus objetivos:
|
21 |
-
-
|
22 |
-
-
|
23 |
-
-
|
24 |
-
|
25 |
-
- **
|
26 |
-
|
27 |
-
|
28 |
-
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
- **
|
44 |
-
|
45 |
-
|
46 |
-
-
|
47 |
-
|
48 |
-
|
49 |
-
-
|
50 |
-
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
- Email
|
56 |
-
|
57 |
-
|
58 |
-
-
|
59 |
-
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
- **
|
65 |
-
-
|
66 |
-
-
|
67 |
-
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
1
|
73 |
-
2
|
74 |
-
|
75 |
-
|
76 |
-
5
|
77 |
-
|
78 |
-
####
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
-
|
88 |
-
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
1.
|
101 |
-
2.
|
102 |
-
3.
|
103 |
-
4.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
5. Prueba diferentes variaciones para optimizar resultados
|
|
|
1 |
+
# Manual de Usuario
|
2 |
+
|
3 |
+
### Introducción
|
4 |
+
Bienvenido a Email Generator CopyXpert, tu asistente avanzado para crear secuencias de emails persuasivos. Esta herramienta está diseñada para transformar tus conceptos de marketing en campañas de email que capturan la atención, construyen relaciones y generan conversiones.
|
5 |
+
|
6 |
+
### Guía Rápida de Uso
|
7 |
+
|
8 |
+
#### 1. Información Básica
|
9 |
+
- **Público Objetivo**
|
10 |
+
- Define claramente tu audiencia
|
11 |
+
- Ejemplo: "Emprendedores digitales", "Profesionales freelance", "Clientes de e-commerce"
|
12 |
+
- Sé específico para resultados óptimos
|
13 |
+
|
14 |
+
- **Producto o Servicio**
|
15 |
+
- Describe tu oferta concisamente
|
16 |
+
- Ejemplo: "Curso de yoga online", "Software de productividad", "Servicios de consultoría"
|
17 |
+
- Incluye detalles relevantes sin extenderte
|
18 |
+
|
19 |
+
- **Selección de Fórmula**
|
20 |
+
- Elige entre las fórmulas disponibles según tus objetivos:
|
21 |
+
- **Soap Opera Sequence**: Narrativa emocional con arco dramático
|
22 |
+
- **Nurturing Sequence**: Cultiva relaciones con prospectos para conversiones futuras
|
23 |
+
- **Infotainment**: Equilibrio entre información y entretenimiento
|
24 |
+
- **Conversión Directa**: Enfoque conversacional y natural para ventas
|
25 |
+
- **Carrito Abandonado**: Recupera clientes potenciales que no completaron la compra
|
26 |
+
|
27 |
+
- **Estructura de la Secuencia**
|
28 |
+
- Todas las fórmulas generan secuencias completas de 5 emails
|
29 |
+
- Cada email cumple un propósito específico en el recorrido del cliente
|
30 |
+
- La secuencia está diseñada para una progresión natural hacia la conversión
|
31 |
+
|
32 |
+
#### 2. Panel de Personalización
|
33 |
+
|
34 |
+
##### Control de Creatividad
|
35 |
+
- **Ajuste de Temperatura (0.0 - 2.0)**
|
36 |
+
- 0.0-0.7: Conservador y directo
|
37 |
+
- 0.8-1.2: Balance óptimo
|
38 |
+
- 1.3-2.0: Experimental y creativo
|
39 |
+
|
40 |
+
##### Fórmulas Disponibles
|
41 |
+
|
42 |
+
#### Soap Opera Sequence
|
43 |
+
- **Estructura**: Narrativa emocional con arco dramático completo
|
44 |
+
- **Ideal para**: Crear conexión emocional profunda y generar anticipación
|
45 |
+
- **Elementos clave**:
|
46 |
+
- Introducción cautivadora con elementos de vulnerabilidad
|
47 |
+
- Desarrollo del problema con alto contenido dramático
|
48 |
+
- Momento de revelación y descubrimiento
|
49 |
+
- Presentación de la solución como transformación
|
50 |
+
- Cierre con sentido de urgencia y oportunidad
|
51 |
+
|
52 |
+
#### Nurturing Sequence
|
53 |
+
- **Estructura**: Secuencia que proporciona valor constante para construir relación
|
54 |
+
- **Elementos clave**:
|
55 |
+
- Email 1: Valor inmediato y establecimiento de expectativas
|
56 |
+
- Email 2: Manejo de objeciones y construcción de confianza
|
57 |
+
- Email 3: Establecimiento de autoridad y credibilidad profunda
|
58 |
+
- Email 4: Presentación de la solución y creación de deseo
|
59 |
+
- Email 5: Creación de urgencia y motivación a la acción inmediata
|
60 |
+
|
61 |
+
#### Infotainment
|
62 |
+
- **Estructura**: Información valiosa presentada de forma entretenida
|
63 |
+
- **Ideal para**: Educación de audiencia y construcción de autoridad
|
64 |
+
- **Elementos clave**:
|
65 |
+
- Equilibrio entre contenido educativo y entretenimiento
|
66 |
+
- Uso de historias, analogías y ejemplos sorprendentes
|
67 |
+
- Construcción gradual de credibilidad y confianza
|
68 |
+
|
69 |
+
#### Conversión Directa
|
70 |
+
- **Estructura**: Comunicación natural que guía hacia una acción específica
|
71 |
+
- **Variantes**:
|
72 |
+
- Email 1: Conexión inicial y valor anticipado
|
73 |
+
- Email 2: Credibilidad a través de historias
|
74 |
+
- Email 3: Expansión de beneficios específicos
|
75 |
+
- Email 4: Presentación natural de la oferta
|
76 |
+
- Email 5: Cierre con sentido de oportunidad
|
77 |
+
|
78 |
+
#### Carrito Abandonado
|
79 |
+
- **Elementos**:
|
80 |
+
- Recordatorio amistoso del producto/servicio
|
81 |
+
- Eliminación de objeciones mediante historias
|
82 |
+
- Creación de urgencia genuina
|
83 |
+
- Incentivos oportunos
|
84 |
+
- Garantías presentadas conversacionalmente
|
85 |
+
- **Combinaciones estratégicas**:
|
86 |
+
- Recordatorio + Beneficios: Valor y oportunidad
|
87 |
+
- Testimonios + Garantías: Confianza y seguridad
|
88 |
+
- Urgencia + Incentivos: Motivación para completar la compra
|
89 |
+
|
90 |
+
### Mejores Prácticas
|
91 |
+
|
92 |
+
#### Para Resultados Óptimos
|
93 |
+
1. Sé específico con tu audiencia
|
94 |
+
2. Define claramente tu producto o servicio
|
95 |
+
3. Selecciona la fórmula adecuada para tu objetivo
|
96 |
+
4. Personaliza los emails según el recorrido del cliente
|
97 |
+
5. Mantén un tono conversacional y auténtico
|
98 |
+
|
99 |
+
#### Qué Evitar
|
100 |
+
1. Lenguaje excesivamente promocional
|
101 |
+
2. Estructuras rígidas o poco naturales
|
102 |
+
3. Técnicas de presión obvias
|
103 |
+
4. Promesas exageradas o poco creíbles
|
104 |
+
|
105 |
+
### Solución de Problemas
|
106 |
+
|
107 |
+
#### Problemas Comunes
|
108 |
+
- **Emails demasiado genéricos**
|
109 |
+
- Solución: Mayor especificidad en la descripción
|
110 |
+
- Incluir detalles concretos sobre tu audiencia
|
111 |
+
|
112 |
+
- **Tono poco natural**
|
113 |
+
- Solución: Ajustar creatividad a nivel moderado
|
114 |
+
- Enfocarse en un estilo conversacional
|
115 |
+
|
116 |
+
- **Baja tasa de conversión**
|
117 |
+
- Solución: Revisar la alineación entre oferta y audiencia
|
118 |
+
- Fortalecer elementos de prueba social y garantías
|
119 |
+
|
120 |
+
### Consejos Avanzados
|
121 |
+
1. Utiliza técnicas de storytelling para mayor conexión emocional
|
122 |
+
2. Incorpora elementos de prueba social de forma natural
|
123 |
+
3. Personaliza los asuntos según el tipo recomendado para cada email
|
124 |
+
4. Equilibra información valiosa con llamadas a la acción claras
|
125 |
5. Prueba diferentes variaciones para optimizar resultados
|