|
from dotenv import load_dotenv |
|
import streamlit as st |
|
import os |
|
import google.generativeai as genai |
|
|
|
load_dotenv() |
|
genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) |
|
|
|
story_formulas = { |
|
"PASA": { |
|
"description": """ |
|
La f贸rmula P.A.S.A. es una de las estructuras m谩s efectivas en copywriting, dise帽ada para crear una conexi贸n emocional profunda que lleva a la acci贸n. |
|
|
|
TEOR脥A: |
|
Esta f贸rmula se basa en la psicolog铆a del dolor y el alivio, siguiendo el principio de que las personas est谩n m谩s motivadas a evitar el dolor que a buscar el placer. |
|
|
|
ESTRUCTURA: |
|
1. Problema: |
|
- Identifica un dolor espec铆fico y real |
|
- Debe ser inmediatamente reconocible por la audiencia |
|
- Se presenta desde la perspectiva del lector |
|
- Usa lenguaje emp谩tico y comprensivo |
|
|
|
2. Agitaci贸n: |
|
- Profundiza en las consecuencias emocionales |
|
- Explora ramificaciones futuras |
|
- Aumenta la tensi贸n psicol贸gica |
|
- Crea un punto de inflexi贸n emocional |
|
|
|
3. Soluci贸n: |
|
- Presenta la respuesta de forma natural |
|
- Enfoca en beneficios transformacionales |
|
- Construye credibilidad gradualmente |
|
- Demuestra el cambio positivo |
|
|
|
4. Acci贸n: |
|
- Propone el siguiente paso l贸gico |
|
- Minimiza la fricci贸n y resistencia |
|
- Crea sentido de urgencia |
|
- Ofrece garant铆as impl铆citas |
|
""", |
|
"examples": [ |
|
{ |
|
"title": "App de Meditaci贸n", |
|
"target": "Profesionales estresados", |
|
"story": """ |
|
El insomnio se hab铆a convertido en su compa帽ero m谩s fiel. Sara miraba el reloj: 3 AM, otra vez. |
|
|
|
Los d铆as se volv铆an borrosos, su concentraci贸n desaparec铆a. Las reuniones importantes se convert铆an en una lucha por mantener los ojos abiertos, mientras su productividad se desplomaba. |
|
|
|
Todo cambi贸 cuando descubri贸 MeditaApp. Sus ejercicios de respiraci贸n guiada y meditaciones nocturnas la ayudaron a encontrar ese interruptor mental que necesitaba para desconectar. |
|
|
|
Descarga MeditaApp hoy y recupera tus noches. Tus primeros 7 d铆as son gratuitos, porque creemos que una noche de buen sue帽o no tiene precio. |
|
""" |
|
}, |
|
{ |
|
"title": "Curso de Finanzas Personales", |
|
"target": "J贸venes profesionales", |
|
"story": """ |
|
Cada notificaci贸n del banco le provocaba un nudo en el est贸mago. Miguel evitaba revisar su cuenta, sabiendo que los n煤meros rojos lo esperaban. |
|
|
|
Las deudas crec铆an mientras sus sue帽os se alejaban. La idea de comprar una casa o empezar un negocio parec铆a cada vez m谩s inalcanzable, y la ansiedad financiera lo consum铆a d铆a y noche. |
|
|
|
Entonces encontr贸 FinanzasMaster. El curso no solo le ense帽贸 a manejar su dinero, sino a construir un futuro financiero s贸lido. En seis meses, elimin贸 sus deudas y comenz贸 a ver crecer sus ahorros. |
|
|
|
脷nete a FinanzasMaster hoy. Transforma tu relaci贸n con el dinero con nuestro programa probado de 12 semanas. Matr铆cula con 50% de descuento esta semana. |
|
""" |
|
} |
|
] |
|
}, |
|
"GHA": { |
|
"description": """ |
|
La f贸rmula G.H.A. (Gancho-Historia-Acci贸n) es una estructura narrativa poderosa que utiliza el storytelling para crear conexiones emocionales y motivar a la acci贸n. |
|
|
|
TEOR脥A: |
|
Esta f贸rmula aprovecha el poder de las historias para captar la atenci贸n, generar empat铆a y motivar el cambio, bas谩ndose en la psicolog铆a narrativa y el poder de la identificaci贸n personal. |
|
|
|
ESTRUCTURA: |
|
1. Gancho: |
|
- Abre con un elemento sorpresa o intriga |
|
- Genera curiosidad inmediata |
|
- Plantea una pregunta o situaci贸n provocativa |
|
- Conecta emocionalmente desde la primera l铆nea |
|
|
|
2. Historia: |
|
- Desarrolla una narrativa personal o relatable |
|
- Incluye elementos de conflicto y superaci贸n |
|
- Mantiene la tensi贸n narrativa |
|
- Incorpora detalles sensoriales y emocionales |
|
|
|
3. Acci贸n: |
|
- Surge naturalmente de la resoluci贸n |
|
- Conecta la moraleja con la soluci贸n |
|
- Motiva desde la inspiraci贸n |
|
- Propone un camino claro hacia el cambio |
|
""", |
|
"examples": [ |
|
{ |
|
"title": "Programa de Fitness", |
|
"target": "Personas que quieren comenzar a ejercitarse", |
|
"story": """ |
|
"Nunca ser茅 una persona fitness", me repet铆a cada vez que ve铆a esas fotos perfectas en Instagram. Mi realidad eran 3 minutos de ejercicio y 20 de excusas. |
|
|
|
Un d铆a, mientras sub铆a las escaleras a mi departamento, tuve que detenerme en el segundo piso, jadeando. Mi hijo de 5 a帽os me mir贸 preocupado y me pregunt贸: "驴Mami, est谩s enferma?". Ese momento cambi贸 todo. |
|
|
|
FitLife no me prometi贸 un cuerpo de revista, me ofreci贸 algo mejor: la capacidad de jugar con mi hijo sin quedarme sin aliento. Empec茅 con 10 minutos diarios, luego 15, y ahora corremos juntos en el parque. |
|
|
|
Comienza tu historia de transformaci贸n hoy. 脷nete a FitLife y descubre c贸mo 15 minutos pueden cambiar tu vida. Primera semana gratis, porque tu bienestar no puede esperar. |
|
""" |
|
} |
|
] |
|
} |
|
} |
|
|
|
def generate_story(formula_type, target_audience, product, action, mood, length, story_topic=None): |
|
"""Funci贸n unificada para generar historias""" |
|
model = genai.GenerativeModel("gemini-2.0-flash") |
|
|
|
if formula_type not in story_formulas: |
|
raise ValueError("F贸rmula no v谩lida") |
|
|
|
|
|
system_prompt = f"""You are a world-class copywriter, specialized in crafting persuasive stories that emotionally connect with readers and drive them to action. |
|
|
|
FORMAT RULES: |
|
- Story must be structured in clear paragraphs |
|
- Each section must flow naturally into the next |
|
- No explicit section labels |
|
- Maintain consistent tone throughout |
|
- Include smooth transitions between parts |
|
- Story must feel complete and cohesive |
|
|
|
IMPORTANT STRUCTURE INSTRUCTIONS: |
|
- The selected formula MUST be applied to the entire story |
|
- Review and follow the structure detailed in story_formulas[formula_type]["description"] |
|
- Use the examples in story_formulas[formula_type]["examples"] as inspiration |
|
- Formula provides the framework, tone provides the emotional layer |
|
- Both must work together seamlessly |
|
|
|
FORMAT EXAMPLE: |
|
[First paragraph introducing the situation] |
|
|
|
[Second paragraph developing tension/conflict] |
|
|
|
[Third paragraph presenting transformation] |
|
|
|
[Final paragraph with natural call to action] |
|
|
|
IMPORTANT: |
|
- Each story must be unique and memorable |
|
- Avoid clich茅s and generic scenarios |
|
- Maintain a credible and authentic voice |
|
- Adapt language to target audience |
|
- Focus on emotional transformation |
|
- Follow formula structure while maintaining selected tone |
|
- Never explicitly label sections |
|
- Integrate product and call-to-action organically |
|
|
|
STORY STRUCTURE GUIDELINES: |
|
1. Study the formula description carefully |
|
2. Review provided examples for style and flow |
|
3. Maintain similar paragraph length and structure |
|
4. Use consistent emotional intensity |
|
5. Mirror the narrative progression |
|
6. Adapt content for target audience while keeping formula essence |
|
|
|
TONE AND STYLE: |
|
- Selected tone must remain consistent |
|
- Tone modifies HOW the story is told |
|
- Formula provides structure, tone provides emotion |
|
- Both elements must complement each other |
|
- Maintain voice appropriate for target audience |
|
|
|
KEY ELEMENTS TO INCLUDE: |
|
- Emotional hooks that grab attention |
|
- Relatable situations and characters |
|
- Sensory details and vivid descriptions |
|
- Natural problem-solution progression |
|
- Organic product integration |
|
- Compelling but subtle call-to-action""" |
|
|
|
|
|
story_instruction = f"{system_prompt}\n\n" |
|
|
|
|
|
story_instruction += f""" |
|
SELECTED FORMULA STRUCTURE: |
|
{story_formulas[formula_type]['description']} |
|
|
|
SUCCESSFUL EXAMPLES OF THIS FORMULA: |
|
""" |
|
|
|
|
|
for example in story_formulas[formula_type]['examples']: |
|
story_instruction += f""" |
|
TITLE: {example['title']} |
|
TARGET: {example['target']} |
|
STORY: |
|
{example['story']} |
|
""" |
|
|
|
|
|
story_instruction += f""" |
|
YOUR TASK: |
|
Create a compelling {length}-word story in Spanish with a {mood} tone for {target_audience} about {product} that leads to this action: {action}. |
|
|
|
SPECIFIC REQUIREMENTS: |
|
1. Follow the formula structure exactly as shown in the description |
|
2. Maintain the {mood} tone throughout the story |
|
3. Write for {target_audience} using appropriate language and references |
|
4. Integrate {product} naturally into the narrative |
|
5. Lead to the call-to-action: {action} |
|
""" |
|
|
|
|
|
if formula_type == "GHA" and story_topic: |
|
story_instruction += f""" |
|
6. Incorporate this specific story topic: {story_topic} |
|
""" |
|
|
|
story_instruction += """ |
|
FINAL REMINDERS: |
|
1. Write in clear, engaging Spanish |
|
2. Use proper paragraph structure |
|
3. Maintain narrative flow |
|
4. Create emotional connection |
|
5. Make call-to-action feel natural |
|
|
|
Generate the story now: |
|
""" |
|
|
|
response = model.generate_content([story_instruction]) |
|
if response and response.parts: |
|
return response.parts[0].text.strip() |
|
raise ValueError("No se pudo generar la historia") |
|
|
|
|
|
st.set_page_config(page_title="Generador de Historias", page_icon=":pencil:", layout="wide") |
|
|
|
|
|
st.markdown("<h1 style='text-align: center;'>Story Genius Maker</h1>", unsafe_allow_html=True) |
|
st.markdown("<h3 style='text-align: center;'>Teje historias inolvidables en segundos, guiado por la magia de la inteligencia artificial que da vida a tus ideas en relatos cautivadores.</h3>", unsafe_allow_html=True) |
|
|
|
|
|
with st.expander("Selecciona la f贸rmula para generar tu historia"): |
|
|
|
available_formulas = list(story_formulas.keys()) |
|
formula_display_names = [] |
|
formula_mapping = {} |
|
|
|
|
|
for formula in available_formulas: |
|
display_name = '.'.join(list(formula)) if formula.isupper() else formula |
|
formula_display_names.append(display_name) |
|
formula_mapping[display_name] = formula |
|
|
|
|
|
formula = st.radio( |
|
"Selecciona la f贸rmula para generar tu historia:", |
|
formula_display_names |
|
) |
|
|
|
|
|
selected_formula = formula_mapping[formula] |
|
|
|
|
|
col1, col2 = st.columns([2, 3]) |
|
|
|
|
|
with col1: |
|
target_audience = st.text_input("P煤blico objetivo", |
|
placeholder="驴A qui茅n est谩 dirigido tu mensaje?") |
|
product = st.text_input("Producto/Servicio", |
|
placeholder="驴Qu茅 est谩s ofreciendo?") |
|
action = st.text_area("Llamado a la acci贸n", |
|
placeholder="驴Qu茅 acci贸n espec铆fica debe tomar tu audiencia?") |
|
|
|
|
|
with st.expander("Personaliza tu historia"): |
|
mood = st.selectbox("Tono de la historia:", |
|
["Emocional", "Triste", "Feliz", "Horror", "Comedia", "Rom谩ntico"]) |
|
|
|
|
|
if selected_formula == "GHA": |
|
length = st.slider("Longitud de la historia (palabras):", |
|
min_value=50, max_value=200, value=150, step=10) |
|
else: |
|
length = st.slider("Longitud de la historia (palabras):", |
|
min_value=50, max_value=150, value=100, step=10) |
|
|
|
|
|
story_topic = None |
|
if selected_formula == "GHA": |
|
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.)." |
|
) |
|
|
|
|
|
submit = st.button("Generar mi historia") |
|
|
|
|
|
with col2: |
|
if submit: |
|
if target_audience and product and action: |
|
try: |
|
|
|
if selected_formula == "GHA": |
|
if story_topic: |
|
response = generate_story(selected_formula, target_audience, product, |
|
action, mood, length, story_topic) |
|
else: |
|
st.error("Por favor, completa todos los campos requeridos para la f贸rmula G.H.A.") |
|
response = "" |
|
else: |
|
response = generate_story(selected_formula, target_audience, product, |
|
action, mood, length) |
|
|
|
if response: |
|
st.subheader("Historia generada:") |
|
st.write(response) |
|
except ValueError as e: |
|
st.error(f"Error: {str(e)}") |
|
else: |
|
st.error("Por favor, completa todos los campos requeridos (P煤blico objetivo, Producto y Acci贸n).") |
|
|