Spaces:
Sleeping
Sleeping
from dotenv import load_dotenv | |
import streamlit as st | |
import os | |
import google.generativeai as genai | |
from ads_formulas import ads_formulas # Import the ads formulas | |
from style import styles | |
from prompts import create_fb_ad_instruction | |
from emotional_angles import emotional_angles | |
from copywriter_personas import copywriter_personas | |
from ad_objectives import ad_objectives # Import ad objectives | |
# Cargar las variables de entorno | |
load_dotenv() | |
# Configurar la API de Google | |
genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) | |
# Función para generar modelo | |
def get_model(temperature): | |
generation_config = { | |
"temperature": temperature, | |
} | |
return genai.GenerativeModel('gemini-2.0-flash', generation_config=generation_config) | |
# Function to generate Facebook ads | |
def generate_fb_ad(target_audience, product, temperature, selected_formula, selected_angle, selected_persona, story_prompt="", ad_objective=None): | |
if not target_audience or not product: | |
return "Por favor, completa todos los campos requeridos." | |
# Enfatizar el tema de la historia si se proporciona | |
emphasized_story_prompt = story_prompt | |
if story_prompt and story_prompt.strip(): | |
# Añadir énfasis al tema para que el modelo le dé más importancia | |
emphasized_story_prompt = story_prompt.strip() | |
model = get_model(temperature) | |
ad_instruction = create_fb_ad_instruction( | |
target_audience, | |
product, | |
selected_formula, | |
selected_angle, | |
selected_persona, | |
ad_objective, | |
language="español", # Fixed to Spanish | |
story_prompt=emphasized_story_prompt # Usar el tema enfatizado | |
) | |
# Si hay un tema específico, ajustar la temperatura para mayor coherencia | |
effective_temperature = temperature | |
if story_prompt and story_prompt.strip(): | |
# Reducir ligeramente la temperatura para mantener más enfoque en el tema | |
effective_temperature = max(0.1, temperature * 0.9) | |
response = model.generate_content([ad_instruction], generation_config={"temperature": effective_temperature}) | |
return response.parts[0].text if response and response.parts else "Error generating content." | |
# Configurar la interfaz de usuario con Streamlit | |
st.set_page_config(page_title="Facebook Ads Generator", layout="wide") | |
# Leer el contenido del archivo manual.md | |
with open("manual.md", "r", encoding="utf-8") as file: | |
manual_content = file.read() | |
# Mostrar el contenido del manual en el sidebar | |
st.sidebar.markdown(manual_content) | |
# Ocultar elementos de la interfaz | |
st.markdown(styles["main_layout"], unsafe_allow_html=True) | |
# Centrar el título y el subtítulo | |
st.markdown("<h1 style='text-align: center;'>Facebook Ads Generator</h1>", unsafe_allow_html=True) | |
st.markdown("<h4 style='text-align: center;'>Crea anuncios persuasivos que conectan con tu audiencia y generan conversiones.</h4>", unsafe_allow_html=True) | |
# Añadir CSS personalizado para el botón | |
st.markdown(styles["button"], unsafe_allow_html=True) | |
# Crear columnas | |
col1, col2 = st.columns([1, 2]) | |
# Modificar la parte de la interfaz de usuario para usar session_state | |
# Inicializar valores en session_state si no existen | |
if 'ad_target_audience' not in st.session_state: | |
st.session_state.ad_target_audience = "" | |
if 'ad_product' not in st.session_state: | |
st.session_state.ad_product = "" | |
if 'input_prompt' not in st.session_state: | |
st.session_state.input_prompt = "" | |
if 'ad_formula_key' not in st.session_state: | |
st.session_state.ad_formula_key = list(ads_formulas.keys())[0] | |
if 'emotional_angle_key' not in st.session_state: | |
st.session_state.emotional_angle_key = list(emotional_angles.keys())[0] | |
if 'ad_persona_key' not in st.session_state: | |
st.session_state.ad_persona_key = list(copywriter_personas.keys())[0] | |
if 'ad_objective_key' not in st.session_state: | |
st.session_state.ad_objective_key = list(ad_objectives.keys())[0] | |
if 'ad_temperature' not in st.session_state: | |
st.session_state.ad_temperature = 1.0 | |
# Funciones para actualizar el estado | |
def update_target_audience(): | |
st.session_state.ad_target_audience = st.session_state.target_audience_input | |
def update_product(): | |
st.session_state.ad_product = st.session_state.product_input | |
def update_prompt(): | |
st.session_state.input_prompt = st.session_state.prompt_input | |
# Columnas de entrada | |
with col1: | |
st.text_input( | |
"¿Quién es tu público objetivo?", | |
placeholder="Ejemplo: Madres trabajadoras de 30-45 años", | |
key="target_audience_input", | |
value=st.session_state.ad_target_audience, | |
on_change=update_target_audience | |
) | |
st.text_input( | |
"¿Qué producto tienes en mente?", | |
placeholder="Ejemplo: Curso de gestión del tiempo", | |
key="product_input", | |
value=st.session_state.ad_product, | |
on_change=update_product | |
) | |
st.text_area( | |
"Escribe de qué quieres que trate la historia:", | |
placeholder="Escribe aquí tu idea...", | |
key="prompt_input", | |
value=st.session_state.input_prompt, | |
on_change=update_prompt | |
) | |
with st.expander("Opciones avanzadas"): | |
# Selector de fórmula de anuncio | |
ad_formula_key = st.selectbox( | |
"Fórmula de anuncio", | |
options=list(ads_formulas.keys()), | |
label_visibility="visible", | |
key="ad_formula_key", | |
index=list(ads_formulas.keys()).index(st.session_state.ad_formula_key) | |
) | |
st.session_state.ad_formula_key = ad_formula_key | |
ad_formula = ads_formulas[ad_formula_key] | |
# Selector de ángulo emocional | |
emotional_angle_key = st.selectbox( | |
"Ángulo emocional", | |
options=list(emotional_angles.keys()), | |
label_visibility="visible", | |
key="emotional_angle_key", | |
index=list(emotional_angles.keys()).index(st.session_state.emotional_angle_key) | |
) | |
st.session_state.emotional_angle_key = emotional_angle_key | |
emotional_angle = emotional_angles[emotional_angle_key] | |
# Selector de personalidad de copywriter | |
ad_persona_key = st.selectbox( | |
"Estilo de copywriter", | |
options=list(copywriter_personas.keys()), | |
format_func=lambda x: x.replace("_", " "), | |
label_visibility="visible", | |
key="ad_persona_key", | |
index=list(copywriter_personas.keys()).index(st.session_state.ad_persona_key) | |
) | |
st.session_state.ad_persona_key = ad_persona_key | |
ad_persona = copywriter_personas[ad_persona_key] | |
# Selector de objetivo de anuncio | |
ad_objective_key = st.selectbox( | |
"Objetivo de la campaña", | |
options=list(ad_objectives.keys()), | |
label_visibility="visible", | |
key="ad_objective_key", | |
index=list(ad_objectives.keys()).index(st.session_state.ad_objective_key) | |
) | |
st.session_state.ad_objective_key = ad_objective_key | |
selected_objective = ad_objectives[ad_objective_key] if ad_objective_key != "ninguno" else None | |
# Slider de temperatura | |
ad_temperature = st.slider( | |
"Nivel de creatividad", | |
min_value=0.0, | |
max_value=2.0, | |
value=st.session_state.ad_temperature, | |
step=0.1, | |
label_visibility="visible", | |
key="ad_temperature_slider" | |
) | |
st.session_state.ad_temperature = ad_temperature | |
# Usar los valores de session_state para el botón de generación | |
submit_ad = st.button("GENERAR ANUNCIO") | |
# Mostrar el anuncio generado | |
if submit_ad: | |
if st.session_state.ad_target_audience and st.session_state.ad_product: | |
# Mover el spinner a la segunda columna | |
with col2: | |
with st.spinner('Generando anuncio...'): | |
generated_ad = generate_fb_ad( | |
st.session_state.ad_target_audience, | |
st.session_state.ad_product, | |
st.session_state.ad_temperature, | |
ad_formula, | |
emotional_angle, | |
ad_persona, | |
st.session_state.input_prompt, | |
selected_objective | |
) | |
if not isinstance(generated_ad, str): | |
st.error("Error al generar el anuncio") | |
else: | |
st.markdown(f""" | |
<div style="{styles['results_container']}"> | |
<h3>Anuncio Generado:</h3> | |
<p>{generated_ad}</p> | |
</div> | |
""", unsafe_allow_html=True) | |
else: | |
col2.warning("Por favor, completa todos los campos antes de generar el anuncio.") |