Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546from dotenv import load_dotenvimport streamlit as stimport osimport google.generativeai as genaiimport randomimport datetimefrom streamlit import session_state as statefrom formulas.webinar_formulas import webinar_formulasfrom formulas.webinar_name_formulas import webinar_name_formulasfrom formulas.angles_webinar_names import angles_webinar_names# Cargar las variables de entornoload_dotenv()# Configurar la API de Googlegenai.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ítulosif 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 guionescol.download_button(label=download_label,data=generated_content,file_name=file_name,mime="text/plain",key=f"download_top_{content_type}")# Mostrar el contenido generadocol.subheader(subheader_text)col.markdown(generated_content)# Mostrar botón de descarga inferiorcol.download_button(label=download_label,data=generated_content,file_name=file_name,mime="text/plain",key=f"download_bottom_{content_type}")else: # nombressubheader_text = "Tus nombres de webinar:"file_name = f"nombres_webinar_{timestamp}.txt"download_label = "DESCARGAR NOMBRES DE WEBINAR ▶▶"# Contar el número de nombres generadosnum_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_buttonimport base64# Codificar el contenido para descargab64 = base64.b64encode(generated_content.encode()).decode()# Crear botón de descarga superior con clase específicatop_button_html = f"""<div class="custom-download-button names-download-button top-button"><a href="data:text/plain;base64,{b64}" download="{file_name}">{download_label}</a></div>"""# Crear botón de descarga inferior con clase específicabottom_button_html = f"""<div class="custom-download-button names-download-button bottom-button"><a href="data:text/plain;base64,{b64}" download="{file_name}">{download_label}</a></div>"""# Mostrar botón de descarga superiorcol.markdown(top_button_html, unsafe_allow_html=True)# Mostrar el contenido generadocol.subheader(subheader_text)col.markdown(generated_content)# Mostrar botón de descarga inferiorcol.markdown(bottom_button_html, unsafe_allow_html=True)# Implementar la función generate_and_display para reemplazar código duplicadodef 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 adecuadosgenerated_content = generator_func(audience=audience,topic=product,temperature=temperature,selected_formula=selected_formula,**kwargs)# Mostrar el contenido generado usando la función auxiliardisplay_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 modelodef 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 duplicationdef 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_scriptdef generate_webinar_names(audience, topic, temperature, selected_formula, number_of_names=5, selected_angle=None, **kwargs):# Incluir las instrucciones del sistema en el prompt principalsystem_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 SPANISHFORMAT 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 sistemawebinar_names_instruction = f"{system_prompt}\n\n"# Añadir instrucciones de ángulo solo si no es "NINGUNO" y se proporcionó un ánguloif 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 intact2. Apply the tone and style of the {selected_angle} angle3. Ensure that each element of the formula reflects the angle4. The angle affects "how" it is said, not "what" is saidSUCCESSFUL 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 tareawebinar_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 analogies2. Create intriguing contrasts or paradoxes3. Challenge conventional wisdom with provocative statements4. Use power words that evoke emotion5. Create curiosity with incomplete loops or questions6. Use specific numbers or data points that seem unusualGENERATE 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 functionreturn generate_content(webinar_names_instruction, temperature)# Update the create_input_section function to include the product/offer fielddef 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 providedoffer = Noneif offer_key:offer = col.text_input("¿Cuál es tu producto u oferta?", placeholder="Ejemplo: Curso de marketing de afiliados", key=offer_key)# Formula selectionformula_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, offerelse:return audience, product, selected_formula_key# Update the generate_webinar_script function to include the offer parameterdef generate_webinar_script(audience, topic, temperature, selected_formula, offer=None, creative_idea=None):model = initialize_model(temperature)# Include offer in the system prompt if providedoffer_text = f" and selling {offer}" if offer else ""# Incluir las instrucciones del sistema en el prompt principalsystem_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 elements2. 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 audience3. 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 relevant4. 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 narrative5. 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 highFORMAT 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 principles2. 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 throughout5. Follow the exact structure provided in the framework"""# Añadir instrucciones para la idea creativa si existeif 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 webinar2. Use it as a metaphor or analogy throughout the presentation3. Develop different aspects of this concept in each section4. Make sure the concept naturally connects to the product benefits5. The concept should make the webinar more memorable and engaging"""# Update the task instructions to include the offeroffer_instruction = f" and selling {offer}" if offer else ""# Instrucciones específicas para la tareawebinar_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 webinarwebinar_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 exitososwebinar_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ñolwebinar_script_instruction += f"""SPECIFIC INSTRUCTIONS:1. Create a complete script that follows exactly the provided structure2. Include persuasive elements and clear calls to action3. 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 points6. Use a conversational but professional tone7. Make sure each section fulfills its specific purpose in the framework8. 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 content11. ALL section titles, headers, and content MUST be in Spanish12. Ensure ALL examples, stories, and calls to action are in SpanishGENERATE NOW:Create a complete webinar script following faithfully the structure of the selected framework, entirely in Spanish."""# Enviar el mensaje al modelochat_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 descriptivedef load_css():css_path = "styles/styles.css"if os.path.exists(css_path):try:with open(css_path, "r") as f:st.markdown(f"<style>{f.read()}</style>", 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 menust.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.mdwith open("manual.md", "r", encoding="utf-8") as file:manual_content = file.read()# Mostrar el contenido del manual en el sidebarst.sidebar.markdown(manual_content)# Agregar título y subtítulo usando HTMLst.markdown("<h1 style='text-align: center;'>Perfect Webinar Framework</h1>", unsafe_allow_html=True)st.markdown("<h3 style='text-align: center;'>Crea guiones y títulos de webinars persuasivos que convierten</h3>", unsafe_allow_html=True)# Crear pestañas para la interfaztab1, tab2 = st.tabs(["Guiones de Webinar", "Nombres de Webinar"])# Primera pestaña - Generador de Guiones de Webinarwith tab1:tab1.subheader("Script Webinar")# Crear columnas para la interfazcol1, col2 = tab1.columns([1, 2])# Columna de entrada usando la función reutilizablewith col1:# Inputs básicos (fuera del acordeón)webinar_script_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key="webinar_script_audience")webinar_script_product = st.text_input("¿Sobre qué tema es tu webinar?", placeholder="Ejemplo: Marketing de afiliados", key="webinar_script_product")webinar_script_offer = st.text_input("¿Cuál es tu producto u oferta?", placeholder="Ejemplo: Curso de marketing de afiliados", key="webinar_script_offer")# Botón de generación (movido aquí, justo después de los campos principales)submit_webinar_script = st.button("GENERAR GUIÓN DE WEBINAR ▶▶", key="generate_webinar_script")# Opciones avanzadas en el acordeónwith st.expander("Personaliza tu guión de webinar"):# Selector de fórmula (ahora dentro del acordeón)selected_webinar_formula_key = st.selectbox("Selecciona un framework de webinar",options=list(webinar_formulas.keys()),key="webinar_formula")# Nuevo campo para la idea creativacreative_idea = st.text_area("Idea creativa (opcional)",placeholder="Introduce una idea o concepto creativo que quieras usar como tema central en tu webinar",help="Este concepto será el tema unificador a lo largo de tu webinar, haciéndolo más memorable y atractivo",key="webinar_creative_idea")# Slider de creatividad (ya existente)webinar_script_temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1, key="webinar_script_temp")selected_webinar_formula = webinar_formulas[selected_webinar_formula_key]# Usar la función generate_and_display para generar y mostrar el guiónif submit_webinar_script:generate_and_display(col=col2,generator_func=generate_webinar_script,audience=webinar_script_audience,product=webinar_script_product,temperature=webinar_script_temperature,selected_formula=selected_webinar_formula,content_type="script",offer=webinar_script_offer if webinar_script_offer.strip() else None,creative_idea=creative_idea if creative_idea.strip() else None)# Segunda pestaña - Generador de Nombres de Webinarwith tab2:tab2.subheader("Nombres de Webinar")# Crear columnas para la interfazcol1, col2 = tab2.columns([1, 2])# Columna de entradawith col1:# Inputs básicoswebinar_names_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key="webinar_names_audience")webinar_names_product = st.text_input("¿Sobre qué tema es tu webinar?", placeholder="Ejemplo: Marketing de afiliados", key="webinar_names_product")# Botón de generación (movido aquí, justo después de los campos principales)submit_webinar_names = st.button("GENERAR NOMBRES DE WEBINAR ▶▶", key="generate_webinar_names")# Opciones avanzadas en el acordeónwith st.expander("Personaliza tus nombres de webinar"):# Selector de fórmulaselected_name_formula_key = st.selectbox("Selecciona una fórmula para tus nombres",options=list(webinar_name_formulas.keys()),key="webinar_name_formula")# Selector de ánguloselected_angle = st.selectbox("Selecciona un ángulo (opcional)",options=["NINGUNO"] + list(angles_webinar_names.keys()),key="webinar_name_angle")# Número de nombres a generarnumber_of_names = st.slider("Número de nombres a generar", min_value=3, max_value=15, value=5, step=1, key="number_of_names")# Slider de creatividadwebinar_names_temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1, key="webinar_names_temp")selected_name_formula = webinar_name_formulas[selected_name_formula_key]# Usar la función generate_and_display para generar y mostrar los nombresif submit_webinar_names:generate_and_display(col=col2,generator_func=generate_webinar_names,audience=webinar_names_audience,product=webinar_names_product,temperature=webinar_names_temperature,selected_formula=selected_name_formula,content_type="names",number_of_names=number_of_names,selected_angle=selected_angle if selected_angle != "NINGUNO" else None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551from dotenv import load_dotenvimport streamlit as stimport osimport google.generativeai as genaiimport randomimport datetimefrom streamlit import session_state as statefrom formulas.webinar_formulas import webinar_formulasfrom formulas.webinar_name_formulas import webinar_name_formulasfrom formulas.angles_webinar_names import angles_webinar_names# Cargar las variables de entornoload_dotenv()# Configurar la API de Googlegenai.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:# Modificar la función display_generated_content para usar session_statedef display_generated_content(col, generated_content, content_type):timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")# Guardar el contenido generado en el estado de la sesiónif content_type == "script":state.last_generated_script = generated_contentdownload_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 guionescol.download_button(label=download_label,data=generated_content,file_name=file_name,mime="text/plain",key=f"download_top_{content_type}_{timestamp}", # Añadir timestamp para hacer la key únicaon_click=None # Asegurarse de que no hay callback que recargue la página)# Mostrar el contenido generadocol.subheader(subheader_text)col.markdown(generated_content)# Mostrar botón de descarga inferiorcol.download_button(label=download_label,data=generated_content,file_name=file_name,mime="text/plain",key=f"download_bottom_{content_type}_{timestamp}", # Añadir timestamp para hacer la key únicaon_click=None # Asegurarse de que no hay callback que recargue la página)else: # nombresstate.last_generated_names = generated_contentsubheader_text = "Tus nombres de webinar:"file_name = f"nombres_webinar_{timestamp}.txt"download_label = "DESCARGAR NOMBRES DE WEBINAR ▶▶"# Contar el número de nombres generadosnum_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_buttonimport base64# Codificar el contenido para descargab64 = base64.b64encode(generated_content.encode()).decode()# Crear botón de descarga superior con clase específica y timestamp únicotop_button_html = f"""<div class="custom-download-button names-download-button top-button"><a href="data:text/plain;base64,{b64}" download="{file_name}" id="download_top_{timestamp}">{download_label}</a></div>"""# Crear botón de descarga inferior con clase específica y timestamp únicobottom_button_html = f"""<div class="custom-download-button names-download-button bottom-button"><a href="data:text/plain;base64,{b64}" download="{file_name}" id="download_bottom_{timestamp}">{download_label}</a></div>"""# Mostrar botón de descarga superiorcol.markdown(top_button_html, unsafe_allow_html=True)# Mostrar el contenido generadocol.subheader(subheader_text)col.markdown(generated_content)# Mostrar botón de descarga inferiorcol.markdown(bottom_button_html, unsafe_allow_html=True)# Implementar la función generate_and_display para reemplazar código duplicadodef 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 adecuadosgenerated_content = generator_func(audience=audience,topic=product,temperature=temperature,selected_formula=selected_formula,**kwargs)# Mostrar el contenido generado usando la función auxiliardisplay_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 modelodef 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 duplicationdef 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_scriptdef generate_webinar_names(audience, topic, temperature, selected_formula, number_of_names=5, selected_angle=None, **kwargs):# Incluir las instrucciones del sistema en el prompt principalsystem_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 SPANISHFORMAT 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 sistemawebinar_names_instruction = f"{system_prompt}\n\n"# Añadir instrucciones de ángulo solo si no es "NINGUNO" y se proporcionó un ánguloif 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 intact2. Apply the tone and style of the {selected_angle} angle3. Ensure that each element of the formula reflects the angle4. The angle affects "how" it is said, not "what" is saidSUCCESSFUL 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 tareawebinar_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 analogies2. Create intriguing contrasts or paradoxes3. Challenge conventional wisdom with provocative statements4. Use power words that evoke emotion5. Create curiosity with incomplete loops or questions6. Use specific numbers or data points that seem unusualGENERATE 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 functionreturn generate_content(webinar_names_instruction, temperature)# Update the create_input_section function to include the product/offer fielddef 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 providedoffer = Noneif offer_key:offer = col.text_input("¿Cuál es tu producto u oferta?", placeholder="Ejemplo: Curso de marketing de afiliados", key=offer_key)# Formula selectionformula_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, offerelse:return audience, product, selected_formula_key# Update the generate_webinar_script function to include the offer parameterdef generate_webinar_script(audience, topic, temperature, selected_formula, offer=None, creative_idea=None):model = initialize_model(temperature)# Include offer in the system prompt if providedoffer_text = f" and selling {offer}" if offer else ""# Incluir las instrucciones del sistema en el prompt principalsystem_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 elements2. 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 audience3. 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 relevant4. 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 narrative5. 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 highFORMAT 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 principles2. 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 throughout5. Follow the exact structure provided in the framework"""# Añadir instrucciones para la idea creativa si existeif 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 webinar2. Use it as a metaphor or analogy throughout the presentation3. Develop different aspects of this concept in each section4. Make sure the concept naturally connects to the product benefits5. The concept should make the webinar more memorable and engaging"""# Update the task instructions to include the offeroffer_instruction = f" and selling {offer}" if offer else ""# Instrucciones específicas para la tareawebinar_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 webinarwebinar_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 exitososwebinar_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ñolwebinar_script_instruction += f"""SPECIFIC INSTRUCTIONS:1. Create a complete script that follows exactly the provided structure2. Include persuasive elements and clear calls to action3. 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 points6. Use a conversational but professional tone7. Make sure each section fulfills its specific purpose in the framework8. 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 content11. ALL section titles, headers, and content MUST be in Spanish12. Ensure ALL examples, stories, and calls to action are in SpanishGENERATE NOW:Create a complete webinar script following faithfully the structure of the selected framework, entirely in Spanish."""# Enviar el mensaje al modelochat_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 descriptivedef load_css():css_path = "styles/styles.css"if os.path.exists(css_path):try:with open(css_path, "r") as f:st.markdown(f"<style>{f.read()}</style>", 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 menust.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.mdwith open("manual.md", "r", encoding="utf-8") as file:manual_content = file.read()# Mostrar el contenido del manual en el sidebarst.sidebar.markdown(manual_content)# Agregar título y subtítulo usando HTMLst.markdown("<h1 style='text-align: center;'>Perfect Webinar Framework</h1>", unsafe_allow_html=True)st.markdown("<h3 style='text-align: center;'>Crea guiones y títulos de webinars persuasivos que convierten</h3>", unsafe_allow_html=True)# Crear pestañas para la interfaztab1, tab2 = st.tabs(["Guiones de Webinar", "Nombres de Webinar"])# Primera pestaña - Generador de Guiones de Webinarwith tab1:tab1.subheader("Script Webinar")# Crear columnas para la interfazcol1, col2 = tab1.columns([1, 2])# Columna de entrada usando la función reutilizablewith col1:# Inputs básicos (fuera del acordeón)webinar_script_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key="webinar_script_audience")webinar_script_product = st.text_input("¿Sobre qué tema es tu webinar?", placeholder="Ejemplo: Marketing de afiliados", key="webinar_script_product")webinar_script_offer = st.text_input("¿Cuál es tu producto u oferta?", placeholder="Ejemplo: Curso de marketing de afiliados", key="webinar_script_offer")# Botón de generación (movido aquí, justo después de los campos principales)submit_webinar_script = st.button("GENERAR GUIÓN DE WEBINAR ▶▶", key="generate_webinar_script")# Opciones avanzadas en el acordeónwith st.expander("Personaliza tu guión de webinar"):# Selector de fórmula (ahora dentro del acordeón)selected_webinar_formula_key = st.selectbox("Selecciona un framework de webinar",options=list(webinar_formulas.keys()),key="webinar_formula")# Nuevo campo para la idea creativacreative_idea = st.text_area("Idea creativa (opcional)",placeholder="Introduce una idea o concepto creativo que quieras usar como tema central en tu webinar",help="Este concepto será el tema unificador a lo largo de tu webinar, haciéndolo más memorable y atractivo",key="webinar_creative_idea")# Slider de creatividad (ya existente)webinar_script_temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1, key="webinar_script_temp")selected_webinar_formula = webinar_formulas[selected_webinar_formula_key]# Usar la función generate_and_display para generar y mostrar el guiónif submit_webinar_script:generate_and_display(col=col2,generator_func=generate_webinar_script,audience=webinar_script_audience,product=webinar_script_product,temperature=webinar_script_temperature,selected_formula=selected_webinar_formula,content_type="script",offer=webinar_script_offer if webinar_script_offer.strip() else None,creative_idea=creative_idea if creative_idea.strip() else None)# Segunda pestaña - Generador de Nombres de Webinarwith tab2:tab2.subheader("Nombres de Webinar")# Crear columnas para la interfazcol1, col2 = tab2.columns([1, 2])# Columna de entradawith col1:# Inputs básicoswebinar_names_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key="webinar_names_audience")webinar_names_product = st.text_input("¿Sobre qué tema es tu webinar?", placeholder="Ejemplo: Marketing de afiliados", key="webinar_names_product")# Botón de generación (movido aquí, justo después de los campos principales)submit_webinar_names = st.button("GENERAR NOMBRES DE WEBINAR ▶▶", key="generate_webinar_names")# Opciones avanzadas en el acordeónwith st.expander("Personaliza tus nombres de webinar"):# Selector de fórmulaselected_name_formula_key = st.selectbox("Selecciona una fórmula para tus nombres",options=list(webinar_name_formulas.keys()),key="webinar_name_formula")# Selector de ánguloselected_angle = st.selectbox("Selecciona un ángulo (opcional)",options=["NINGUNO"] + list(angles_webinar_names.keys()),key="webinar_name_angle")# Número de nombres a generarnumber_of_names = st.slider("Número de nombres a generar", min_value=3, max_value=15, value=5, step=1, key="number_of_names")# Slider de creatividadwebinar_names_temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1, key="webinar_names_temp")selected_name_formula = webinar_name_formulas[selected_name_formula_key]# Usar la función generate_and_display para generar y mostrar los nombresif submit_webinar_names:generate_and_display(col=col2,generator_func=generate_webinar_names,audience=webinar_names_audience,product=webinar_names_product,temperature=webinar_names_temperature,selected_formula=selected_name_formula,content_type="names",number_of_names=number_of_names,selected_angle=selected_angle if selected_angle != "NINGUNO" else None)
app.py+550-545