JeCabrera commited on
Commit
296ffff
·
verified ·
1 Parent(s): c048218

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -21
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # Código actualizado con selección de tipos de encabezados
2
 
3
  from dotenv import load_dotenv
4
  import streamlit as st
@@ -15,7 +15,7 @@ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
15
  # Función para obtener una mención del producto de manera probabilística
16
  def get_random_product_mention():
17
  mentions = ["Directa", "Indirecta", "Metafórica"]
18
- probabilities = [0.34, 0.33, 0.33]
19
  return random.choices(mentions, probabilities)[0]
20
 
21
  # Crear la instrucción de mención basada en la opción seleccionada
@@ -84,24 +84,23 @@ def generate_headlines(number_of_headlines, target_audience, product, temperatur
84
  # Crear la configuración del modelo
85
  generation_config = {
86
  "temperature": temperature,
87
- "top_p": 0.85,
88
- "top_k": 128,
89
- "max_output_tokens": 2048,
90
  "response_mime_type": "text/plain",
91
  }
92
 
93
  model = genai.GenerativeModel(
94
  model_name="gemini-1.5-flash",
95
  generation_config=generation_config,
96
- system_instruction="You are a world-class copywriter, with expertise in crafting hooks, headlines, and subject lines that immediately capture the reader's attention, prompting them to open the email or continue reading. Your skill lies in deeply understanding the emotions, desires, and challenges of a specific audience. You are also an expert in creating benefits that connect symptoms with problems, allowing you to design personalized strategies that resonate and motivate action. You know how to use proven structures to attract your target audience, generating interest and creating a powerful connection. Your task is to generate unusual, creative, and fascinating subject lines or headlines that spark curiosity and encourage the reader to engage further. Respond in Spanish and use a numbered list format. Important: Only answer with subject lines, never include explanations or categories.",
97
  )
98
 
99
- # Crear un mensaje para el modelo que incluye tipos específicos
100
- selected_types = random.sample(selected_types, min(number_of_headlines, len(selected_types)))
101
  headlines_instruction = (
102
  f"Tu tarea es crear {number_of_headlines} ganchos o encabezados titulares llamativos diseñados para {target_audience} "
103
  f"con el fin de generar interés en {product}. Usa la siguiente mención: {mention_instruction}. "
104
- "Asegúrate de utilizar los siguientes tipos de titulares: " + ", ".join(selected_types) + "."
105
  )
106
 
107
  chat_session = model.start_chat(
@@ -113,8 +112,8 @@ def generate_headlines(number_of_headlines, target_audience, product, temperatur
113
  ]
114
  )
115
 
116
- response = chat_session.send_message("Genera los titulares")
117
- return response.text
118
 
119
  # Configurar la interfaz de usuario con Streamlit
120
  st.set_page_config(page_title="Enchanted Hooks", layout="wide")
@@ -147,7 +146,7 @@ st.markdown("""
147
  """, unsafe_allow_html=True)
148
 
149
  # Crear columnas
150
- col1, col2 = st.columns([1, 2])
151
 
152
  # Columnas de entrada
153
  with col1:
@@ -155,13 +154,13 @@ with col1:
155
  product = st.text_input("¿Qué producto tienes en mente?", placeholder="Ejemplo: Curso de Inglés")
156
  number_of_headlines = st.selectbox("Número de Titulares", options=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], index=4)
157
 
158
- # Crear acordión para la creatividad y selección de tipos
159
  with st.expander("Personaliza tus titulares"):
160
  temperature = st.slider("Creatividad", min_value=0.0, max_value=1.0, value=0.5, step=0.1)
161
- selected_headline_types = st.multiselect(
162
- "Selecciona los tipos de encabezados que deseas generar:",
163
  options=list(headline_types.keys()),
164
- default=list(headline_types.keys())
165
  )
166
 
167
  # Botón de enviar
@@ -169,12 +168,10 @@ with col1:
169
 
170
  # Mostrar los titulares generados
171
  if submit:
172
- if target_audience and product:
173
  try:
174
  # Obtener la respuesta del modelo
