Spaces:
Sleeping
Sleeping
File size: 9,180 Bytes
6cbfd9d 61f706c 6cbfd9d b5d094d 48ca5b5 b5d094d 48ca5b5 b5d094d 48ca5b5 b5d094d 48ca5b5 2eab768 6cbfd9d b5d094d 6cbfd9d 5f6663a 2eab768 5f6663a d442069 5f6663a b5d094d 5f6663a d442069 5f6663a 6cbfd9d b5d094d 6cbfd9d b5d094d 2eab768 6cbfd9d e411757 232fce4 2eab768 ad8bd78 232fce4 3d42c0e e411757 232fce4 ad8bd78 e411757 346ec34 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
import random
# Cargar las variables de entorno
load_dotenv()
# Configurar la API de Google
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Funci贸n para obtener una menci贸n del producto de manera probabil铆stica
def get_random_product_mention():
mentions = ["Directa", "Indirecta", "Metaf贸rica"]
probabilities = [0.20, 0.30, 0.50] # Probabilidades ajustadas
return random.choices(mentions, probabilities)[0]
# Crear la instrucci贸n de menci贸n basada en la opci贸n seleccionada
def get_mention_instruction(product_mention, product):
if product_mention == "Directa":
return f"""
Directly introduce the product '{product}' as the clear solution to the problem the reader is facing. Ensure that the product is presented in a way that highlights its key benefits and demonstrates how it directly addresses the issue at hand. The mention should feel natural and seamlessly integrated into the narrative.
"""
elif product_mention == "Indirecta":
return f"""
Subtly reference the product '{product}' as a potential solution to the reader's problem without naming it explicitly. Weave the product's core benefits into the description of how the reader can overcome the issue, creating an implicit connection between the solution and the product. Ensure the mention is subtle but clear enough to guide the reader towards the product.
"""
elif product_mention == "Metaf贸rica":
return f"""
Introduce the product '{product}' using a metaphor, connecting it symbolically to the solution the reader needs. The metaphor should relate to the problem being discussed and should creatively suggest how the product offers a resolution without explicitly stating its name. The metaphor should evoke the benefits of the product in a memorable and thought-provoking way.
"""
return ""
# Funci贸n para obtener una cantidad de bullets
def get_gemini_response_bullets(target_audience, product, num_bullets, temperature):
product_mention = get_random_product_mention()
mention_instruction = get_mention_instruction(product_mention, product) # Define aqu铆
model_choice = "gemini-1.5-flash" # Modelo por defecto
# Configuraci贸n del modelo generativo y las instrucciones del sistema
model = genai.GenerativeModel(
model_name=model_choice, # Nombre del modelo que estamos utilizando
generation_config={
"temperature": temperature, # Cambiamos creatividad por temperature
"top_p": 0.85,
"top_k": 128,
"max_output_tokens": 2048,
"response_mime_type": "text/plain",
},
system_instruction=(
f"You are a world-class copywriter, expert in creating benefits that connect symptoms with problems of {target_audience}. "
f"You deeply understand the emotions, desires, and challenges of {target_audience}, allowing you to design personalized copywriting that resonate and motivate action. "
f"You know how to use proven structures to attract {target_audience}, generating interest and creating a powerful connection with {product}. "
"Generate unusual, creative, and fascinating bullets that capturing {target_audience}'s attention. Respond in Spanish and use a numbered list format. "
"Important: Never include explanations or categories, like this: 'La leyenda del padre soltero: Dice que nunca hay tiempo suficiente. El yoga te ense帽a a usar mejor el tiempo que tienes, incluso cuando te parece imposible.' "
"Los bullets deben ser de los siguientes tipos: "
"* 'El armario del ba帽o es el mejor lugar para guardar medicamentos, 驴verdad? Incorrecto. Es el peor. Los hechos est谩n en la p谩gina 10.' "
"* 'El mejor tiempo verbal que le da a tus clientes la sensaci贸n de que ya te han comprado.' "
"* 'La historia de...', 'Los misterios de...', 'La leyenda de...' "
"* 'Un sistema simple para escribir textos sin intentar convencerlos de comprar.' "
"* Verdad: 'La verdad que nunca te han contado en la escuela, o en casa, sobre c贸mo ganarte la vida con la m煤sica.' "
"* '驴Sab铆as que...' "
"* '驴Cu谩ndo es una buena idea decirle a una chica que te gusta? Si no se lo dices en ese momento, desp铆dete de conocerla 铆ntimamente.' "
"Recuerda que un buen bullet debe tener:\n\n"
"1. **Conexi贸n**: Palabras que resalten la relaci贸n entre el producto y el beneficio para el usuario (e.g., 'Mejorar', 'Transformar').\n"
"2. **Beneficio**: Explicar c贸mo el usuario se beneficiar谩 al asistir, descargar o comprar el producto.\n\n"
"Aseg煤rate de que cada bullet siga la estructura de 'Conexi贸n + conector + Beneficio', y evita incluir explicaciones como 'Conexi贸n: Mejorar' o 'Beneficio: Aumentar mi felicidad'.\n"
"Importante: Solo responde con bullets, nunca incluyas explicaciones o categor铆as, como este ejemplo: 'Asistir a la masterclass y descubrir t茅cnicas para potenciar mi carrera profesional. (Este bullet apela al deseo de crecimiento personal y profesional.)'\n"
"Los bullets deben de variados, basate en estos ejemplos para realizar tu tarea de crear bullets:\n\n"
"Usa estos lineamientos para generar bullets de alta conversi贸n en espa帽ol."
f"Al responder, siempre incluye un encabezado que haga referencia a {target_audience} y el producto de la siguiente manera: "
f"'Aqu铆 tienes 5 bullets para {target_audience}, que aumenten el deseo de adquirir el {product}, usando la menci贸n indirecta:' "
)
)
# Crear el prompt para generar bullets
bullets_instruction = (
f"Tu tarea es escribir {num_bullets} bullets que denoten los beneficios del {product} y que tienen la cualidad de fascinar y por lo tanto, fomentan el deseo de adquirir, asistir, descargar o comprar el {product}."
f"Un buen bullet conecta los s铆ntomas con los problemas enfrentado por {target_audience} de una manera natural, que no se note como manipuladora."
f"Escribe bullets creativos, en un estilo conversacional, que no sean aburridos, sino mas bien divertidos. "
f"Utiliza la funci贸n {mention_instruction} al crear los bullets para referirte a los beneficios del {product}. "
"Por favor, crea los bullets ahora."
)
# Crear un mensaje para el modelo que incluye los bullets generados seg煤n los tipos seleccionados
full_prompt = f"{bullets_instruction}"
response = model.generate_content([full_prompt])
if response and response.parts:
return response.parts[0].text
else:
raise ValueError("Lo sentimos, intenta con una combinaci贸n diferente de entradas.")
# Inicializar la aplicaci贸n Streamlit
st.set_page_config(page_title="Generador de Bullets", layout="wide")
# Centrar el t铆tulo y el subt铆tulo
st.markdown("<h1 style='text-align: center;'>Impact Bullet Generator</h1>", unsafe_allow_html=True)
st.markdown("<h4 style='text-align: center;'>Transforma los pensamientos de tu audiencia en balas persuasivas que inspiren a la acci贸n.</h4>", unsafe_allow_html=True)
# A帽adir CSS personalizado para el bot贸n
st.markdown("""
<style>
div.stButton > button {
background-color: #FFCC00;
color: black;
width: 90%;
height: 60px;
font-weight: bold;
font-size: 22px;
text-transform: uppercase;
border: 1px solid #000000;
border-radius: 8px;
display: block;
margin: 0 auto;
}
div.stButton > button:hover {
background-color: #FFD700;
color: black;
}
</style>
""", unsafe_allow_html=True)
# Crear dos columnas para el layout (40% y 60%)
col1, col2 = st.columns([2, 3])
with col1:
# Campos de entrada
target_audience = st.text_input("驴Qui茅n es tu p煤blico objetivo?")
product = st.text_input("驴Qu茅 producto tienes en mente?")
# Campos de personalizaci贸n sin acorde贸n
num_bullets = st.slider("N煤mero de Bullets", min_value=1, max_value=15, value=5)
temperature = st.slider("Creatividad", min_value=0.0, max_value=1.0, value=0.5, step=0.1)
# Bot贸n de enviar
submit = st.button("Generar Bullets")
# Mostrar los bullets generados
if submit:
if target_audience and product:
try:
# Obtener la respuesta del modelo
generated_bullets = get_gemini_response_bullets(target_audience, product, num_bullets, temperature)
col2.markdown(f"""
<div style="border: 1px solid #000000; padding: 5px; border-radius: 8px; background-color: #ffffff;">
<h4>Observa la magia en acci贸n:</h4>
<p>{generated_bullets}</p>
</div>
""", unsafe_allow_html=True)
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, proporciona el p煤blico objetivo y el producto.")
|