JeCabrera's picture
Update app.py
24eb247 verified
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
import random
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Funci贸n para obtener una menci贸n del producto de manera probabil铆stica
def get_random_product_mention():
mentions = ["Directa", "Indirecta", "Metaf贸rica"]
probabilities = [0.30, 0.35, 0.35]
return random.choices(mentions, probabilities)[0]
# Crear la instrucci贸n de menci贸n basada en la opci贸n seleccionada
def get_mention_instruction(product_mention, product):
if product_mention == "Directa":
return f"""
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.
"""
elif product_mention == "Indirecta":
return f"""
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.
"""
elif product_mention == "Metaf贸rica":
return f"""
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.
"""
return ""
# Funci贸n para obtener la f贸rmula de copywriting seleccionada
def get_formula_instruction(formula, product):
if formula == "If/Then":
return f"""
Write the opening paragraph using the 'If/Then' structure. Start by presenting a problem or goal the reader might have, and then clearly explain how the product '{product}' can solve it. The 'If/Then' logic is based on a direct connection between the reader's desire (the 'If') and the solution you're offering (the 'Then'). This structure taps into a basic belief system that reinforces the idea that the promised benefit is achievable if the initial condition is met.
Here are some variations of the 'If/Then' structure that you can use:
1. Curious: "If you've ever wondered why ice cream tastes better when you eat it with a metal spoon, then this psychological trick will surprise you."
2. Emotional: "If you feel like you always give more than you receive in your relationships, then this message can help you change your story."
3. Funny: "If you think slow Wi-Fi is a form of modern-day torture, then you need to read this before throwing your router out the window."
4. Intriguing: "If everyone seems to be successful while you're still looking for your way, then this guide might be exactly what you need to turn things around."
5. Creative: "If you've ever dreamed of writing a letter so powerful it makes your ex cry or convinces a stranger to buy, then here's the formula you've been searching for."
The 'If/Then' approach is highly effective because it connects with pre-existing beliefs or desires in the reader鈥檚 mind. It either reinforces or challenges these beliefs by offering a direct benefit or new perspective.
For example:
- Reinforcing a belief: "If you believe authenticity is the key to connecting with people, then you're closer to writing texts that sell without sounding fake."
- Challenging a belief: "If you think you need to be extroverted to sell more, then you'll be surprised to know that many introverts are actually the best salespeople."
- Showing a benefit: "If you believe spending time with your family is more important than any paycheck, then this system will help you earn more while working less."
- Showing a disadvantage: "If you believe that talent is everything when it comes to success, then you may be underestimating the power of discipline."
- Intriguing and transformative: "If you think you already know everything about how to write to sell, then this forgotten secret could make you rethink everything you thought you knew."
"""
elif formula == "If / Then + Authority":
return f"""
Write the opening paragraph using the 'If/Then' structure but with an authority figure or testimonial for added credibility. Start by presenting a problem or goal the reader might have, then explain how the product '{product}' can solve it, while mentioning an authority figure or expert opinion. The inclusion of authority figures or recognized references increases the impact of your message, making it more persuasive. For example:
"If you want to learn how to write paragraphs that sell, then here are the techniques used by legendary copywriters like Gary Halbert and Eugene Schwartz to captivate millions."
This use of authority validates your claim and makes the reader more likely to trust the solution you're offering.
"""
elif formula == "Sensationalist":
return f"""
Write the opening paragraph using a sensationalist approach. Introduce an unexpected or shocking fact, and link it to the product '{product}' as the solution. The goal is to create curiosity and urgency in the reader's mind.
Context:
Sensationalism works by surprising the reader with an outlandish or shocking statement. It grabs attention instantly and makes the reader want to know more. Use bold, extreme statements that provoke curiosity or astonishment.
Example:
"驴Sab铆as que la mayor铆a de las personas pierden $5,000 al a帽o por no conocer este simple truco financiero? Aqu铆 te cuento c贸mo evitarlo."
By shocking the reader with an unusual claim or fact, you spark curiosity and compel them to keep reading.
"""
elif formula == "Ask a Question":
return f"""
Write the opening paragraph by asking a provocative question related to the reader's problem or goal. After the question, suggest that the product '{product}' holds the answer.
Context:
Asking a question is a powerful way to engage the reader. It immediately invites them to think about their own situation and wonder how your product can provide a solution.
Example:
"驴Sab铆as que el valor a largo plazo de las tarjetas de b茅isbol es mayor que el de las acciones y monedas raras?"
The question makes the reader pause and consider the information they are being offered, creating an interactive and engaging experience.
"""
return ""
# Generar respuesta del modelo
def get_gemini_response(target_audience, product, formula, length, mood, emotionality):
product_mention = get_random_product_mention()
mention_instruction = get_mention_instruction(product_mention, product)
# Obtener la instrucci贸n para la f贸rmula seleccionada
formula_instruction = get_formula_instruction(formula, product)
# Crear el prompt completo
full_prompt = f"""
You are a creative writer skilled in the art of persuasion. The tone of the opening paragraph 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}
Use the following copywriting techniques to write this opening paragraph: {formula_instruction}.
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.
Create an opening paragraph 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.
"""
model_choice = "gemini-1.5-flash"
model = genai.GenerativeModel(model_choice)
response = model.generate_content([full_prompt])
# Comprobar si la respuesta es v谩lida y devolver el texto
if response and response.parts:
return response.parts[0].text
else:
raise ValueError("Lo sentimos, intenta con una combinaci贸n diferente de entradas.")
# Configuraci贸n de la p谩gina de Streamlit
st.set_page_config(page_title="First Line Alchemy", layout="wide")
# Centrar el t铆tulo y el subt铆tulo
st.markdown("<h1 style='text-align: center;'>First Line Alchemy</h1>", unsafe_allow_html=True)
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)
col1, col2 = st.columns([2, 3])
with col1:
target_audience = st.text_input("驴Qui茅n es tu p煤blico objetivo?")
product = st.text_input("驴Qu茅 producto tienes en mente?")
with st.expander("Personaliza tu p谩rrafo de apertura"):
formula = st.selectbox("Selecciona una f贸rmula de copywriting", ["If/Then", "If / Then + Authority", "Sensationalist", "Ask a Question"])
length = st.slider("N煤mero de palabras", min_value=10, max_value=50, value=25)
mood = st.selectbox("Tono de voz", ["Conversacional", "Formal", "Persuasivo"])
emotionality = st.selectbox("Emocionalidad del texto", ["Triste", "Feliz", "Rom谩ntico", "Sorpresa", "Esperanza", "Ira", "Confianza"])
submit = st.button("Generar Texto")
if submit:
if target_audience and product:
try:
generated_text = get_gemini_response(target_audience, product, formula, length, mood, emotionality)
col2.markdown(f"""
<div style="border: 1px solid #000000; padding: 10px; border-radius: 8px; background-color: #ffffff;">
<h4>Tu p谩rrafo de apertura:</h4>
<p>{generated_text}</p>
</div>
""", unsafe_allow_html=True)
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, proporciona el p煤blico objetivo y el producto.")