JeCabrera's picture
Update app.py
ae4c2eb verified
raw
history blame
10.5 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 (P.A.S.A)
def get_pasa_response(target_audience, product, action, mood, length):
model = genai.GenerativeModel("gemini-1.5-flash")
full_prompt = f"""
You are a skilled copywriter and storyteller. Create a persuasive story in Spanish following the P.A.S.A. formula (Problema, Agitación, Solución, Acción).
Do not explicitly label or explain each section (Problema, Agitación, Solución, Acción). Instead, weave these elements naturally into a cohesive, flowing narrative that emotionally connects with the {target_audience}.
The story should have {length} words, with a {mood} tone. Here are the details:
1. Problema: Describe a specific problem that keeps the {target_audience} awake at night.
2. Agitación: Amplify the emotional and practical consequences of this problem.
3. Solución: Highlight how the product '{product}' solves this problem and improves their life.
4. Acción: Adapt the provided call-to-action '{action}' and craft it in a way that motivates the reader to take immediate steps, using compelling language that encourages them to act.
Write a cohesive, engaging, and emotionally resonant narrative tailored to connect with the {target_audience}.
"""
response = model.generate_content([full_prompt])
if response and response.parts:
text = response.parts[0].text
return text.strip()
else:
raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
# Función para obtener respuesta del modelo Gemini (A.D.P.)
def get_adp_response(target_audience, product, action, mood, length):
model = genai.GenerativeModel("gemini-1.5-flash")
full_prompt = f"""
You are a skilled copywriter and storyteller. Create a creative and persuasive story in Spanish following the A.D.P. formula (Antes, Después, Puente).
Do not explicitly label or explain each section (Antes, Después, Puente). Instead, weave these elements naturally into a cohesive, flowing narrative that emotionally connects with the {target_audience}.
The story should always be written in the second person (using 'tú') and should have unexpected twists to engage the {target_audience}.
The story should have {length} words, with a {mood} tone. Here are the details:
1. Antes: Describe the current problem and frustrations that you {target_audience} are facing. Create an immersive situation where the reader can recognize themselves.
2. Después: Paint a desired scenario where the problem of {target_audience} is solved and the benefits are clearly evident. Use a surprising twist to show how life can change.
3. Puente: Introduce your solution '{product}' as the logical bridge between your frustration and the desired result. Make sure to emphasize the transformation you’ll experience if you take action '{action}'. Conclude with a compelling call to action '{action}' inviting the reader to take immediate steps to improve their situation.
Ensure that the story has a creative flow with unexpected turns and keeps the reader hooked, motivating them to act at the end.
Write a cohesive, engaging, and emotionally resonant narrative tailored to connect deeply with you, the {target_audience}.
"""
response = model.generate_content([full_prompt])
if response and response.parts:
text = response.parts[0].text
return text.strip()
else:
raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
# Función para obtener respuesta del modelo Gemini (G.H.A.)
def get_gha_response(target_audience, product, action, mood, length, story_topic):
model = genai.GenerativeModel("gemini-1.5-flash")
full_prompt = f"""
You are a skilled copywriter and storyteller. Create a persuasive story in Spanish following the G.H.A. formula (Gancho, Historia, Acción).
Do not explicitly label or explain each section (Gancho, Historia, Acción). Instead, weave these elements naturally into a cohesive, flowing narrative that emotionally connects with the {target_audience}.
The story should have {length} words, with a {mood} tone. Here are the details:
1. **Gancho**: Begin with a hook that immediately grabs the attention of the {target_audience}. It could be a provocative question, an unexpected fact, or a statement that challenges their beliefs or assumptions. The goal is to create curiosity and make them want to read more.
2. **Historia**: Tell a personal or fictional story based on the following story topic: "{story_topic}". Incorporate the following elements seamlessly into the narrative:
- What was the initial situation or challenge the protagonist faced?
- What conflict or problem arose and how did it affect them emotionally?
- How did they feel and what did they learn from that experience?
- What action did they take to resolve the situation or what did they learn in the process?
- What was the outcome or lesson learned that could apply to the {target_audience}'s life?
Make sure the story is engaging and retains the attention of the reader while providing a meaningful takeaway that resonates with their own struggles or aspirations.
3. **Acción**: Conclude with a natural call to action '{action}' that invites the reader to take the next step, based on the lesson or transformation in the story. Tie the benefits of the {product} into the CTA, emphasizing how taking action will help them achieve similar results.
For example:
- "Lo que aprendí es que la vulnerabilidad te conecta con los demás, y tú también puedes lograrlo si compartes tus experiencias reales. Si deseas experimentar la calma y claridad mental que trae la práctica del yoga, únete a nuestro webinar y descubre cómo el yoga puede ayudarte a gestionar el estrés y mejorar tu bienestar."
- "Tras superar mi fracaso, entendí que la mente y el cuerpo están más conectados de lo que pensaba, y tú también puedes descubrir ese equilibrio. Si quieres sentirte más tranquilo, centrado y en control, participa en nuestro webinar de yoga y transforma tu vida."
- "Lo que descubrí es que la práctica constante te lleva a un cambio profundo, y tú también puedes lograrlo si decides hacer algo por ti mismo. Únete a nuestra sesión de yoga y aprende cómo liberarte de tensiones, aumentar tu flexibilidad y encontrar la paz interior."
Empower the reader by showing them how the benefits of the {product} can lead to a transformation. The call to action should be clear, inviting them to take immediate steps based on the benefits of the {product}.
Ensure that the entire narrative flows smoothly, making the call to action feel like a natural next step after the story, rather than a forced conclusion.
"""
response = model.generate_content([full_prompt])
if response and response.parts:
text = response.parts[0].text
return text.strip()
else:
raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
# Inicializar la aplicación Streamlit
st.set_page_config(page_title="Generador de Historias", page_icon=":pencil:", layout="wide")
# Título y subtítulo
st.markdown("<h1 style='text-align: center;'>Story Genius Maker</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center;'>Teje historias inolvidables en segundos, guiado por la magia de la inteligencia artificial que da vida a tus ideas en relatos cautivadores.</h3>", unsafe_allow_html=True)
# Acordeón para elegir la fórmula
with st.expander("Selecciona la fórmula para generar tu historia"):
formula = st.radio("Selecciona la fórmula para generar tu historia:", ["P.A.S.A.", "A.D.P.", "G.H.A."])
# Crear las columnas para el diseño (40% para la izquierda, 60% para la derecha)
col1, col2 = st.columns([2, 3])
# Cambiar el comportamiento del slider cuando se seleccione "G.H.A."
with col1:
target_audience = st.text_input("Público objetivo", placeholder="¿A quién está dirigido tu mensaje?")
product = st.text_input("Producto/Servicio", placeholder="¿Qué estás ofreciendo?")
action = st.text_area("Llamado a la acción", placeholder="¿Qué acción específica debe tomar tu audiencia?")
# Personalización adicional
with st.expander("Personaliza tu historia"):
mood = st.selectbox("Tono de la historia:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
# Ajustar el slider según la fórmula seleccionada
if formula == "G.H.A.":
length = st.slider("Longitud de la historia (palabras):", min_value=50, max_value=200, value=150, step=10)
else:
length = st.slider("Longitud de la historia (palabras):", min_value=50, max_value=150, value=100, step=10)
if formula == "G.H.A.":
story_topic = st.text_area("De qué quieres que trate la historia", placeholder="Explica si hay algo específico sobre lo que te gustaría contar (puede ser una vivencia personal, película, cuento, personaje ficticio, etc.).")
# Botón para generar contenido
submit = st.button("Generar mi historia")
# Mostrar el contenido generado en la columna derecha (col2)
with col2:
if submit:
if target_audience and product and action:
try:
if formula == "P.A.S.A.":
response = get_pasa_response(target_audience, product, action, mood, length)
elif formula == "A.D.P.":
response = get_adp_response(target_audience, product, action, mood, length)
elif formula == "G.H.A.":
if story_topic:
response = get_gha_response(target_audience, product, action, mood, length, story_topic)
else:
st.error("Por favor, completa todos los campos requeridos para la fórmula G.H.A.")
response = ""
if response:
st.subheader("Historia generada:")
st.write(response)
except ValueError as e:
st.error(f"Error: {str(e)}")
else:
st.error("Por favor, completa todos los campos requeridos (Público objetivo, Producto y Acción).")