FirstParagraph / app.py
JeCabrera's picture
Update app.py
16c57a6 verified
raw
history blame
5.49 kB
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Funci贸n para obtener respuesta del modelo Gemini
def get_gemini_response(target_audience, product, product_mention, text_type, length, mood, model_choice):
model = genai.GenerativeModel(model_choice)
# Crear la instrucci贸n de menci贸n basada en la opci贸n seleccionada
mention_instruction = ""
if product_mention == "Directa":
mention_instruction = f"Mention the product '{product}' directly in the text."
elif product_mention == "Indirecta":
mention_instruction = f"Ensure that subtle and realistic references to the product '{product}' are included without explicitly mentioning it."
elif product_mention == "Metaf贸rica":
mention_instruction = f"Refer to the product '{product}' through a metaphor without explicitly mentioning it."
# Instrucci贸n espec铆fica para el tipo de texto
format_instruction = ""
if text_type == "Historia":
format_instruction = "Ensure that the narrative is engaging and includes character development, a clear plot, and a resolution."
elif text_type == "Carta de venta":
format_instruction = "Craft a compelling sales pitch that highlights the product's benefits and persuades the reader to take action."
elif text_type == "Correo":
format_instruction = "Write a concise and engaging email that captures the reader's attention and encourages a response."
elif text_type == "Landing page":
format_instruction = "Design an informative and persuasive landing page that effectively showcases the product and drives conversions."
# Crear el prompt completo basado en los campos del frontend
full_prompt = f"""
You are a creative writer skilled in the art of persuasion. Write a {length} {text_type} in Spanish. The tone of the {text_type} should be {mood} and carefully crafted to emotionally resonate with a {target_audience}. {mention_instruction} {format_instruction} 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.
"""
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="Poetic Vision", page_icon=":pencil:", layout="wide") # Configurar el dise帽o en ancho
# Componentes principales de la UI
st.markdown("<h1 style='text-align: center;'>VisionTales</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center;'>Convierte tus ideas en historias inolvidables.</h3>", unsafe_allow_html=True)
# 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:
# Entradas del usuario
target_audience = st.text_input("P煤blico objetivo:", placeholder="Especifica tu p煤blico aqu铆...")
product = st.text_input("Producto:", placeholder="Especifica el producto aqu铆...")
# Agrupar todas las opciones en una acorde贸n
with st.expander("Personaliza tu texto"):
# Variable para c贸mo se debe mencionar el producto
product_mention = st.selectbox("Menci贸n del producto:", ["Directa", "Indirecta", "Metaf贸rica"])
# Opciones actualizadas para el tipo de texto
text_type = st.selectbox("Tipo de texto:", ["Historia", "Carta de venta", "Correo", "Landing page"])
length = st.selectbox("Longitud del texto:", ["Corto", "Largo"])
mood = st.selectbox("Tono del Texto:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Rom谩ntico"])
# Opci贸n para seleccionar el modelo
model_choice = st.selectbox("Selecciona el modelo:", ["gemini-1.5-flash", "gemini-1.5-pro"], index=0)
# Bot贸n para generar contenido
submit = st.button("Escribir mi historia")
# Manejo del clic en el bot贸n
if submit:
if target_audience and product: # Verificar que se haya proporcionado el p煤blico objetivo y el producto
try:
response = get_gemini_response(target_audience, product, product_mention, text_type, length, mood, model_choice)
col2.subheader("Contenido generado:")
col2.write(response)
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, proporciona el p煤blico objetivo y el producto.")