Spaces:
Sleeping
Sleeping
File size: 13,255 Bytes
91a0d7e a8fd769 5d758ad d51e47b a8fd769 d51e47b 5d758ad afdeed9 5d758ad afdeed9 59b4bb9 2457cc0 59b4bb9 90a2666 59b4bb9 edf5fad 0b38acb 1ff0df4 59b4bb9 ff0dac9 f4e4aff 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 59b4bb9 6cfedcb 16c57a6 2610857 1ff0df4 afdeed9 2457cc0 1ff0df4 59b4bb9 1ff0df4 a8fd769 1ff0df4 d51e47b 1ff0df4 90a2666 8febed4 dc6da68 8febed4 dc6da68 4ee7a48 5aaf0f3 d1a785f 5aaf0f3 d1a785f 5d758ad 6bb7353 f2e2023 dc6da68 f2e2023 f7d0163 f2e2023 d1a785f dc6da68 f2e2023 d1a785f 2c60041 d1a785f 90a2666 485570a 52cc04b 5a2ea4e 485570a d1a785f 2c60041 04f18da |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
from dotenv import load_dotenv
import streamlit as st
import os
import google.generativeai as genai
import random # Nueva importaci贸n para la selecci贸n aleatoria de menci贸n
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.34, 0.33, 0.33]
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. The mention should feel natural and seamlessly integrated into the narrative.
"""
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, 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.
"""
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 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.
"""
return ""
# Funci贸n para obtener una t茅cnica de copywriting de manera aleatoria
def get_random_copywriting_technique():
techniques = [
"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鈥檚 very simple, clear, and powerful. It lets people know what to expect. There鈥檚 also a very interesting belief structure that is built with this combo. If this, then that. It鈥檚 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鈥檚 how you do it.",
"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鈥檒l 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鈥檒l show you why you can do it too starting today.' As you can see, it doesn鈥檛 have as much impact as the version with the gladiators and samurais.",
"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鈥檚 ads started like this: 'My name is Betty Adams, and the first thing you should know about me is... I鈥檓 not a doctor. I鈥檓 also not a nutrition expert. I didn鈥檛 go to college and I don鈥檛 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鈥檓 not a doctor,' 'I鈥檓 not a nutrition expert,' 'I didn鈥檛 go to school,' 'I don鈥檛 have a degree.' These four negative statements strengthen her claim about what she is. Now, this won鈥檛 always work for every sales letter. It will depend on your market and ideal customer. If your market isn鈥檛 skeptical, you don鈥檛 need to use this kind of paragraph.",
"4. Sensationalist: This one is related to the sensational headline. Here鈥檚 where you鈥檇 say something like: 'Let me tell you this strange story about a man who was arrested because he had herpes.' It鈥檚 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.",
"5. Ask a Question: It makes people stop if they鈥檙e 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鈥檚 different and gets them ready to start the journey.",
"6. Micro Openings: This paragraph should be short. Just a few words... so they鈥檒l 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鈥檙e going straight to their mind, to their doubts. One that you can use effectively is: 'Imagine the following:'"
]
return random.sample(techniques, k=random.randint(1, 3)) # Escoge entre 1 y 3 t茅cnicas al azar
# Al crear el prompt completo, incluye el tama帽o y las t茅cnicas seleccionadas
def get_gemini_response(target_audience, product, text_type, length, mood, emotionality):
product_mention = get_random_product_mention()
mention_instruction = get_mention_instruction(product_mention, product) # Agrega esta l铆nea
model_choice = "gemini-1.5-flash" # Modelo predeterminado
model = genai.GenerativeModel(model_choice)
# Obtener t茅cnicas aleatorias
copywriting_techniques = get_random_copywriting_technique()
techniques_text = " ".join(copywriting_techniques)
# Instrucci贸n espec铆fica para el tipo de texto
format_instruction = ""
if text_type == "Historia":
format_instruction = f"""
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.
"""
elif text_type == "Carta de venta":
format_instruction = f"""
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.
"""
elif text_type == "Correo":
format_instruction = f"""
Write a concise but impactful opening paragraph for an email that captures the reader鈥檚 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.
"""
elif text_type == "Landing page":
format_instruction = f"""
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.
"""
# Crear el prompt completo basado en los campos del frontend
full_prompt = f"""
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}
Use the following copywriting techniques to write this opening paragraph: {techniques_text}.
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 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.
"""
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.")
# Inicializar la aplicaci贸n Streamlit
st.set_page_config(page_title="First Line Alchemy", layout="wide")
# Inicializar el estado de la expansi贸n del acorde贸n
if "accordion_expanded" not in st.session_state:
st.session_state["accordion_expanded"] = False # Por defecto est谩 cerrado
# Definir una funci贸n para manejar el cambio de estado del acorde贸n
def toggle_accordion():
st.session_state["accordion_expanded"] = not st.session_state["accordion_expanded"]
# 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)
# A帽adir CSS personalizado para el bot贸n
st.markdown("""
<style>
div.stButton > button {
background-color: #FFCC00; /* Color llamativo */
color: black; /* Texto en negro */
width: 90%;
height: 60px;
font-weight: bold;
font-size: 22px; /* Tama帽o m谩s grande */
text-transform: uppercase; /* Texto en may煤sculas */
border: 1px solid #000000; /* Borde negro de 1px */
border-radius: 8px;
display: block;
margin: 0 auto; /* Centramos el bot贸n */
}
div.stButton > button:hover {
background-color: #FFD700; /* Color al pasar el mouse */
color: black; /* Texto sigue en negro */
}
</style>
""", unsafe_allow_html=True)
# Create two columns for the layout (40% and 60%)
col1, col2 = st.columns([2, 3]) # 2 + 3 = 5 parts in total
with col1:
# Create input fields
target_audience = st.text_input("驴Qui茅n es tu p煤blico objetivo?")
product = st.text_input("驴Qu茅 producto tienes en mente?")
# Accordion for customizing the opening paragraph, controlled by session_state
with st.expander("Personaliza tu p谩rrafo de apertura", expanded=st.session_state["accordion_expanded"]):
text_type = st.selectbox("Tipo de texto", ["Historia", "Carta de venta", "Correo", "Landing page"])
length = st.slider("N煤mero de palabras", min_value=50, max_value=100, value=50)
mood = st.selectbox("Tono de voz", ["Conversacional", "Formal", "Persuasivo"])
emotionality = st.selectbox("Emocionalidad del texto", ["Triste", "Feliz", "Horror", "Comedia", "Rom谩ntico", "Sorpresa", "Desesperaci贸n", "Esperanza", "Ira", "Confianza"])
# Submit button
submit = st.button("Escribir mi Texto", on_click=toggle_accordion)
# Button to generate text (outside the accordion)
if submit:
if target_audience and product: # Check if target audience and product are provided
try:
# Get the response from the model
generated_text = get_gemini_response(target_audience, product, text_type, length, mood, emotionality)
col2.markdown("""
<div style="border: 1px solid #000000; padding: 5px; border-radius: 8px; background-color: #ffffff;">
<h4>Aqu铆 est谩 tu p谩rrafo de apertura:</h4>
<p>{}</p>
</div>
""".format(generated_text), unsafe_allow_html=True) # Update with generated text
except ValueError as e:
col2.error(f"Error: {str(e)}")
else:
col2.error("Por favor, proporciona el p煤blico objetivo y el producto.")
|