JeCabrera commited on
Commit
522d135
·
verified ·
1 Parent(s): a988be6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -41
app.py CHANGED
@@ -7,24 +7,100 @@ load_dotenv()
7
 
8
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
9
 
10
- # Función para obtener respuesta del modelo Gemini
11
- def get_gemini_response(target_audience, product, action, mood, length):
12
  model = genai.GenerativeModel("gemini-1.5-flash")
13
-
14
- # Crear el prompt para el modelo
15
  full_prompt = f"""
16
- 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).
17
- 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}.
18
- The story should have {length} words, with a {mood} tone. Here are the details:
19
- 1. Problema: Describe a specific problem that keeps the {target_audience} awake at night.
20
- 2. Agitación: Amplify the emotional and practical consequences of this problem.
21
- 3. Solución: Highlight how the product '{product}' solves this problem and improves their life.
22
- 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.
23
-
24
- Write a cohesive, engaging, and emotionally resonant narrative tailored to connect with the {target_audience}.
25
- """
26
  response = model.generate_content([full_prompt])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  if response and response.parts:
29
  text = response.parts[0].text
30
  return text.strip()
@@ -32,33 +108,13 @@ Write a cohesive, engaging, and emotionally resonant narrative tailored to conne
32
  raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
33
 
34
  # Inicializar la aplicación Streamlit
35
- st.set_page_config(page_title="Generador P.A.S.A.", page_icon=":pencil:", layout="wide")
36
 
37
- st.markdown("<h1 style='text-align: center;'>Generador de Historias P.A.S.A.</h1>", unsafe_allow_html=True)
38
  st.markdown("<h3 style='text-align: center;'>Crea historias persuasivas con inteligencia artificial, diseñadas para conectar emocionalmente con tu audiencia.</h3>", unsafe_allow_html=True)
39
 
40
- # CSS personalizado para el botón
41
- st.markdown("""
42
- <style>
43
- div.stButton > button {
44
- background-color: #FFCC00;
45
- color: black;
46
- width: 90%;
47
- height: 60px;
48
- font-weight: bold;
49
- font-size: 22px;
50
- text-transform: uppercase;
51
- border: 1px solid #000000;
52
- border-radius: 8px;
53
- display: block;
54
- margin: 0 auto;
55
- }
56
- div.stButton > button:hover {
57
- background-color: #FFD700;
58
- color: black;
59
- }
60
- </style>
61
- """, unsafe_allow_html=True)
62
 
63
  # Crear las columnas para el diseño (40% para la izquierda, 60% para la derecha)
64
  col1, col2 = st.columns([2, 3])