175
- generated_headlines = generate_headlines(
176
- number_of_headlines, target_audience, product, temperature, selected_headline_types
177
- )
178
  col2.markdown(f"""
179
  <div style="border: 1px solid #000000; padding: 5px; border-radius: 8px; background-color: #ffffff;">
180
  <h4>Observa la magia en acción:</h4>
@@ -184,4 +181,4 @@ if submit:
184
  except ValueError as e:
185
  col2.error(f"Error: {str(e)}")
186
  else:
187
- col2.error("Por favor, proporciona el público objetivo y el producto.")
 
1
+ # Código actualizado para incluir selección de tipos de encabezados en el acordeón
2
 
3
  from dotenv import load_dotenv
4
  import streamlit as st
 
15
  # Función para obtener una mención del producto de manera probabilística
16
  def get_random_product_mention():
17
  mentions = ["Directa", "Indirecta", "Metafórica"]
18
+ probabilities = [0.34, 0.33, 0.33]
19
  return random.choices(mentions, probabilities)[0]
20
 
21
  # Crear la instrucción de mención basada en la opción seleccionada
 
84
  # Crear la configuración del modelo
85
  generation_config = {
86
  "temperature": temperature,
87
+ "top_p": 0.85, # Considerar un poco menos de palabras probables
88
+ "top_k": 128, # Aumentar las palabras candidatas para más variedad
89
+ "max_output_tokens": 2048, # Mantenerlo igual, pero puedes aumentar si deseas más detalle
90
  "response_mime_type": "text/plain",
91
  }
92
 
93
  model = genai.GenerativeModel(
94
  model_name="gemini-1.5-flash",
95
  generation_config=generation_config,
96
+ system_instruction="You are a world-class copywriter, with expertise in crafting hooks, headlines, and subject lines that immediately capture the reader's attention, prompting them to open the email or continue reading. Your skill lies in deeply understanding the emotions, desires, and challenges of a specific audience. You are also an expert in creating benefits that connect symptoms with problems, allowing you to design personalized strategies that resonate and motivate action. You know how to use proven structures to attract your target audience, generating interest and creating a powerful connection. Your task is to generate unusual, creative, and fascinating subject lines or headlines that spark curiosity and encourage the reader to engage further. Respond in Spanish and use a numbered list format. Important: Only answer with subject lines, never include explanations or categories, like this: 'La leyenda del padre soltero: Dice que nunca hay tiempo suficiente. El yoga te enseña a usar mejor el tiempo que tienes, incluso cuando te parece imposible (este bullet es curioso).'"
97
  )
98
 
99
+ # Crear un mensaje para el modelo que incluye tipos específicos, pero no los menciona en la salida
 
100
  headlines_instruction = (
101
  f"Tu tarea es crear {number_of_headlines} ganchos o encabezados titulares llamativos diseñados para {target_audience} "
102
  f"con el fin de generar interés en {product}. Usa la siguiente mención: {mention_instruction}. "
103
+ f"Asegúrate de utilizar los siguientes tipos de titulares: {', '.join(selected_types)}."
104
  )
105
 
106
  chat_session = model.start_chat(
 
112
  ]
113
  )
114
 
115
+ response = chat_session.send_message("Genera los titulares") # Enviar mensaje para obtener la respuesta
116
+ return response.text # Regresar la respuesta directamente
117
 
118
  # Configurar la interfaz de usuario con Streamlit
119
  st.set_page_config(page_title="Enchanted Hooks", layout="wide")
 
146
  """, unsafe_allow_html=True)
147
 
148
  # Crear columnas
149
+ col1, col2 = st.columns([1, 2])
150
 
151
  # Columnas de entrada
152
  with col1:
 
154
  product = st.text_input("¿Qué producto tienes en mente?", placeholder="Ejemplo: Curso de Inglés")
155
  number_of_headlines = st.selectbox("Número de Titulares", options=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], index=4)
156
 
157
+ # Crear acordión para la creatividad
158
  with st.expander("Personaliza tus titulares"):
159
  temperature = st.slider("Creatividad", min_value=0.0, max_value=1.0, value=0.5, step=0.1)
160
+ selected_types = st.multiselect(
161
+ "Elige los tipos de encabezados que deseas incluir",
162
  options=list(headline_types.keys()),
163
+ default=["pregunta", "historia"]
164
  )
165
 
166
  # Botón de enviar
 
168
 
169
  # Mostrar los titulares generados
170
  if submit:
171
+ if target_audience and product and selected_types:
172
  try:
173
  # Obtener la respuesta del modelo
174
+ generated_headlines = generate_headlines(number_of_headlines, target_audience, product, temperature, selected_types)
 
 
175
  col2.markdown(f"""
176
  <div style="border: 1px solid #000000; padding: 5px; border-radius: 8px; background-color: #ffffff;">
177
  <h4>Observa la magia en acción:</h4>
 
181
  except ValueError as e:
182
  col2.error(f"Error: {str(e)}")
183
  else:
184
+ col2.error("Por favor, proporciona el público objetivo, el producto y selecciona al menos un tipo de encabezado.")