Spaces:
Sleeping
Sleeping
File size: 6,967 Bytes
91a0d7e a8fd769 5d758ad d51e47b a8fd769 d51e47b 5d758ad e661bf0 5d758ad 59b4bb9 5d758ad 59b4bb9 1ff0df4 59b4bb9 ff0dac9 f4e4aff 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 2610857 1ff0df4 83e23ac 59b4bb9 1ff0df4 59b4bb9 1ff0df4 a8fd769 1ff0df4 d51e47b 1ff0df4 5d758ad 4ee7a48 5aaf0f3 5d758ad 6bb7353 4ee7a48 5aaf0f3 e661bf0 2c60041 |
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 |
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
import random # Nueva importación para la selección aleatoria de mención
load_dotenv()
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.34, 0.33, 0.33] # Probabilidades de cada mención
return random.choices(mentions, probabilities)[0]
# Función para obtener una técnica de copywriting de manera aleatoria
def get_random_copywriting_technique():
techniques = [
"If/Then: This is one of the most commonly used opening paragraphs. It’s very simple, clear, and powerful.",
"If / Then + Authority: Adding a figure of authority or credibility to the opening.",
"Honesty: Being transparent is one of the best ways to get more customers.",
"Sensationalist: It grabs attention with unusual or provocative statements.",
"Ask a Question: It makes people stop if they’re interested.",
"Micro Openings: Keep it brief to encourage further reading."
]
return random.sample(techniques, k=random.randint(1, 3)) # Escoge entre 1 y 3 técnicas al azar
# Al crear el prompt completo, incluye el tamaño y las técnicas seleccionadas
def get_gemini_response(target_audience, product, text_type, length, mood, model_choice):
product_mention = get_random_product_mention()
model = genai.GenerativeModel(model_choice)
# Obtener técnicas aleatorias
copywriting_techniques = get_random_copywriting_technique()
techniques_text = " ".join(copywriting_techniques)
# Instrucción específica para el tipo de texto
format_instruction = ""
if text_type == "Historia":
format_instruction = f"""
Write an engaging opening paragraph that introduces a relatable problem your audience is facing. Stir emotions by highlighting the impact of the problem on their life, and create curiosity with hints of a potential solution without revealing everything. The paragraph should be approximately {length} words long to maintain engagement and avoid losing the reader's attention.
"""
elif text_type == "Carta de venta":
format_instruction = f"""
Craft a persuasive lead paragraph for a sales letter that quickly identifies a common pain point your reader is experiencing. The paragraph should be around {length} words long and agitate the problem by emphasizing the negative consequences of not addressing it, and tease the possibility of a solution to spark curiosity.
"""
elif text_type == "Correo":
format_instruction = f"""
Write a concise but impactful opening paragraph for an email that captures the reader’s attention. The text should be approximately {length} words, addressing a challenge they are likely facing, and leave them intrigued by hinting at a valuable solution that will be revealed if they continue reading.
"""
elif text_type == "Landing page":
format_instruction = f"""
Design a compelling first paragraph for a landing page that immediately draws attention to a significant problem your target audience is encountering. The paragraph should be about {length} words long, stirring emotions and enticing them to keep scrolling by subtly suggesting a solution.
"""
# Crear el prompt completo basado en los campos del frontend
full_prompt = f"""
You are a creative writer skilled in the art of persuasion. The tone of the {text_type} should be {mood} and carefully crafted to emotionally resonate with a {target_audience}. {product_mention} {format_instruction}
Incorporate the following copywriting techniques: {techniques_text}
Use persuasive techniques to guide the reader towards an intuitive understanding of the product's benefits, focusing on creating a strong emotional connection with the audience.
Create an opening paragraph for a {text_type} of {length} words in Spanish, that makes {target_audience} aware they have a problem by explaining it with real-life situations, using a natural or conversational tone. The goal of this paragraph is to make them want to keep reading and find out what {product} is about. Use persuasion effectively in every word, mastering advanced techniques.
"""
response = model.generate_content([full_prompt])
# Comprobar si la respuesta es válida y devolver el texto
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="VisionTales", layout="wide")
st.title("VisionTales: Crea historias inolvidables con IA")
# Añadir CSS personalizado para el botón
st.markdown("""
<style>
div.stButton > button {
background-color: #FFCC00; /* Color llamativo */
color: black; /* Texto en negro */
width: 90%;
height: 60px;
font-weight: bold;
font-size: 22px; /* Tamaño más grande */
text-transform: uppercase; /* Texto en mayúsculas */
border: 1px solid #000000; /* Borde negro de 1px */
border-radius: 8px;
display: block;
margin: 0 auto; /* Centramos el botón */
}
div.stButton > button:hover {
background-color: #FFD700; /* Color al pasar el mouse */
color: black; /* Texto sigue en negro */
}
</style>
""", unsafe_allow_html=True)
# Crear dos columnas para el diseño (40% y 60%)
col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 partes en total
with col1:
# Crear campos de entrada
target_audience = st.text_input("¿Quién es tu público objetivo?")
product = st.text_input("¿Qué producto tienes en mente?")
text_type = st.selectbox("Tipo de texto", ["Historia", "Carta de venta", "Correo", "Landing page"])
length = st.slider("Número de palabras", min_value=50, max_value=500, value=100)
mood = st.selectbox("Tono de voz", ["Conversacional", "Formal", "Emocional", "Persuasivo"])
model_choice = st.selectbox("Modelo", ["gemini-1.5-flash", "gemini-1.5-pro"])
# Botón para generar el texto (dentro de la interfaz principal)
if st.button("Escribir mi texto"):
if target_audience and product: # Verificar que se haya proporcionado el público objetivo y el producto
try:
# Obtener la respuesta del modelo
generated_text = get_gemini_response(target_audience, product, text_type, length, mood, model_choice)
col2.subheader("Contenido generado:")
col2.write(generated_text) # Resultado del texto generado
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, proporciona el público objetivo y el producto.")
|