Spaces:
Running
Running
from dotenv import load_dotenv | |
import streamlit as st | |
import os | |
import google.generativeai as genai | |
from langdetect import detect | |
# 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 | |
# Remove language from function parameters | |
def get_gemini_response(input_prompt, genre, length, mood, target_audience, cta_type): | |
if not input_prompt: | |
return "Por favor, escribe un mensaje para generar contenido." | |
# Better language detection | |
try: | |
detected_lang = detect(input_prompt) | |
language = "Español" if detected_lang == "es" else "English" | |
except: | |
language = "Español" # Default to Spanish if detection fails | |
model = genai.GenerativeModel('gemini-2.0-flash') | |
full_prompt = f""" | |
You are a creative storyteller. Write a {mood} {genre} about "{input_prompt}" using everyday words and natural conversation. | |
Write in the same language as the input prompt ({language}). | |
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 | |
Keep in mind: | |
- Write for {target_audience} | |
- Use simple, clear language that everyone can understand | |
- Avoid technical terms or complex words | |
- Tell the story in short paragraphs | |
- End with a natural {cta_type} invitation | |
Example format: | |
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. | |
- Format the output in clear, separate paragraphs with line breaks | |
- Only write {genre}, anything else. | |
""" | |
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=100, | |
max_value=150, | |
value=125, | |
step=5) | |
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, | |
mood, target_audience, cta_type | |
) | |
st.subheader("Contenido generado:") | |
st.write(response) |