from dotenv import load_dotenv import streamlit as st import os import google.generativeai as genai import random from streamlit import session_state as state from formulas import email_formulas # Updated import statement from angles import angles # Cargar las variables de entorno load_dotenv() # Configurar la API de Google genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Fórmulas con ejemplos y explicaciones # email_formulas dictionary has been moved to formulas/email_formulas.py # Cambiar el nombre de la función def generate_emails(target_audience, product, temperature, selected_formula, selected_angle, file_content="", image_parts=None, is_image=False, emotion="", desired_action="", creative_idea=""): # Crear la configuración del modelo generation_config = { "temperature": temperature, "top_p": 0.65, "top_k": 360, "max_output_tokens": 8196, } model = genai.GenerativeModel( model_name="gemini-2.0-flash", generation_config=generation_config, ) # Definir las instrucciones de formato una sola vez format_instructions = """ FORMAT RULES: - Each email must have a clear and attractive subject line - The email body must be persuasive and emotional - Include a clear call to action - Add a professional signature - Separate each email with a dividing line - Do not include greetings like 'Hello [Name]' - Make sure that the postscripts (P.D.) are smaller and more discrete than the main body """ # Incluir las instrucciones del sistema en el prompt principal system_prompt = f"""You are a world-class direct response copywriter trained by Gary Halbert, Gary Bencivenga, and David Ogilvy. You have helped many marketers before me persuade their clients through emotional email sequences. 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]. {format_instructions} IMPORTANT: - Each email must be unique and memorable - Avoid clichés and generalities - Maintain a persuasive but credible tone - Adapt language to the target audience - Focus on transformative benefits""" # Iniciar el prompt con las instrucciones del sistema email_instruction = f"{system_prompt}\n\n" # Añadir instrucciones para la idea creativa si existe if creative_idea: email_instruction += f""" CREATIVE CONCEPT: Use the following creative concept as the central theme for all emails in the sequence: "{creative_idea}" CREATIVE CONCEPT INSTRUCTIONS: 1. This concept should be the unifying theme across all emails 2. Use it as a metaphor or analogy throughout the sequence 3. Develop different aspects of this concept in each email 4. Make sure the concept naturally connects to the product benefits 5. The concept should make the emails more memorable and engaging """ # Añadir contenido del archivo si existe if file_content: email_instruction += f""" REFERENCE CONTENT: Carefully analyze the following content as a reference for generating emails: {file_content[:3000]} ANALYSIS INSTRUCTIONS: 1. Extract key information about the product or service mentioned 2. Identify the tone, style, and language used 3. Detect any data about the target audience or customer avatar 4. Look for benefits, features, or pain points mentioned 5. Use relevant terms, phrases, or concepts from the content 6. Maintain consistency with the brand identity or main message 7. Adapt the emails to resonate with the provided content IMPORTANT COMBINATIONS: """ # Updated conditions for specific input combinations if product and not target_audience: 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. """ elif target_audience and not product: 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. """ elif product and target_audience: 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. """ email_instruction += """ IMPORTANT: Naturally integrate the elements found in the content with the selected formula and angle. """ # Preparar instrucciones específicas del ángulo una sola vez angle_instructions = "" if selected_angle != "NINGUNO": angle_instructions = f""" MAIN ANGLE: {selected_angle} SPECIFIC ANGLE INSTRUCTIONS: {angles[selected_angle]["instruction"]} IMPORTANT: The angle {selected_angle} must be applied as a "style layer" over the formula structure: 1. Keep the base structure of the formula intact 2. Apply the tone and style of the {selected_angle} angle 3. Ensure each element of the formula reflects the angle 4. The angle affects "how" it's said, not "what" is said SUCCESSFUL EXAMPLES OF THE {selected_angle} ANGLE: """ for example in angles[selected_angle]["examples"]: angle_instructions += f"- {example}\n" # Añadir las instrucciones del ángulo al prompt principal email_instruction += angle_instructions # Dentro de la función, actualizar el prompt para incluir emoción y acción deseada email_instruction += ( f"\nYour task is to create 5 persuasive emails for {target_audience} " f"that evoke {emotion} and convince them to {desired_action} about {product}. " ) # Usar la variable angle_instructions para determinar si hay un ángulo seleccionado if angle_instructions: email_instruction += f"IMPORTANT: Each email MUST follow the {selected_angle} angle clearly and consistently.\n\n" email_instruction += ( f"Avoid obvious mentions of {product} and focus on generating genuine interest" ) if angle_instructions: email_instruction += f" using the selected angle" email_instruction += ".\n\n" # Agregar ejemplos de la fórmula examples_to_use = selected_formula['examples'][:min(2, len(selected_formula['examples']))] # Reduced to only 2 examples email_instruction += "FORMULA EXAMPLES TO STUDY (ONLY FOR STRUCTURE, NOT CONTENT):\n" for i, example in enumerate(examples_to_use, 1): email_instruction += f"{i}. {example}\n" # Añadir advertencia crítica con emoji para llamar la atención email_instruction += "\n⚠️ WARNING: DO NOT COPY THESE EXAMPLES. Create completely original content with different stories, scenarios and language. The examples are ONLY for understanding the structure.\n" # Añadir instrucciones específicas sobre la temperatura creativa email_instruction += f"\nCREATIVITY LEVEL: {temperature}. Higher values mean more creative and original content.\n\n" email_instruction += f"FORMULA TO FOLLOW:\n{selected_formula['description']}\n\n" # Consolidar las instrucciones finales en un solo bloque final_instructions = [ "Follow the logical structure but not the exact wording", "Be creative and original with your content", "Maintain the sequence flow between emails" ] # Añadir instrucciones específicas para el ángulo si es necesario if selected_angle != "NINGUNO": final_instructions.extend([ "Apply the angle as a 'style layer'", "Maintain coherence between formula and angle", "Ensure each email reflects both elements" ]) email_instruction += "\nFINAL REMINDER:\n" for i, instruction in enumerate(final_instructions, 1): email_instruction += f"{i}. {instruction}\n" # Simplify the final instruction to clearly specify 5 emails email_instruction += f"\nGENERATE NOW:\nCreate 5 CREATIVE emails that follow the logical structure but with original content.\n" # Modificar la forma de enviar el mensaje según si hay imagen o no message_parts = [email_instruction] # Add the image to the message parts if it exists if is_image and image_parts: message_parts.append(image_parts) instruction_text = "Generate the emails in Spanish following only the STRUCTURE of the examples, but with completely original content, drawing inspiration from the provided image." else: instruction_text = "Generate the emails in Spanish following only the STRUCTURE of the examples, but with completely original content and stories." # Simplificar las instrucciones finales para evitar redundancia instruction_text += " Do not include explanations, only the emails. IMPORTANT: Do not include greetings like 'Hello [Name]' and make sure that the postscripts (P.D.) are smaller and more discrete than the main body of the email, using a lighter format." # Create the chat session with the message parts chat_session = model.start_chat( history=[ { "role": "user", "parts": message_parts, }, ] ) # Enviar el mensaje con las instrucciones response = chat_session.send_message(instruction_text) return response.text # Define the clean_response_text function before it's used def clean_response_text(text): """Remove extra spaces and normalize whitespace in the response text""" import re # Replace multiple newlines with just two text = re.sub(r'\n{3,}', '\n\n', text) # Remove leading/trailing whitespace text = text.strip() return text # Configurar la interfaz de usuario con Streamlit st.set_page_config( page_title="Email Composer", layout="wide", menu_items={}, # Empty dict removes the three-dot menu initial_sidebar_state="expanded" ) # Add custom CSS to reduce margins st.markdown(""" """, unsafe_allow_html=True) # Leer el contenido del archivo manual.md with open("manual.md", "r", encoding="utf-8") as file: manual_content = file.read() # Mostrar el contenido del manual en el sidebar st.sidebar.markdown(manual_content) # Load CSS from file with open("styles/main.css", "r") as f: css = f.read() # Apply the CSS st.markdown(f"", unsafe_allow_html=True) # Centrar el título y el subtítulo st.markdown("
{generated_emails}