JeCabrera's picture
Update app.py
cb9d211 verified
raw
history blame
26.1 kB
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
import datetime
from streamlit import session_state as state
# Cargar las variables de entorno
load_dotenv()
# Configurar la API de Google
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Función para inicializar el modelo
def initialize_model(temperature=1.0):
return genai.GenerativeModel(
model_name="gemini-2.0-flash",
generation_config={"temperature": temperature}
)
# Función para generar contenido
def generate_content(prompt, temperature=1.0):
model = initialize_model(temperature)
response = model.generate_content(prompt)
return response.text
# Función auxiliar para mostrar el contenido generado y los botones de descarga
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 == "sales_page_section":
download_label = "DESCARGAR SECCIÓN DE CARTA DE VENTAS ▶▶"
file_name = f"seccion_carta_ventas_{timestamp}.txt"
subheader_text = "Tu sección de carta de ventas:"
# Mostrar botón de descarga superior
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}"
)
# Función para generar la sección "Above the Fold"
def generate_above_the_fold(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers by addressing their pain points and offering compelling solutions.
THE EXPERT TEAM:
1. MASTER SALES PAGE STRATEGIST:
- Expert in sales page frameworks and conversion strategies
- Trained in the Perfect Sales Page methodology by Russell Brunson
- Ensures the copy follows proven sales page 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 headlines, hooks, and persuasive elements
- Crafts irresistible calls to action that drive conversions
- Specializes in problem-solution frameworks that resonate deeply
3. AUDIENCE PSYCHOLOGY SPECIALIST:
- Expert in understanding audience pain points and objections
- Creates content that builds genuine connection and trust
- Identifies and addresses hidden fears and desires
- Ensures the content feels personal and relevant to the ideal customer
YOUR TASK:
Create the ABOVE THE FOLD section of a compelling sales page following the "Headline Pack" structure that includes pre-headline, headline, and subheadline.
HEADLINE PACK STRUCTURE:
1. PRE-HEADLINE: "Atención: Solo para [customer identity]"
2. HEADLINE: "CÓMO LOGRAR/HACER [DESIRED END RESULT] EN [STEPS OR TIME IN WHICH IT IS ACHIEVED]"
3. SUBHEADLINE: "(incluso si [main objection])"
FORMAT REQUIREMENTS:
- Create a powerful headline that promises a specific transformation
- Include a pre-headline that clearly identifies the target audience
- Add a subheadline that addresses the main objection
- Include primary CTA button text
- Ensure it speaks directly to the specific target market
- Write in Spanish
- Start directly with the sales page content without introductory text
EXAMPLE HEADLINE PACK:
"Atención: Solo para inversionistas en bienes raíces principiantes.
CÓMO HACER TU PRIMERA INVERSIÓN SEGURA EN BIENES RAÍCES EN 3 SIMPLES PASOS…
(incluso si tienes poco capital disponible)."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Create a powerful headline that captures attention immediately
- Focus on the transformation your product/service provides
- Highlight the main benefit in the subheadline
- Create a sense of urgency and curiosity
- Include a clear call to action
- Use language that resonates with your specific audience
"""
# Instrucciones específicas para la tarea
above_fold_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the ABOVE THE FOLD section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must be compelling, attention-grabbing, and drive conversions."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
above_fold_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(above_fold_instruction, temperature)
# Función para generar la sección "Problem"
def generate_problem_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers by addressing their pain points and offering compelling solutions.
YOUR TASK:
Create the PROBLEM section of a compelling sales page that addresses the pain points of the ideal customer.
FORMAT REQUIREMENTS:
- Describe the pain points your target audience is experiencing
- Use questions to help prospects identify with the problem
- Agitate the problem by explaining consequences of not solving it
- Include specific examples that resonate with your audience
- Make the prospect feel understood
- Use language and scenarios specific to the target market
- Write in Spanish
EXAMPLE PROBLEM SECTION:
"¿Estás cansado de trabajar largas horas y no ver resultados? ¿Sientes que no tienes tiempo para disfrutar de tu vida?"
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Identify and describe the main pain points of your target audience
- Use questions that help prospects identify with the problem
- Agitate the problem by explaining the consequences of not solving it
- Include specific examples that resonate with your audience
- Make the prospect feel understood
"""
# Instrucciones específicas para la tarea
problem_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the PROBLEM section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must clearly identify and agitate the pain points that your product/service solves."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
problem_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(problem_instruction, temperature)
# Función para generar la sección "Solution & Benefits"
def generate_solution_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers by addressing their pain points and offering compelling solutions.
YOUR TASK:
Create the SOLUTION & BENEFITS section of a compelling sales page that offers a solution through the product/service.
FORMAT REQUIREMENTS:
- Present your product/service as the ideal solution to the problems described
- Highlight the key features and their corresponding benefits
- Explain how your solution works in a clear, step-by-step manner
- Include specific results or transformations customers can expect
- Address potential objections preemptively
- Use bullet points to highlight key benefits
- Write in Spanish
EXAMPLE SOLUTION & BENEFITS SECTION:
"Con nuestro sistema probado, aprenderás a automatizar tus procesos y generar ingresos pasivos mientras disfrutas de tu tiempo libre."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Present your product/service as the ideal solution to the problems described
- Highlight the key features and their corresponding benefits
- Explain how your solution works in a clear, step-by-step manner
- Include specific results or transformations customers can expect
- Address potential objections preemptively
- Use bullet points to highlight key benefits
"""
# Instrucciones específicas para la tarea
solution_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the SOLUTION & BENEFITS section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must present your product/service as the ideal solution to the problems described earlier."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
solution_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(solution_instruction, temperature)
# Función para generar la sección "Authority"
def generate_authority_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the AUTHORITY section of a compelling sales page that establishes credibility and trust.
FORMAT REQUIREMENTS:
- Highlight credentials, experience, and expertise
- Mention media appearances, publications, or recognition
- Include relevant statistics or achievements
- Establish why you are qualified to solve the customer's problem
- Write in Spanish
EXAMPLE AUTHORITY SECTION:
"Hemos ayudado a más de 10,000 emprendedores a alcanzar sus metas financieras. Aparecimos en Forbes y Entrepreneur."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Establish credibility through specific achievements
- Include relevant statistics that build trust
- Mention any media appearances or recognition
- Explain why you are qualified to solve the customer's problem
"""
# Instrucciones específicas para la tarea
authority_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the AUTHORITY section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must establish credibility and trust with the audience."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
authority_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(authority_instruction, temperature)
# Función para generar la sección "Offer & Bonus"
def generate_offer_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the OFFER & BONUS section of a compelling sales page that presents the offer in an irresistible way.
FORMAT REQUIREMENTS:
- Present the offer clearly with pricing information
- Highlight any discounts or limited-time offers
- Detail the bonuses included with the purchase
- Emphasize the value proposition
- Create a sense of urgency or scarcity
- Write in Spanish
EXAMPLE OFFER & BONUS SECTION:
"Por tiempo limitado, obtén acceso al curso completo por solo $99 (antes $299) e incluye 3 bonus exclusivos."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Present the offer clearly with pricing details
- Highlight any discounts or special offers
- Detail the bonuses included with the purchase
- Emphasize the total value the customer receives
- Create a sense of urgency or scarcity
"""
# Instrucciones específicas para la tarea
offer_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the OFFER & BONUS section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must present the offer in an irresistible way and highlight any bonuses."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
offer_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(offer_instruction, temperature)
# Función para generar la sección "Social Proof"
def generate_social_proof_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the SOCIAL PROOF section of a compelling sales page that builds trust through testimonials.
FORMAT REQUIREMENTS:
- Include testimonials from satisfied customers
- Highlight specific results or transformations
- Use full names and relevant details when possible
- Include diverse testimonials that address different benefits
- Write in Spanish
EXAMPLE SOCIAL PROOF SECTION:
"Mira lo que dicen nuestros clientes: 'Gracias a este curso, tripliqué mis ingresos en solo 2 meses' - Ana G."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Create realistic and specific testimonials
- Include full names and relevant details
- Highlight specific results or transformations
- Address different benefits or use cases
"""
# Instrucciones específicas para la tarea
social_proof_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the SOCIAL PROOF section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must build trust through testimonials and social proof."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
social_proof_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(social_proof_instruction, temperature)
# Función para generar la sección "Guarantees"
def generate_guarantees_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the GUARANTEES section of a compelling sales page that removes risk for the customer.
FORMAT REQUIREMENTS:
- Clearly state the guarantee terms
- Explain how the guarantee works
- Address potential objections or concerns
- Build trust through risk reversal
- Write in Spanish
EXAMPLE GUARANTEES SECTION:
"Si no estás satisfecho, te devolvemos el 100% de tu dinero. Sin preguntas."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Clearly state the guarantee terms
- Explain how the guarantee works
- Address potential objections or concerns
- Build trust through risk reversal
"""
# Instrucciones específicas para la tarea
guarantees_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the GUARANTEES section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must remove risk for the customer through strong guarantees."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
guarantees_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(guarantees_instruction, temperature)
# Función para generar la sección "Call to Action"
def generate_cta_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the CALL TO ACTION section of a compelling sales page that drives conversions.
FORMAT REQUIREMENTS:
- Create a clear and compelling call to action
- Use action-oriented language
- Remind the reader of the key benefits
- Create a sense of urgency
- Make the next step obvious and easy
- Write in Spanish
EXAMPLE CALL TO ACTION SECTION:
"Haz clic en el botón ahora y comienza tu transformación hoy mismo."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Create a clear and compelling call to action
- Use action-oriented language
- Remind the reader of the key benefits
- Create a sense of urgency
- Make the next step obvious and easy
"""
# Instrucciones específicas para la tarea
cta_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the CALL TO ACTION section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must drive conversions with a clear and compelling call to action."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
cta_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(cta_instruction, temperature)
# Función para generar la sección "P.S."
def generate_ps_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the P.S. (POSTSCRIPT) section of a compelling sales page that adds a final persuasive element.
FORMAT REQUIREMENTS:
- Start with "P.S." or "Recuerda"
- Add a final compelling reason to act now
- Remind the reader of scarcity or urgency
- Reinforce a key benefit or address a final objection
- Keep it brief but impactful
- Write in Spanish
EXAMPLE P.S. SECTION:
"P.S. Recuerda, esta oferta especial termina en 24 horas. No pierdas esta oportunidad."
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Start with "P.S." or "Recuerda"
- Add a final compelling reason to act now
- Remind the reader of scarcity or urgency
- Reinforce a key benefit or address a final objection
- Keep it brief but impactful
"""
# Instrucciones específicas para la tarea
ps_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the P.S. (POSTSCRIPT) section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must add a final persuasive element that drives action."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
ps_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(ps_instruction, temperature)
# Función para generar la sección "Final Call to Action"
def generate_final_cta_section(audience, product, temperature, offer=None, **kwargs):
system_prompt = """You are a collaborative team of world-class experts working together to create an exceptional sales page that converts visitors into customers.
YOUR TASK:
Create the FINAL CALL TO ACTION section of a compelling sales page that drives conversions.
FORMAT REQUIREMENTS:
- Create a final, powerful call to action
- Use strong, action-oriented language
- Make the button text clear and compelling
- Create a sense of urgency and excitement
- Write in Spanish
EXAMPLE FINAL CALL TO ACTION SECTION:
"¡RESERVA TU PLAZA AHORA!"
IMPORTANT INSTRUCTIONS:
- Write the entire section in Spanish
- Create a final, powerful call to action
- Use strong, action-oriented language
- Make the button text clear and compelling
- Create a sense of urgency and excitement
"""
# Instrucciones específicas para la tarea
final_cta_instruction = (
f"{system_prompt}\n\n"
f"Your task is to create the FINAL CALL TO ACTION section of a sales page IN SPANISH for {audience} "
f"about {product}. "
f"The section must drive conversions with a final, powerful call to action."
f"\n\n"
)
# Añadir información sobre la oferta si se proporciona
if offer:
final_cta_instruction += f"The specific offer/product is: {offer}\n\n"
# Enviar el mensaje al modelo
return generate_content(final_cta_instruction, temperature)
# Función para validar entradas
def validate_inputs(audience, product):
has_audience = audience.strip() != ""
has_product = product.strip() != ""
return has_audience and has_product
# Función para cargar CSS
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"<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}")
# Configuración de la página
st.set_page_config(
page_title="CopyXpert - Generador de Páginas de Ventas",
layout="wide",
initial_sidebar_state="expanded",
menu_items=None
)
load_css()
# Leer el contenido del archivo manual.md
try:
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)
except:
st.sidebar.warning("No se pudo cargar el manual. Asegúrate de que el archivo manual.md existe.")
# Agregar título y subtítulo usando HTML
st.markdown("<h1 style='text-align: center;'>CopyXpert</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center;'>Generador de Páginas de Ventas Persuasivas</h3>", unsafe_allow_html=True)
# Interfaz principal para el generador de páginas de ventas
st.subheader("Generador de Secciones de Páginas de Ventas")
# Crear columnas para la interfaz
col1, col2 = st.columns([1, 2])
# Columna de entrada
with col1:
# Inputs básicos
sales_page_audience = st.text_input("¿Quién es tu público objetivo?", placeholder="Ejemplo: Emprendedores digitales", key="sales_page_audience")
sales_page_product = st.text_input("¿Sobre qué producto/servicio es tu página?", placeholder="Ejemplo: Curso de marketing", key="sales_page_product")
sales_page_offer = st.text_input("¿Cuál es tu oferta específica?", placeholder="Ejemplo: Curso de marketing por $197", key="sales_page_offer")
# Selector de sección
sales_page_section = st.selectbox(
"Selecciona la sección a generar",
options=[
"Above the Fold (Encabezado)",
"Problem (Problema)",
"Solution & Benefits (Solución y Beneficios)",
"Authority (Autoridad)",
"Offer & Bonus (Oferta y Bonus)",
"Social Proof (Prueba Social)",
"Guarantees (Garantías)",
"Call to Action (Llamada a la Acción)",
"P.S. (Post-Data)",
"Final Call to Action (Llamada Final)"
],
key="sales_page_section"
)
# Botón de generación
submit_sales_page = st.button("GENERAR SECCIÓN DE PÁGINA DE VENTAS ▶▶", key="generate_sales_page")
# Opciones avanzadas en el acordeón
with st.expander("Personaliza tu sección"):
# Slider de creatividad
sales_page_temperature = st.slider("Creatividad", min_value=0.0, max_value=2.0, value=1.0, step=0.1, key="sales_page_temp")
# Generar y mostrar la sección de la página de ventas
if submit_sales_page:
# Validar entradas
if validate_inputs(sales_page_audience, sales_page_product):
try:
# Crear un contenedor para el spinner en la columna 2
with col2:
with st.spinner("Generando sección de página de ventas...", show_time=True):
# Mapear la selección a la función correspondiente
section_functions = {
"Above the Fold (Encabezado)": generate_above_the_fold,
"Problem (Problema)": generate_problem_section,
"Solution & Benefits (Solución y Beneficios)": generate_solution_section,
"Authority (Autoridad)": generate_authority_section,
"Offer & Bonus (Oferta y Bonus)": generate_offer_section,
"Social Proof (Prueba Social)": generate_social_proof_section,
"Guarantees (Garantías)": generate_guarantees_section,
"Call to Action (Llamada a la Acción)": generate_cta_section,
"P.S. (Post-Data)": generate_ps_section,
"Final Call to Action (Llamada Final)": generate_final_cta_section
}
# Obtener la función correspondiente
generator_func = section_functions[sales_page_section]
# Generar el contenido
generated_content = generator_func(
audience=sales_page_audience,
product=sales_page_product,
temperature=sales_page_temperature,
offer=sales_page_offer if sales_page_offer.strip() else None
)
# Mostrar el contenido generado fuera del bloque del spinner
display_generated_content(col2, generated_content, "sales_page_section")
except Exception as e:
st.error(f"Error al generar la sección: {str(e)}")
else:
st.warning("Por favor, completa los campos de público objetivo y producto/servicio.")