@@ -74,6 +130,9 @@ with col1:
74
  mood = st.selectbox("Tono de la historia:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
75
  length = st.slider("Longitud de la historia (palabras):", min_value=50, max_value=200, value=150, step=10)
76
 
 
 
 
77
  # Botón para generar contenido
78
  submit = st.button("Generar mi historia")
79
 
@@ -82,9 +141,20 @@ with col2:
82
  if submit:
83
  if target_audience and product and action:
84
  try:
85
- response = get_gemini_response(target_audience, product, action, mood, length)
86
- st.subheader("Historia generada:")
87
- st.write(response)
 
 
 
 
 
 
 
 
 
 
 
88
  except ValueError as e:
89
  st.error(f"Error: {str(e)}")
90
  else:
 
7
 
8
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
9
 
10
+ # Función para obtener respuesta del modelo Gemini (P.A.S.A)
11
+ def get_pasa_response(target_audience, product, action, mood, length):
12
  model = genai.GenerativeModel("gemini-1.5-flash")
 
 
13
  full_prompt = f"""
14
+ 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).
15
+ 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}.
16
+ The story should have {length} words, with a {mood} tone. Here are the details:
17
+ 1. Problema: Describe a specific problem that keeps the {target_audience} awake at night.
18
+ 2. Agitación: Amplify the emotional and practical consequences of this problem.
19
+ 3. Solución: Highlight how the product '{product}' solves this problem and improves their life.
20
+ 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.
21
+ Write a cohesive, engaging, and emotionally resonant narrative tailored to connect with the {target_audience}.
22
+ """
 
23
  response = model.generate_content([full_prompt])
24
+ if response and response.parts:
25
+ text = response.parts[0].text
26
+ return text.strip()
27
+ else:
28
+ raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
29
+
30
+ # Función para obtener respuesta del modelo Gemini (A.D.P.)
31
+ def get_adp_response(target_audience, product, action, mood, length):
32
+ model = genai.GenerativeModel("gemini-1.5-flash")
33
+ full_prompt = f"""
34
+ You are a skilled copywriter and storyteller. Create a persuasive story in Spanish following the A.D.P. formula (Antes, Después, Puente).
35
+ 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}.
36
+ The story should have {length} words, with a {mood} tone. Here are the details:
37
+ 1. **Antes**: Describe the current problem or frustration that the {target_audience} is facing. Reflect on their daily struggles, fears, and obstacles. For example, you can show how they may feel like their efforts are going unnoticed, creating a sense of frustration or helplessness. Think about these questions:
38
+ - What frustrations, fears, or problems is your audience facing?
39
+ - What is preventing them from achieving their goals?
40
+ - How does it feel to live with this problem?
41
+ Example: "Pasas horas escribiendo contenido, pero al final sientes que nadie lo lee o conecta contigo. Es como gritar en un desierto, esperando que alguien escuche."
42
+
43
+ 2. **Después**: Now, paint a picture of the ideal scenario where the problem is resolved. Show how life would be improved, focusing on the benefits your audience would experience. Integrate questions like:
44
+ - How would life be for your audience if the problem was solved?
45
+ - What specific benefits would they gain?
46
+ - What positive emotions would they feel?
47
+ Example: "Ahora imagina que cada vez que publicas una historia, tu audiencia reacciona, comenta y comparte. Tus mensajes se llenan de prospectos interesados, y tus ventas crecen sin sentir que estás forzando nada."
48
+
49
+ 3. **Puente**: Connect the "Antes" and "Después" by presenting the product '{product}' as the solution. Explain how this product bridges the gap between the frustration and the ideal outcome, and how it can improve their situation. The solution should feel logical and accessible. Think about these questions:
50
+ - How does your solution specifically resolve the problem?
51
+ - What makes your solution unique or effective?
52
+ - What simple steps should the reader take to achieve this transformation?
53
+ At the end, adapt the provided call-to-action '{action}' to encourage the reader to take immediate action, emphasizing that this is the logical next step to achieve the benefits and desired transformation.
54
+ Example: "La clave está en aprender a contar historias que conecten emocionalmente con tu audiencia. Con la fórmula A.D.P., puedes guiar a tus lectores desde su frustración actual hasta el resultado que desean. Hoy te enseñaré exactamente cómo hacerlo en mi clase en vivo a las 05:00 pm."
55
 
56
+ Write a cohesive, engaging, and emotionally resonant narrative tailored to connect with the {target_audience}.
57
+ """
58
+ response = model.generate_content([full_prompt])
59
+ if response and response.parts:
60
+ text = response.parts[0].text
61
+ return text.strip()
62
+ else:
63
+ raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
64
+
65
+ # Función para obtener respuesta del modelo Gemini (G.H.A.)
66
+ def get_gha_response(target_audience, product, action, mood, length, story_topic):
67
+ model = genai.GenerativeModel("gemini-1.5-flash")
68
+ full_prompt = f"""
69
+ You are a skilled copywriter and storyteller. Create a persuasive story in Spanish following the G.H.A. formula (Gancho, Historia, Acción).
70
+ 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}.
71
+ The story should have {length} words, with a {mood} tone. Here are the details:
72
+
73
+ 1. **Gancho**: Start with an attention-grabbing hook that immediately captures the {target_audience}'s interest. It can be a question, a surprising fact, or a statement that challenges their beliefs. Some key elements to consider are:
74
+ - What surprising or intriguing thing can you ask or say that makes your audience think?
75
+ - What belief can you challenge or what mistake can you highlight to grab their attention?
76
+ - Example: "¿Qué pasaría si tus fracasos fueran la clave para tus mayores éxitos?"
77
+ - Example: "Lo que nadie te dice: los errores venden más que los aciertos."
78
+ - Example: "¿Recuerdas tu peor fracaso? Es justo lo que necesitas para conectar con tu audiencia."
79
+
80
+ 2. **Historia**: Tell an engaging and emotional story that resonates with the {target_audience}. This can be a personal experience, a fictional story, a movie, a fable, or any narrative that interests the reader and connects with their situation. It should have a meaningful lesson or takeaway. Consider the following questions to craft the story:
81
+ - ¿Cuál era tu situación inicial?
82
+ - ¿Qué problema o conflicto surgió?
83
+ - ¿Cómo te sentiste ante ese problema y qué aprendiste?
84
+ - ¿Qué hiciste para resolverlo o qué aprendiste?
85
+ - ¿Cuál fue el resultado positivo o la lección que aprendiste?
86
+ You can use a personal experience, a movie scene, a fictional character, or even create an imaginative story that resonates with the audience. Example:
87
+ "Era mi primera venta importante y estaba emocionado. El día había llegado, y con él, mi gran oportunidad. Había preparado todo con tanto esmero que casi podía sentir el éxito en el aire. Pero cuando llegó el momento… mi cliente no apareció. Me quedé allí, solo, mirando la pantalla, sintiendo una presión en el pecho. ¿Qué había hecho mal? La duda me invadió, y por un momento, sentí que todo había sido en vano. Me costó entenderlo, pero finalmente lo vi: mi mensaje no resonaba con sus necesidades, no estaba hablando su idioma. Decidí cambiar el enfoque. Ya no quise seguir ocultando mis fracasos. Empecé a ser más honesto, a compartir mis inseguridades y mis aprendizajes, a mostrar que detrás de los resultados, había un ser humano que también había caído y se había levantado. Desde ese día, mis ventas mejoraron, pero lo más importante es que comencé a conectar de verdad con las personas. Ahora sé que la autenticidad y la vulnerabilidad son las claves para generar confianza. Y eso lo cambio todo."
88
+
89
+ 3. **Acción**: Conclude with a strong and motivating call-to-action, linking the story's lesson with a step that the reader can take immediately. Consider these questions to craft the action:
90
+ - What can your audience do right now to achieve similar results?
91
+ - How can they benefit by following the steps you learned in your story?
92
+ - What makes the action you're suggesting the logical next step?
93
+ - Example: "Lo que aprendí es que ser honesto en tus historias conecta más con la gente, y tú también puedes lograrlo si compartes tus experiencias reales. Si quieres saber cómo hacerlo, únete a mi clase en vivo hoy a las 05:00 pm."
94
+ You may adapt this phrase in a natural way to ensure the message flows smoothly and doesn't sound repetitive.
95
+
96
+ 4. **Producto**: Use the product '{product}' as part of the solution in the story. Explain how it will help solve the problem your target audience is facing.
97
+ 5. **Llamado a la Acción**: Create a clear and compelling call to action that motivates the {target_audience} to take immediate action based on the lesson from the story. Use the provided action '{action}' but make it sound natural in the context of the story.
98
+ 6. **Público Objetivo**: Write the story specifically for the {target_audience}. Consider their needs, pain points, and aspirations while crafting the story.
99
+ 7. **De qué quieres que trate la historia**: Please explain what you would like the story to focus on. It could be a personal experience, a movie, a fictional character, or anything that resonates with your audience's situation. The key is that it should grab their attention and connect emotionally with them.
100
+
101
+ Write a cohesive, engaging, and emotionally resonant narrative tailored to connect with the {target_audience}.
102
+ """
103
+ response = model.generate_content([full_prompt])
104
  if response and response.parts:
105
  text = response.parts[0].text
106
  return text.strip()
 
108
  raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
109
 
110
  # Inicializar la aplicación Streamlit
111
+ st.set_page_config(page_title="Generador de Historias", page_icon=":pencil:", layout="wide")
112
 
113
+ st.markdown("<h1 style='text-align: center;'>Generador de Historias</h1>", unsafe_allow_html=True)
114
  st.markdown("<h3 style='text-align: center;'>Crea historias persuasivas con inteligencia artificial, diseñadas para conectar emocionalmente con tu audiencia.</h3>", unsafe_allow_html=True)
115
 
116
+ # Crear el selector para elegir la fórmula
117
+ formula = st.radio("Selecciona la fórmula para generar tu historia:", ["P.A.S.A.", "A.D.P.", "G.H.A."])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  # Crear las columnas para el diseño (40% para la izquierda, 60% para la derecha)
120
  col1, col2 = st.columns([2, 3])
 
130
  mood = st.selectbox("Tono de la historia:", ["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Romántico"])
131
  length = st.slider("Longitud de la historia (palabras):", min_value=50, max_value=200, value=150, step=10)
132
 
133
+ if formula == "G.H.A.":
134
+ 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.).")
135
+
136
  # Botón para generar contenido
137
  submit = st.button("Generar mi historia")
138
 
 
141
  if submit:
142
  if target_audience and product and action:
143
  try:
144
+ if formula == "P.A.S.A.":
145
+ response = get_pasa_response(target_audience, product, action, mood, length)
146
+ elif formula == "A.D.P.":
147
+ response = get_adp_response(target_audience, product, action, mood, length)
148
+ elif formula == "G.H.A.":
149
+ if story_topic:
150
+ response = get_gha_response(target_audience, product, action, mood, length, story_topic)
151
+ else:
152
+ st.error("Por favor, completa todos los campos requeridos para la fórmula G.H.A.")
153
+ response = ""
154
+
155
+ if response:
156
+ st.subheader("Historia generada:")
157
+ st.write(response)
158
  except ValueError as e:
159
  st.error(f"Error: {str(e)}")
160
  else: