JeCabrera commited on
Commit
74b2613
·
verified ·
1 Parent(s): 15e27a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -95
app.py CHANGED
@@ -2,7 +2,7 @@ from dotenv import load_dotenv
2
  import streamlit as st
3
  import os
4
  import google.generativeai as genai
5
- import random # Nueva importación para la selección aleatoria de mención
6
 
7
  load_dotenv()
8
 
@@ -11,76 +11,57 @@ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
11
  # Función para obtener una mención del producto de manera probabilística
12
  def get_random_product_mention():
13
  mentions = ["Directa", "Indirecta", "Metafórica"]
14
- probabilities = [0.34, 0.33, 0.33]
15
  return random.choices(mentions, probabilities)[0]
16
 
17
  # Crear la instrucción de mención basada en la opción seleccionada
18
  def get_mention_instruction(product_mention, product):
19
  if product_mention == "Directa":
20
  return f"""
21
- Directly introduce the product '{product}' as the clear solution to the problem the reader is facing. Ensure that the product is presented in a way that highlights its key benefits and demonstrates how it directly addresses the issue at hand. The mention should feel natural and seamlessly integrated into the narrative.
22
  """
23
  elif product_mention == "Indirecta":
24
  return f"""
25
- Subtly reference the product '{product}' as a potential solution to the reader's problem without naming it explicitly. Weave the product's core benefits into the description of how the reader can overcome the issue, creating an implicit connection between the solution and the product. Ensure the mention is subtle but clear enough to guide the reader towards the product.
26
  """
27
  elif product_mention == "Metafórica":
28
  return f"""
29
- Introduce the product '{product}' using a metaphor, connecting it symbolically to the solution the reader needs. The metaphor should relate to the problem being discussed and should creatively suggest how the product offers a resolution without explicitly stating its name. The metaphor should evoke the benefits of the product in a memorable and thought-provoking way.
30
  """
31
  return ""
32
 
33
  # Función para obtener una técnica de copywriting de manera aleatoria
34
  def get_random_copywriting_technique():
35
  techniques = [
36
- "1. If/Then: This is one of the most commonly used opening paragraphs. Gary Halbert, one of the most important copywriters of the 20th century, used them in almost every one of his sales letters. It’s very simple, clear, and powerful. It lets people know what to expect. There’s also a very interesting belief structure that is built with this combo. If this, then that. It’s as if they need to meet some kind of prerequisite to get the benefit. An example of this would be: 'If you want to make more than $100,000 a year working just 4 hours a day, then this letter will show you how.' Very simple. If you want that, then here’s how you do it.",
37
- "2. If / Then + Authority: Even more powerful than the 'If / Then' key is the same concept but adding a figure of authority or credibility. For example: 'If you want to know a secret way to become almost invincible in a fight... then here I’ll show you what the gladiators and samurais used to do. And why you can do it too starting today.' One way to notice the power of these opening paragraphs is by removing the authority figure. In this case: the gladiators and samurais. That would change the paragraph to: 'If you want to know a secret way to become almost invincible in a fight... then here I’ll show you why you can do it too starting today.' As you can see, it doesn’t have as much impact as the version with the gladiators and samurais.",
38
- "3. Honesty: Being transparent is one of the best ways to get more customers. It also works with opening paragraphs. For example, one of Gary Halbert’s ads started like this: 'My name is Betty Adams, and the first thing you should know about me is... I’m not a doctor. I’m also not a nutrition expert. I didn’t go to college and I don’t even have a degree. In fact, the only thing I consider myself an expert in is...' And then it went to a subheading where she mentioned how she could help you lose 10 kilos in a very simple way. In this case, you can notice all the negatives she uses: 'I’m not a doctor,' 'I’m not a nutrition expert,' 'I didn’t go to school,' 'I don’t have a degree.' These four negative statements strengthen her claim about what she is. Now, this won’t always work for every sales letter. It will depend on your market and ideal customer. If your market isn’t skeptical, you don’t need to use this kind of paragraph.",
39
- "4. Sensationalist: This one is related to the sensational headline. Here’s where you’d say something like: 'Let me tell you this strange story about a man who was arrested because he had herpes.' It’s sensationalist. And sensationalism sells. It always has and always will. Without a doubt, the paragraph is strange and makes your reader think: 'How was someone arrested for having herpes? What did he do? What happened?' It keeps them hooked, addicted to finding out more. They need to know.",
40
- "5. Ask a Question: It makes people stop if they’re interested. One of the best opening paragraphs is this: 'Did you know that the long-term value of baseball cards is much higher than that of stocks and rare coins?' So when you talk to someone in the finance, investor, or related niches about this topic, they will be interested because it’s different and gets them ready to start the journey.",
41
- "6. Micro Openings: This paragraph should be short. Just a few words... so they’ll read the next one. This is because being brief makes it easy to read. And if you say something that puts your reader in the right mindset, this can be quite powerful. For example, if your product is targeted to a skeptical market, you can use a paragraph like the following: 'I was a total skeptic.' With this, you’re going straight to their mind, to their doubts. One that you can use effectively is: 'Imagine the following:'"
42
  ]
43
- return random.sample(techniques, k=random.randint(1, 3)) # Escoge entre 1 y 3 técnicas al azar
44
 
45
- # Al crear el prompt completo, incluye el tamaño y las técnicas seleccionadas
46
- def get_gemini_response(target_audience, product, text_type, length, mood, emotionality):
47
  product_mention = get_random_product_mention()
48
- mention_instruction = get_mention_instruction(product_mention, product) # Agrega esta línea
49
- model_choice = "gemini-1.5-flash" # Modelo predeterminado
50
-
51
- model = genai.GenerativeModel(model_choice)
52
 
53
  # Obtener técnicas aleatorias
54
  copywriting_techniques = get_random_copywriting_technique()
55
  techniques_text = " ".join(copywriting_techniques)
56
 
57
- # Instrucción específica para el tipo de texto
58
- format_instruction = ""
59
- if text_type == "Historia":
60
- format_instruction = f"""
61
- Write an engaging opening paragraph that introduces a relatable problem your audience is facing. Stir emotions by highlighting the impact of the problem on their life, and create curiosity with hints of a potential solution without revealing everything. The paragraph should be approximately {length} words long to maintain engagement and avoid losing the reader's attention.
62
- """
63
- elif text_type == "Carta de venta":
64
- format_instruction = f"""
65
- Craft a persuasive lead paragraph for a sales letter that quickly identifies a common pain point your reader is experiencing. The paragraph should be around {length} words long and agitate the problem by emphasizing the negative consequences of not addressing it, and tease the possibility of a solution to spark curiosity.
66
- """
67
- elif text_type == "Correo":
68
- format_instruction = f"""
69
- Write a concise but impactful opening paragraph for an email that captures the reader’s attention. The text should be approximately {length} words, addressing a challenge they are likely facing, and leave them intrigued by hinting at a valuable solution that will be revealed if they continue reading.
70
- """
71
- elif text_type == "Landing page":
72
- format_instruction = f"""
73
- Design a compelling first paragraph for a landing page that immediately draws attention to a significant problem your target audience is encountering. The paragraph should be about {length} words long, stirring emotions and enticing them to keep scrolling by subtly suggesting a solution.
74
- """
75
-
76
- # Crear el prompt completo basado en los campos del frontend
77
  full_prompt = f"""
78
- You are a creative writer skilled in the art of persuasion. The tone of the {text_type} should be {mood} and {emotionality} emotionally resonate with a {target_audience}. Evoke feelings of {target_audience} through relatable, real-life situations that reflect their experiences. {mention_instruction} {format_instruction}
79
- Use the following copywriting techniques to write this opening paragraph: {techniques_text}.
80
- Use persuasive techniques to guide the reader towards an intuitive understanding of the product's benefits, focusing on creating a strong emotional connection with the audience.
81
- Create an opening paragraph for a {text_type} of {length} words in Spanish that makes {target_audience} aware they have a problem. Highlight this problem by explaining it with relatable situations tailored to their context, using a natural or conversational tone. The goal of this paragraph is to entice them to keep reading and discover what {product} is about. Use persuasion effectively in every word, mastering advanced techniques.
 
82
  """
83
-
 
 
84
  response = model.generate_content([full_prompt])
85
 
86
  # Comprobar si la respuesta es válida y devolver el texto
@@ -89,74 +70,37 @@ Create an opening paragraph for a {text_type} of {length} words in Spanish that
89
  else:
90
  raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
91
 
92
- # Inicializar la aplicación Streamlit
93
  st.set_page_config(page_title="First Line Alchemy", layout="wide")
94
 
95
- # Inicializar el estado de la expansión del acordeón
96
- if "accordion_expanded" not in st.session_state:
97
- st.session_state["accordion_expanded"] = False # Por defecto está cerrado
98
-
99
- # Definir una función para manejar el cambio de estado del acordeón
100
- def toggle_accordion():
101
- st.session_state["accordion_expanded"] = not st.session_state["accordion_expanded"]
102
-
103
- # Centrar el título y el subtítulo
104
  st.markdown("<h1 style='text-align: center;'>First Line Alchemy</h1>", unsafe_allow_html=True)
105
- st.markdown("<h4 style='text-align: center;'>Experimenta la magia de transformar conceptos ordinarios en líneas de apertura extraordinarias que cautivan la imaginación e inspiran acción.</h4>", unsafe_allow_html=True)
106
-
107
- # Añadir CSS personalizado para el botón
108
- st.markdown("""
109
- <style>
110
- div.stButton > button {
111
- background-color: #FFCC00; /* Color llamativo */
112
- color: black; /* Texto en negro */
113
- width: 90%;
114
- height: 60px;
115
- font-weight: bold;
116
- font-size: 22px; /* Tamaño más grande */
117
- text-transform: uppercase; /* Texto en mayúsculas */
118
- border: 1px solid #000000; /* Borde negro de 1px */
119
- border-radius: 8px;
120
- display: block;
121
- margin: 0 auto; /* Centramos el botón */
122
- }
123
- div.stButton > button:hover {
124
- background-color: #FFD700; /* Color al pasar el mouse */
125
- color: black; /* Texto sigue en negro */
126
- }
127
- </style>
128
- """, unsafe_allow_html=True)
129
 
130
- # Create two columns for the layout (40% and 60%)
131
- col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 parts in total
132
 
133
  with col1:
134
- # Create input fields
135
  target_audience = st.text_input("¿Quién es tu público objetivo?")
136
  product = st.text_input("¿Qué producto tienes en mente?")
137
 
138
- # Accordion for customizing the opening paragraph, controlled by session_state
139
- with st.expander("Personaliza tu párrafo de apertura", expanded=st.session_state["accordion_expanded"]):
140
- text_type = st.selectbox("Tipo de texto", ["Historia", "Carta de venta", "Correo", "Landing page"])
141
  length = st.slider("Número de palabras", min_value=50, max_value=100, value=50)
142
  mood = st.selectbox("Tono de voz", ["Conversacional", "Formal", "Persuasivo"])
143
- emotionality = st.selectbox("Emocionalidad del texto", ["Triste", "Feliz", "Horror", "Comedia", "Romántico", "Sorpresa", "Desesperación", "Esperanza", "Ira", "Confianza"])
144
 
145
- # Submit button
146
- submit = st.button("Escribir mi Texto", on_click=toggle_accordion)
147
 
148
- # Button to generate text (outside the accordion)
149
  if submit:
150
- if target_audience and product: # Check if target audience and product are provided
151
  try:
152
- # Get the response from the model
153
- generated_text = get_gemini_response(target_audience, product, text_type, length, mood, emotionality)
154
- col2.markdown("""
155
- <div style="border: 1px solid #000000; padding: 5px; border-radius: 8px; background-color: #ffffff;">
156
- <h4>Aquí está tu párrafo de apertura:</h4>
157
- <p>{}</p>
158
  </div>
159
- """.format(generated_text), unsafe_allow_html=True) # Update with generated text
160
  except ValueError as e:
161
  col2.error(f"Error: {str(e)}")
162
  else:
 
2
  import streamlit as st
3
  import os
4
  import google.generativeai as genai
5
+ import random
6
 
7
  load_dotenv()
8
 
 
11
  # Función para obtener una mención del producto de manera probabilística
12
  def get_random_product_mention():
13
  mentions = ["Directa", "Indirecta", "Metafórica"]
14
+ probabilities = [0.05, 0.10, 0.85]
15
  return random.choices(mentions, probabilities)[0]
16
 
17
  # Crear la instrucción de mención basada en la opción seleccionada
18
  def get_mention_instruction(product_mention, product):
19
  if product_mention == "Directa":
20
  return f"""
21
+ Directly introduce the product '{product}' as the clear solution to the problem the reader is facing. Ensure that the product is presented in a way that highlights its key benefits and demonstrates how it directly addresses the issue at hand.
22
  """
23
  elif product_mention == "Indirecta":
24
  return f"""
25
+ Subtly reference the product '{product}' as a potential solution to the reader's problem without naming it explicitly. Weave the product's core benefits into the description of how the reader can overcome the issue.
26
  """
27
  elif product_mention == "Metafórica":
28
  return f"""
29
+ Introduce the product '{product}' using a metaphor, connecting it symbolically to the solution the reader needs. The metaphor should creatively suggest how the product offers a resolution without explicitly stating its name.
30
  """
31
  return ""
32
 
33
  # Función para obtener una técnica de copywriting de manera aleatoria
34
  def get_random_copywriting_technique():
35
  techniques = [
36
+ "If/Then: Create a condition and show how it leads to the desired result.",
37
+ "Questions: Pose a question to engage the reader and lead into the solution.",
38
+ "Honesty: Build trust by being transparent about limitations or challenges.",
39
+ "Sensationalist: Use an unusual or shocking statement to hook the reader.",
40
+ "Micro Openings: Use a very short and impactful opening to capture attention.",
41
+ "Authority: Refer to a credible figure or data to reinforce your point."
42
  ]
43
+ return random.sample(techniques, k=random.randint(1, 3))
44
 
45
+ # Generar respuesta del modelo
46
+ def get_gemini_response(target_audience, product, formula, length, mood, emotionality):
47
  product_mention = get_random_product_mention()
48
+ mention_instruction = get_mention_instruction(product_mention, product)
 
 
 
49
 
50
  # Obtener técnicas aleatorias
51
  copywriting_techniques = get_random_copywriting_technique()
52
  techniques_text = " ".join(copywriting_techniques)
53
 
54
+ # Crear el prompt completo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  full_prompt = f"""
56
+ You are a creative writer skilled in the art of persuasion. Write an opening paragraph using the {formula} formula to connect with a {target_audience}.
57
+ The tone should be {mood}, and the emotionality should convey {emotionality}.
58
+ {mention_instruction}
59
+ Use the following copywriting techniques: {techniques_text}.
60
+ The paragraph should be approximately {length} words long and emotionally resonate with the audience, enticing them to continue reading.
61
  """
62
+
63
+ model_choice = "gemini-1.5-flash"
64
+ model = genai.GenerativeModel(model_choice)
65
  response = model.generate_content([full_prompt])
66
 
67
  # Comprobar si la respuesta es válida y devolver el texto
 
70
  else:
71
  raise ValueError("Lo sentimos, intenta con una combinación diferente de entradas.")
72
 
73
+ # Configuración de la página de Streamlit
74
  st.set_page_config(page_title="First Line Alchemy", layout="wide")
75
 
76
+ # Interfaz de usuario
 
 
 
 
 
 
 
 
77
  st.markdown("<h1 style='text-align: center;'>First Line Alchemy</h1>", unsafe_allow_html=True)
78
+ st.markdown("<h4 style='text-align: center;'>Transforma conceptos en líneas que cautivan e inspiran acción.</h4>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
+ col1, col2 = st.columns([2, 3])
 
81
 
82
  with col1:
 
83
  target_audience = st.text_input("¿Quién es tu público objetivo?")
84
  product = st.text_input("¿Qué producto tienes en mente?")
85
 
86
+ with st.expander("Personaliza tu párrafo de apertura"):
87
+ formula = st.selectbox("Selecciona una fórmula de copywriting", ["If/Then", "Questions", "Honesty", "Sensationalist", "Micro Openings", "Authority"])
 
88
  length = st.slider("Número de palabras", min_value=50, max_value=100, value=50)
89
  mood = st.selectbox("Tono de voz", ["Conversacional", "Formal", "Persuasivo"])
90
+ emotionality = st.selectbox("Emocionalidad del texto", ["Triste", "Feliz", "Romántico", "Sorpresa", "Esperanza", "Ira", "Confianza"])
91
 
92
+ submit = st.button("Generar Texto")
 
93
 
 
94
  if submit:
95
+ if target_audience and product:
96
  try:
97
+ generated_text = get_gemini_response(target_audience, product, formula, length, mood, emotionality)
98
+ col2.markdown(f"""
99
+ <div style="border: 1px solid #000000; padding: 10px; border-radius: 8px; background-color: #ffffff;">
100
+ <h4>Tu párrafo de apertura:</h4>
101
+ <p>{generated_text}</p>
 
102
  </div>
103
+ """, unsafe_allow_html=True)
104
  except ValueError as e:
105
  col2.error(f"Error: {str(e)}")
106
  else: