from dotenv import load_dotenv import streamlit as st import os import google.generativeai as genai import random import datetime from streamlit import session_state as state from formulas.webinar_formulas import webinar_formulas from formulas.webinar_name_formulas import webinar_name_formulas from formulas.angles_webinar_names import angles_webinar_names # Cargar las variables de entorno load_dotenv() # Configurar la API de Google genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Función auxiliar para mostrar el contenido generado y los botones de descarga # In the display_generated_content function, modify the names section: def display_generated_content(col, generated_content, content_type): timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # Determinar el tipo de contenido para personalizar los botones y títulos if content_type == "script": download_label = "DESCARGAR GUIÓN DE WEBINAR ▶▶" file_name = f"guion_webinar_{timestamp}.txt" subheader_text = "Tu guión de webinar:" # Mostrar botón de descarga superior para guiones col.download_button( label=download_label, data=generated_content, file_name=file_name, mime="text/plain", key=f"download_top_{content_type}" ) # Mostrar el contenido generado col.subheader(subheader_text) col.markdown(generated_content) # Mostrar botón de descarga inferior col.download_button( label=download_label, data=generated_content, file_name=file_name, mime="text/plain", key=f"download_bottom_{content_type}" ) else: # nombres subheader_text = "Tus nombres de webinar:" file_name = f"nombres_webinar_{timestamp}.txt" download_label = "DESCARGAR NOMBRES DE WEBINAR ▶▶" # Contar el número de nombres generados num_names = len([line for line in generated_content.split('\n') if line.strip().startswith(('1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.', '11.', '12.', '13.', '14.', '15.'))]) # Para los nombres, usar HTML personalizado en lugar de st.download_button import base64 # Codificar el contenido para descarga b64 = base64.b64encode(generated_content.encode()).decode() # Crear botón de descarga superior con clase específica top_button_html = f"""
""" # Crear botón de descarga inferior con clase específica bottom_button_html = f""" """ # Mostrar botón de descarga superior col.markdown(top_button_html, unsafe_allow_html=True) # Mostrar el contenido generado col.subheader(subheader_text) col.markdown(generated_content) # Mostrar botón de descarga inferior col.markdown(bottom_button_html, unsafe_allow_html=True) # Implementar la función generate_and_display para reemplazar código duplicado def generate_and_display(col, generator_func, audience, product, temperature, selected_formula, content_type, **kwargs): if validate_inputs(audience, product): try: with col: with st.spinner(f"Generando {'guión' if content_type == 'script' else 'nombres'} de webinar...", show_time=True): # Llamar a la función generadora con los parámetros adecuados generated_content = generator_func( audience=audience, topic=product, temperature=temperature, selected_formula=selected_formula, **kwargs ) # Mostrar el contenido generado usando la función auxiliar display_generated_content(col, generated_content, content_type) except ValueError as e: col.error(f"Error: {str(e)}") else: col.error("Por favor, proporciona el público objetivo y el tema del webinar.") # Función para crear la configuración del modelo (evita duplicación) def create_model_config(temperature): return { "temperature": temperature, "top_p": 0.65, "top_k": 360, "max_output_tokens": 8196, } # Función para inicializar el modelo def initialize_model(temperature): config = create_model_config(temperature) return genai.GenerativeModel( model_name="gemini-2.0-flash", generation_config=config, ) # Refactored model interaction function to reduce duplication def generate_content(prompt_instructions, temperature): model = initialize_model(temperature) chat_session = model.start_chat( history=[ { "role": "user", "parts": [prompt_instructions], }, ] ) response = chat_session.send_message("Generate the content following exactly the provided instructions. All content must be in Spanish.") return response.text # Función para generar nombres de webinars # Refactorizar la función generate_webinar_names para que acepte los mismos parámetros que generate_webinar_script def generate_webinar_names(audience, topic, temperature, selected_formula, number_of_names=5, selected_angle=None, **kwargs): # Incluir las instrucciones del sistema en el prompt principal system_prompt = """You are a world-class copywriter, with expertise in crafting compelling and disruptive webinar titles that immediately capture the audience's attention and drive registrations. FORMAT RULES: - Each webinar name must start with number and period - One webinar name per line - No explanations or categories - Add a line break between each name - Avoid unnecessary : symbols - Each webinar name must be a complete, intriguing and creative title - WRITE ALL WEBINAR NAMES IN SPANISH FORMAT EXAMPLE: 1. Nombre del Webinar 1. 2. Nombre del Webinar 2. 3. Nombre del Webinar 3. 4. Nombre del Webinar 4. 5. Nombre del Webinar 5. IMPORTANT: - Each webinar name must be unique, memorable and disruptive - Create curiosity and intrigue with unexpected combinations - Use creative language that stands out from typical webinar titles - Incorporate pattern interrupts that make people stop scrolling - Adapt speaking language from the audience - Focus on transformative benefits with creative angles - Follow the selected formula structure but add creative twists - WRITE ALL WEBINAR NAMES IN SPANISH""" # Iniciar el prompt con las instrucciones del sistema webinar_names_instruction = f"{system_prompt}\n\n" # Añadir instrucciones de ángulo solo si no es "NINGUNO" y se proporcionó un ángulo if selected_angle and selected_angle != "NINGUNO": webinar_names_instruction += f""" MAIN ANGLE: {selected_angle} SPECIFIC ANGLE INSTRUCTIONS: {angles_webinar_names[selected_angle]["instruction"]} IMPORTANT: The {selected_angle} angle should 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 that each element of the formula reflects the angle 4. The angle affects "how" it is said, not "what" is said SUCCESSFUL EXAMPLES OF THE {selected_angle} ANGLE: """ for example in angles_webinar_names[selected_angle]["examples"]: webinar_names_instruction += f"- {example}\n" # Instrucciones específicas para la tarea webinar_names_instruction += ( f"\nYour task is to create {number_of_names} irresistible, creative and disruptive webinar names for {audience} " f"that instantly capture attention and generate registrations for a webinar about {topic}. " f"Focus on awakening genuine curiosity, creating intrigue, and communicating the value they will get by registering." f"\n\n" f"IMPORTANT: Use these examples of the selected formula as inspiration, but make your titles more creative and disruptive. " f"Each example represents a base structure to follow, but add unexpected elements and creative twists" f":\n\n" ) # Agregar ejemplos aleatorios de la fórmula (keeping examples in Spanish) random_examples = random.sample(selected_formula['examples'], min(5, len(selected_formula['examples']))) webinar_names_instruction += "EXAMPLES OF THE FORMULA TO FOLLOW (BUT MAKE YOURS MORE CREATIVE):\n" for i, example in enumerate(random_examples, 1): webinar_names_instruction += f"{i}. {example}\n" # Instrucciones específicas (translated to English) webinar_names_instruction += "\nSPECIFIC INSTRUCTIONS:\n" webinar_names_instruction += "1. Use the same basic structure as the examples but add creative twists\n" webinar_names_instruction += "2. Create curiosity gaps that make people want to learn more\n" webinar_names_instruction += "3. Use unexpected word combinations that surprise the reader\n" webinar_names_instruction += "4. Incorporate pattern interrupts that make people stop and think\n" webinar_names_instruction += f"5. Adapt the content for {audience} while making titles more memorable and disruptive\n\n" webinar_names_instruction += f"FORMULA TO FOLLOW (AS A BASE):\n{selected_formula['description']}\n\n" webinar_names_instruction += f""" CREATIVE TECHNIQUES TO APPLY: 1. Use unexpected metaphors or analogies 2. Create intriguing contrasts or paradoxes 3. Challenge conventional wisdom with provocative statements 4. Use power words that evoke emotion 5. Create curiosity with incomplete loops or questions 6. Use specific numbers or data points that seem unusual GENERATE NOW: Create {number_of_names} creative, disruptive webinar names that use the formula structure as a base but add unexpected creative elements to make them stand out. """ # Enviar el mensaje al modelo # Use the common generate_content function return generate_content(webinar_names_instruction, temperature) # Update the create_input_section function to include the product/offer field def create_input_section(col, audience_key, product_key, formulas, formula_key, offer_key=None): audience = col.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key=audience_key) product = col.text_input("¿Sobre qué tema es tu webinar?", placeholder="Ejemplo: Marketing de afiliados", key=product_key) # Add the new product/offer field if a key is provided offer = None if offer_key: offer = col.text_input("¿Cuál es tu producto u oferta?", placeholder="Ejemplo: Curso de marketing de afiliados", key=offer_key) # Formula selection formula_keys = list(formulas.keys()) selected_formula_key = col.selectbox( "Selecciona un framework de webinar", options=formula_keys, key=formula_key ) if offer_key: return audience, product, selected_formula_key, offer else: return audience, product, selected_formula_key # Update the generate_webinar_script function to include the offer parameter def generate_webinar_script(audience, topic, temperature, selected_formula, offer=None, creative_idea=None): model = initialize_model(temperature) # Include offer in the system prompt if provided offer_text = f" and selling {offer}" if offer else "" # Incluir las instrucciones del sistema en el prompt principal system_prompt = f"""You are a collaborative team of world-class experts working together to create an exceptional webinar script that converts audience into customers. THE EXPERT TEAM: 1. MASTER WEBINAR STRATEGIST: - Expert in webinar frameworks and conversion strategies - Trained in the Perfect Webinar methodology by Russell Brunson - Ensures the script follows the selected framework structure precisely - Focuses on strategic placement of key conversion elements 2. ELITE DIRECT RESPONSE COPYWRITER: - Trained by Gary Halbert, Gary Bencivenga, and David Ogilvy - Creates compelling hooks, stories, and persuasive elements - Crafts irresistible calls to action that drives conversions - Ensures the language resonates with the target audience 3. AUDIENCE PSYCHOLOGY SPECIALIST: - Expert in understanding audience motivations and objections - Creates content that builds genuine connection and trust - Identifies and addresses hidden fears and desires - Ensures the content feels personal and relevant 4. STORYTELLING MASTER: - Creates compelling narratives that illustrate key points - Develops relatable examples and case studies - Ensures stories support the transformation being offered - Makes complex concepts accessible through narrative 5. WEBINAR ENGAGEMENT EXPERT: - Specializes in maintaining audience attention throughout - Creates interactive elements and engagement hooks - Develops compelling transitions between sections - Ensures the webinar flows naturally and keeps interest high FORMAT REQUIREMENTS: - Create a complete webinar script with clear sections and subsections - Include specific talking points for each section - Write in a conversational, engaging tone - Include persuasive elements and calls to action - Follow the selected webinar framework structure exactly - WRITE THE ENTIRE SCRIPT IN SPANISH - Start directly with the webinar content without introductory text - DO NOT include any explanatory text at the beginning like "Here's the webinar script..." or "I've created a webinar script..." COLLABORATIVE PROCESS: As a team of experts, you will: 1. Analyze the framework '{selected_formula['description']}' to understand its core principles 2. Identify how to best adapt this framework for {audience} learning about {topic}{offer_text} 3. Create persuasive language that resonates with {audience} 4. Ensure the script maintains engagement throughout 5. Follow the exact structure provided in the framework""" # Añadir instrucciones para la idea creativa si existe if creative_idea: system_prompt += f""" CREATIVE CONCEPT: Use the following creative concept as the central theme for the webinar: "{creative_idea}" CREATIVE CONCEPT INSTRUCTIONS: 1. This concept should be the unifying theme across the entire webinar 2. Use it as a metaphor or analogy throughout the presentation 3. Develop different aspects of this concept in each section 4. Make sure the concept naturally connects to the product benefits 5. The concept should make the webinar more memorable and engaging """ # Update the task instructions to include the offer offer_instruction = f" and selling {offer}" if offer else "" # Instrucciones específicas para la tarea webinar_script_instruction = ( f"{system_prompt}\n\n" f"\nYour task is to create a complete webinar script IN SPANISH for {audience} " f"about {topic}{offer_instruction} that is persuasive and converts the audience into customers. " f"The script must follow exactly the structure of the framework '{selected_formula['description']}' " f"and must include all the necessary elements for a successful webinar." f"\n\n" ) # Estructura del webinar webinar_script_instruction += "WEBINAR STRUCTURE TO FOLLOW:\n" for i, step in enumerate(selected_formula['structure'], 1): webinar_script_instruction += f"{i}. {step}\n" # Ejemplos de webinars exitosos webinar_script_instruction += "\n\nEXAMPLES OF SUCCESSFUL WEBINARS WITH THIS STRUCTURE:\n" for i, example in enumerate(selected_formula['examples'], 1): webinar_script_instruction += f"{i}. {example}\n" # Instrucciones específicas - Reforzar el español webinar_script_instruction += f""" SPECIFIC INSTRUCTIONS: 1. Create a complete script that follows exactly the provided structure 2. Include persuasive elements and clear calls to action 3. Adapt the language and examples specifically for {audience} 4. Focus on the transformative benefits of {topic} 5. Include relevant stories and examples that reinforce your points 6. Use a conversational but professional tone 7. Make sure each section fulfills its specific purpose in the framework 8. IMPORTANT: Write the ENTIRE script in Spanish (neutral Latin American Spanish) 9. DO NOT include any introductory text like "Here's the webinar script..." or "I've created a webinar script..." 10. Start directly with the webinar title and content 11. ALL section titles, headers, and content MUST be in Spanish 12. Ensure ALL examples, stories, and calls to action are in Spanish GENERATE NOW: Create a complete webinar script following faithfully the structure of the selected framework, entirely in Spanish. """ # Enviar el mensaje al modelo chat_session = model.start_chat( history=[ { "role": "user", "parts": [webinar_script_instruction], }, ] ) response = chat_session.send_message("Generate the webinar script IN NEUTRAL SPANISH following exactly the provided structure. All content must be in neutral Spanish (not Spain Spanish). Start directly with the webinar content without any introductory text.") return response.text # Función para validar entradas (evita duplicación) def validate_inputs(audience, product): has_audience = audience.strip() != "" has_product = product.strip() != "" return has_audience and has_product # Update the load_css function comment to be more descriptive def load_css(): css_path = "styles/styles.css" if os.path.exists(css_path): try: with open(css_path, "r") as f: st.markdown(f"", unsafe_allow_html=True) except Exception as e: st.warning(f"Error al cargar el archivo CSS: {str(e)}") else: st.warning(f"No se encontró el archivo CSS en {css_path}") # Modify the page config section to include the CSS loading and remove menu st.set_page_config( page_title="Perfect Webinar Framework", layout="wide", initial_sidebar_state="expanded", menu_items=None # This removes the three dots menu ) load_css() # This will load the styles from styles.css # 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) # Agregar título y subtítulo usando HTML st.markdown("