JeCabrera's picture
Update app.py
2232f78 verified
raw
history blame
4.5 kB
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
# Cargar variables de entorno
load_dotenv()
# Configurar API de Google Gemini
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Función para obtener la respuesta del modelo Gemini
def get_gemini_response(input_prompt, genre, length, language, mood, target_audience, cta_type):
if not input_prompt:
return "Por favor, escribe un mensaje para generar contenido."
model = genai.GenerativeModel('gemini-2.0-flash')
full_prompt = f"""
You are a professional storyteller. Write a {mood} {genre} in {language} using a natural, engaging, and conversational style.
The story should be about "{input_prompt}" and use exactly {length} words.
Target Audience: {target_audience}
CTA Type: {cta_type}
First, identify the main benefit that would resonate most with {target_audience} based on the story topic and CTA type.
Then, write a story that naturally leads to this benefit.
Structure:
1. Introduce a relatable problem that captures the audience's attention
2. Develop the story with natural narrative and emotional connection
3. Show consequences of inaction
4. Present the solution organically
5. Close with a specific call to action based on the type:
- For product purchase: Show how buying transforms their situation
- For PDF guide: Highlight how the guide provides the knowledge they need
- For webinar: Emphasize how the live training will help them succeed
Make the CTA feel natural and focus on the transformation they'll experience.
### **Ejemplo de historia bien escrita:**
En una lejana galaxia, el maestro Xylo dictaba clases en la Tierra.
Sus métodos eran monótonos, y sus alumnos bostezaban sin parar.
“¿Por qué no prestan atención?”, se preguntaba.
Frustrado, investigó y descubrió que el problema no eran los niños, sino sus clases aburridas.
Por eso decidió cambiar.
Tomó un curso online para hacer sus lecciones dinámicas y sorprendentes.
Pronto, sus alumnos rieron, participaron y aprendieron con entusiasmo.
Si Xylo pudo transformar sus clases, tú también.
Inscríbete hoy aquí.
**Importante:**
- **Haz que la historia sea humana y emocional**, evitando frases promocionales evidentes.
"""
response = model.generate_content([full_prompt])
return response.parts[0].text if response and response.parts else "Error al generar contenido."
# Configurar la aplicación Streamlit
st.set_page_config(page_title="Story Generator", page_icon=":pencil:", layout="wide")
# Título de la app
st.markdown("""
<h1 style='text-align: center;'>Generador de Historias</h1>
<h3 style='text-align: center;'>Escribe una idea y la IA creará una historia única.</h3>
""", unsafe_allow_html=True)
# Crear dos columnas
col1, col2 = st.columns([1, 1])
# Columna izquierda para inputs
# Remove the benefit input field
with col1:
# Entrada de texto principal
input_prompt = st.text_area("Escribe de qué quieres que trate la historia:", placeholder="Escribe aquí tu idea...")
# Campos de texto libre
target_audience = st.text_input("Público Objetivo:", placeholder="Ejemplo: Profesionales de 25-35 años interesados en tecnología...")
# CTA type only
cta_type = st.selectbox("Tipo de llamado a la acción:", [
"Comprar producto",
"Descargar guía PDF",
"Asistir a webinar"
])
# Opciones avanzadas en acordeón
with st.expander("Opciones avanzadas"):
genre = st.selectbox("Tipo de texto:", ["Historia", "Poema", "Cita", "Ensayo"])
length = st.slider("Longitud del texto (palabras):",
min_value=25,
max_value=100,
value=60,
step=5)
language = st.selectbox("Idioma del texto:", ["Español", "Inglés"])
mood = st.selectbox("Estado de ánimo:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
generate_button = st.button("Generar historia")
with col2:
if generate_button:
response = get_gemini_response(
input_prompt, genre, length, language,
mood, target_audience, cta_type
)
st.subheader("Contenido generado:")
st.write(response)