Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103111 unmodified lineimport streamlit as stimport osimport google.generativeai as genaifrom puv_formulas import puv_formulasfrom styles import apply_styles, format_creative_responsefrom options import tone_options, creative_approachesimport PyPDF2import docxfrom PIL import Imageimport datetime # Add this import for timestamp# Cargar variables de entornoload_dotenv()# Configurar API de Google Geminigenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))# Función para obtener la respuesta del modelo Geminidef get_gemini_response(product_service, target_audience, main_benefit, tone_of_voice, temperature, file_content="", image_parts=None, creative_approach=""):# Adjust prompt based on what's providedbusiness_info = f"Target Audience: {target_audience}\n"business_info += f"Product/Service: {product_service}\n"business_info += f"Main Benefit: {main_benefit}\n"if tone_of_voice:business_info += f"Brand Tone of Voice: {tone_of_voice}\n"# Add creative approach to business info if providedif creative_approach:# Get the description from the dictionaryfrom options import creative_approachesapproach_description = creative_approaches.get(creative_approach, "")business_info += f"\nCREATIVE APPROACH: {creative_approach}\n"business_info += f"Description: {approach_description}\n"business_info += f"IMPORTANT: Please follow this creative approach strictly when generating concepts.\n"# Add file content if availablereference_info = ""if file_content:reference_info = f"\nREFERENCE MATERIAL:\n{file_content}\n"model = genai.GenerativeModel('gemini-2.0-flash')full_prompt = f"""You are a Creative Concept expert. Analyze (internally only, do not output the analysis) the following information:BUSINESS INFORMATION:{business_info}{reference_info}A Creative Idea is a set of pieces created to sell a brand, product, or service, united by the same idea that is transmitted through a creative concept.First, analyze (but don't output) these points:1. TARGET AUDIENCE ANALYSIS:- What everyday concepts are they familiar with?- What TV shows, movies, or cultural references resonate with them?- What emotions and experiences are meaningful to them?- What mental images would be easy for them to recall?2. PRODUCT/SERVICE ANALYSIS:- What is the main benefit or promise?- What makes it unique or different?- What transformation does it offer?- What process or journey does the customer go through?Based on your internal analysis, create THREE different Creative Concepts in Spanish language.Each concept should be a DIRECT ANALOGY or METAPHOR that connects your product/service to something completely different but familiar.Examples of good creative concepts:- "Escribir copy es como cocinar tu plato favorito porque necesitas los ingredientes correctos para que todos quieran probarlo"- "Tu negocio es como un equipo de fútbol: necesita buenos jugadores (productos) y una estrategia clara para ganar clientes"- "Tu curso es como Netflix: ofrece contenido que engancha y soluciones que la gente realmente quiere ver"For each concept, include:CONCEPT: A clear statement of the main benefitCREATIVITY: A direct analogy or metaphor connecting your product to something completely different but familiarCRITICAL INSTRUCTIONS:- Each concept MUST use a direct "X es como Y porque Z" structure- Use SIMPLE, EVERYDAY language that anyone can understand- Avoid technical jargon, complex words, or business terminology- Write as if you're explaining to a friend in a casual conversation- Use everyday objects, activities, movies, TV shows or cultural references everyone knows- Make the connection SURPRISING and UNEXPECTED - connect things that normally wouldn't be connected- Challenge conventional thinking by finding parallels between your product and something completely different- Create analogies that make people say "I never thought of it that way!"- Focus on the main benefit- Create clear mental images- Be easy to remember- Use the brand's tone of voice if provided- Format with proper spacing between sectionsOutput EXACTLY in this format (no additional text) in Spanish language:CONCEPTO CREATIVO 1:Concepto:[Main message/benefit in simple, conversational language]Creatividad:[Direct analogy using everyday language: "X es como Y porque Z"]CONCEPTO CREATIVO 2:Concepto:[Main message/benefit]Creatividad:[Direct analogy: "X es como Y porque Z"]CONCEPTO CREATIVO 3:Concepto:[Main message/benefit]Creatividad:[Direct analogy: "X es como Y porque Z"]"""# Handle text-only or text+image requestsif image_parts:response = model.generate_content([full_prompt, image_parts], generation_config={"temperature": temperature})else:response = model.generate_content([full_prompt], generation_config={"temperature": temperature})return response.parts[0].text if response and response.parts else "Error generating content."# Configurar la aplicación Streamlitst.set_page_config(page_title="Generador de Ideas Creativas", page_icon="💡", layout="wide")# Aplicar estilosst.markdown(apply_styles(), unsafe_allow_html=True)# Título de la appst.markdown("<h1>Generador de Ideas Creativas</h1>", unsafe_allow_html=True)st.markdown("<h3>Crea conceptos creativos poderosos que conecten con tu audiencia y transmitan el valor de tu marca de manera memorable.</h3>", unsafe_allow_html=True)# Sidebar manualwith open("manual.md", "r", encoding="utf-8") as file:manual_content = file.read()st.sidebar.markdown(manual_content)# Crear dos columnascol1, col2 = st.columns([1, 1])# Columna izquierda para inputs# In the app.py file, update the main_benefit field label and create an accordion for tone optionswith col1:product_service = st.text_area("¿Cuál es tu producto o servicio?",placeholder="Ejemplo: Curso de copywriting con IA, Programa de coaching...")main_benefit = st.text_area("¿Cuál es tu Oferta Dorada/PUV?",placeholder="Ejemplo: Aprender copywriting a través de transformaciones reales de textos...")target_audience = st.text_area("¿Cuál es tu público objetivo?",placeholder="Ejemplo: Emprendedores que quieren mejorar sus textos comerciales...")# Generate button after main inputsgenerate_button = st.button("Generar Ideas Creativas")with st.expander("Opciones avanzadas"):# Replace nested expanders with a selectbox for tone selectionst.write("Tono de voz de la marca (opcional)")# Use selectbox for tone selectionselected_tone = st.selectbox("Selecciona un tono:",options=list(tone_options.keys()),index=0,key="tone_selectbox")# Display the description of the selected toneif selected_tone != "Ninguno":st.info(tone_options[selected_tone])# Store the selected tonest.session_state.selected_tone = selected_toneelse:# Clear any previously selected toneif "selected_tone" in st.session_state:del st.session_state.selected_tone# Use the stored tone or empty stringtone_of_voice = st.session_state.get("selected_tone", "")# Añadir cargador de archivosuploaded_file = st.file_uploader("📄 Archivo o imagen de referencia",type=['txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'])file_content = ""is_image = Falseimage_parts = Noneif uploaded_file is not None:file_type = uploaded_file.name.split('.')[-1].lower()# Manejar archivos de textoif file_type in ['txt', 'pdf', 'docx']:if file_type == 'txt':try:file_content = uploaded_file.read().decode('utf-8')except Exception as e:st.error(f"Error al leer el archivo TXT: {str(e)}")file_content = ""elif file_type == 'pdf':try:pdf_reader = PyPDF2.PdfReader(uploaded_file)file_content = ""for page in pdf_reader.pages:file_content += page.extract_text() + "\n"except Exception as e:st.error(f"Error al leer el archivo PDF: {str(e)}")file_content = ""elif file_type == 'docx':try:doc = docx.Document(uploaded_file)file_content = "\n".join([para.text for para in doc.paragraphs])except Exception as e:st.error(f"Error al leer el archivo DOCX: {str(e)}")file_content = ""# Manejar archivos de imagenelif file_type in ['jpg', 'jpeg', 'png']:try:image = Image.open(uploaded_file)image_bytes = uploaded_file.getvalue()image_parts = {"mime_type": uploaded_file.type,"data": image_bytes}is_image = Trueexcept Exception as e:st.error(f"Error al procesar la imagen: {str(e)}")is_image = False# Add creative approach selector (moved outside nested expander)selected_approach = st.selectbox("Enfoque creativo:",options=list(creative_approaches.keys()),index=0,key="approach_selectbox")# Display the description of the selected approachst.info(creative_approaches[selected_approach])# Store the selected approachst.session_state.selected_approach = selected_approach# Temperature slidertemperature = st.slider("Nivel de creatividad:",min_value=0.0,max_value=2.0,value=1.0,step=0.1,help="Valores más altos generan ideas más creativas pero menos predecibles.")with col2:if generate_button:# Store the response in session state so it persists across rerunswith st.spinner("Creando tus ideas creativas..."):st.session_state.creative_response = get_gemini_response(product_service,target_audience,main_benefit,tone_of_voice,temperature,file_content,image_parts,st.session_state.get("selected_approach", "")# Removed contrast_level parameter)# Display the response if it exists in session stateif 'creative_response' in st.session_state:st.write("### Conceptos Creativos")# Format the response with custom stylingformatted_response = format_creative_response(st.session_state.creative_response)# Use markdown with HTML to display the formatted responsest.markdown(formatted_response, unsafe_allow_html=True)# Add download button if we have a valid responseif st.session_state.creative_response and not st.session_state.creative_response.startswith("Error") and not st.session_state.creative_response.startswith("Debes"):# Get current timestamp for the filenametimestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")# Prepare content for download (use the original unformatted response)download_content = st.session_state.creative_response# Download buttonst.download_button(label="DESCARGAR IDEAS CREATIVAS",data=download_content,file_name=f"conceptos_creativos_{timestamp}.txt",mime="text/plain")1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385391 unmodified lineimport 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"))# Create a reusable function for generation and display# Función auxiliar para mostrar el contenido generado y los botones de descargadef 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 GUION DE MI WEBINAR ▶▶"file_name = f"guion_webinar_{timestamp}.md"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/markdown",key=f"download_top_{content_type}")else: # nombressubheader_text = "Tus nombres de webinar:"# Mostrar el contenido generadocol.subheader(subheader_text)col.markdown(generated_content)# Mostrar botón de descarga inferior solo para guionesif content_type == "script":col.download_button(label=download_label,data=generated_content,file_name=file_name,mime="text/markdown",key=f"download_bottom_{content_type}")# 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 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 and intriguing 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 and memorable- Avoid clichés and generalities- Maintain an intriguing but credible tone- Adapt speaking language from the audience- Focus on transformative benefits- Follow the selected formula structure- 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 webinar names for {audience} "f"that instantly capture attention and generate registrations for a webinar about {topic}. "f"Focus on awakening genuine interest and communicating the value they will get by registering."f"\n\n"f"IMPORTANT: Carefully study these examples of the selected formula. "f"Each example represents the style and structure to follow"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:\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. Maintain the same structure and length as the previous examples\n"webinar_names_instruction += "2. Use the same tone and writing style\n"webinar_names_instruction += "3. Replicate the phrase construction patterns\n"webinar_names_instruction += "4. Preserve the level of specificity and detail\n"webinar_names_instruction += f"5. Adapt the content for {audience} while maintaining the essence of the examples\n\n"webinar_names_instruction += f"FORMULA TO FOLLOW:\n{selected_formula['description']}\n\n"webinar_names_instruction += f"""GENERATE NOW:Create {number_of_names} webinar names that faithfully follow the style and structure of the examples shown."""# 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)# In the generate_and_display function, where the download functionality is implementeddef generate_and_display(col, generator_func, audience, product, temperature, selected_formula, content_type, offer=None, creative_idea=None):# ... existing code ...# Display the generated contentwith col:if content_type == "script":st.markdown(f"## Tu guión de webinar:")st.markdown(generated_content)# Create download content with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")download_content = generated_content# Download buttonst.download_button(label="DESCARGAR GUIÓN DE WEBINAR",data=download_content,file_name=f"guion_webinar_{timestamp}.txt",mime="text/plain")elif content_type == "names":st.markdown(f"## Nombres para tu webinar:")st.markdown(generated_content)# Create download content with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")download_content = generated_content# Download buttonst.download_button(label="DESCARGAR NOMBRES DE WEBINAR",data=download_content,file_name=f"nombres_webinar_{timestamp}.txt",mime="text/plain")# ... existing code ...
app.py+488-260