JeCabrera's picture
Upload 19 files
f724c1b verified
raw
history blame
16.6 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}"
)
# Add this function near the top of your file
def load_prompt_from_file(file_path):
try:
with open(file_path, "r", encoding="utf-8") as file:
return file.read()
except Exception as e:
st.error(f"Error al cargar el prompt desde {file_path}: {str(e)}")
return ""
# Función para generar la sección "Above the Fold"
def generate_above_the_fold(audience, product, temperature, offer=None, **kwargs):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/above_the_fold.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/problem.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/solution_benefits.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/authority.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/offer_bonus.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/social_proof.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/guarantees.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/cta.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/ps.txt")
# 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):
# Cargar el prompt desde el archivo
system_prompt = load_prompt_from_file("prompts/final_cta.txt")
# 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.")