Spaces:
Running
Running
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, product_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 flow seamlessly and feel personal, not forced. | |
Use approximately {length} words (but prioritize quality over exact word count). | |
**Structure:** | |
1. **Introduce a relatable problem**: Describe a scenario that captures the attention of {target_audience}. Use emotions and common experiences in their lives. | |
2. **Develop the story**: Expand on the problem with details, showing the difficulties the protagonist faces. Use a natural and immersive narrative. | |
3. **Consequences of inaction**: What happens if the problem is not solved? Build urgency without sounding forced. | |
4. **Organic solution**: Introduce {product_type} as a logical option in the story, without making it sound like an advertisement. The story should naturally lead to the solution. | |
5. **Emotional or motivational ending**: End with a reflection or an implicit call to action. | |
The story should be about "{input_prompt}". Ensure the topic is naturally integrated into the narrative. | |
### **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:** | |
- **No menciones directamente {product_type} en el texto**. En su lugar, intégralo de forma sutil y natural en la narrativa. | |
- **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 | |
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...") | |
product_type = st.text_input("Producto o Servicio:", placeholder="Ejemplo: Curso de marketing digital...") | |
# 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, product_type | |
) | |
st.subheader("Contenido generado:") | |
st.write(response) |