from dotenv import load_dotenv import streamlit as st import os import google.generativeai as genai import random # Cargar las variables de entorno load_dotenv() # Configurar la API de Google 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"Introduce directamente el producto '{product}' como la solución clara al problema que enfrenta el lector." elif product_mention == "Indirecta": return f"Referencia sutilmente el producto '{product}' como una posible solución al problema del lector sin nombrarlo explícitamente." elif product_mention == "Metafórica": return f"Introduce el producto '{product}' usando una metáfora, conectándolo simbólicamente a la solución que necesita el lector." return "" # Ejemplos de llamados a la acción por tipo cta_types = { "directos": [ "Descargar la guía para mejorar mi productividad diaria.", "Suscribirme para recibir actualizaciones y promociones exclusivas.", "Unirme a la prueba gratis de 14 días y descubrir nuevas funciones.", "Registrarme para acceder a contenido premium y estrategias efectivas.", "Comprar ahora y obtener un regalo especial con mi pedido." ], "urgencia": [ "Inscribirme ahora para asegurar mi lugar antes de que se agoten las plazas.", "Comenzar mi transformación hoy y no perder más tiempo." ], "descuento": [ "Aprovechar el 50% de descuento y comprar por tiempo limitado.", "Hacer mi pedido ahora y obtener un 30% de descuento adicional." ], "exclusividad": [ "Acceder a contenido exclusivo solo para miembros.", "Ser parte de un grupo selecto y disfrutar de beneficios únicos." ], "beneficio_claro": [ "Mejorar mi productividad en solo una semana.", "Transformar mi carrera profesional con herramientas avanzadas." ], "personalización": [ "Descubrir cómo personalizar esta oferta para mis necesidades.", "Elegir las opciones que mejor se adapten a mis necesidades." ] } # Función para que el modelo elija automáticamente el tipo de CTA y el CTA específico def get_random_cta(): cta_type = random.choice(list(cta_types.keys())) # Selección aleatoria del tipo de CTA cta = random.choice(cta_types[cta_type]) # Selección aleatoria del CTA dentro del tipo return cta # Función para generar llamados a la acción def generate_ctas(number_of_ctas, target_audience, product, call_to_action, temperature): product_mention = get_random_product_mention() mention_instruction = get_mention_instruction(product_mention, product) # Configuración del modelo generation_config = { "temperature": temperature, "top_p": 0.85, "top_k": 128, "max_output_tokens": 2048, "response_mime_type": "text/plain", } # Configuración del modelo generativo y las instrucciones del sistema model = genai.GenerativeModel( model_name="gemini-1.5-flash", # Nombre del modelo que estamos utilizando generation_config=generation_config, # Configuración de generación system_instruction=( "Eres un experto copywriter especializado en productos que solucionan problemas de tus clientes. " "Tu tarea es ayudarme a escribir llamados a la acción (CTA) para mi [página web, landing, correo], " "teniendo en cuenta los puntos débiles de mi [cliente ideal] y el [producto] y la [acción] a realizar. " "Recuerda que un buen CTA debe tener:\n\n" "1. **Acción**: Palabras que invitan a realizar un movimiento (e.g., 'Descargar', 'Suscribirse').\n" "2. **Valor**: Explicar el beneficio que el usuario obtendrá al realizar la acción.\n\n" "Asegúrate de que cada llamado a la acción siga la estructura de 'Acción + conector + Valor', y evita incluir explicaciones como 'Acción: Descubrir' o 'Valor: Un oasis de paz en medio del caos'.\n" "Important: Only answer CTAs, never include explanations or categories, like this: 'Registrarme ahora y descubrir cómo encontrar un poco de paz en medio del caos. (Este CTA apela al deseo de Han Solo de encontrar un momento de tranquilidad en su vida agitada.).'\n" "Basate en estos ejemplos para realizar tu tarea de crear los CTA's:\n\n" "**Ejemplos de CTAs en Voz Activa en Primera Persona:**\n" "- 'Descargar la guía para mejorar mi productividad diaria'\n" "- 'Suscribirme para recibir actualizaciones y promociones exclusivas'\n" "- 'Unirme a la prueba gratis de 14 días y descubrir nuevas funciones'\n" "Usa estos lineamientos para generar CTAs de alta conversión en español." ) ) # Selección aleatoria de tipos de CTA, manteniendo variedad en la salida selected_types = random.sample(list(cta_types.keys()), min(number_of_ctas, len(cta_types))) # Crear un mensaje para el modelo que incluye los CTAs generados según los tipos seleccionados ctas_instruction = ( f"Tu tarea es crear {number_of_ctas} llamados a la acción efectivos dirigidos a {target_audience}, " f"para promover {call_to_action}. Usa la siguiente mención: {mention_instruction}. " "Asegúrate de que cada llamado a la acción siga la estructura de 'Acción + conector + Valor', " "como los ejemplos proporcionados anteriormente." ) # Generar el resultado utilizando el modelo con la instrucción de CTA específica try: response = model.generate_content([ctas_instruction]) # Extraer el texto de la respuesta generated_ctas = response.candidates[0].content.parts[0].text.strip() # Modificado aquí # Retornar el resultado return generated_ctas except Exception as e: raise ValueError(f"Error al generar los CTA: {str(e)}") # Configurar la interfaz de usuario con Streamlit st.set_page_config(page_title="QuickPrompt", layout="wide") import streamlit as st # Título del Sidebar st.sidebar.title("Quick Prompt User Manual") # Introducción del manual st.sidebar.subheader("Welcome to Quick Prompt") st.sidebar.write(""" In a world where competition for attention is fierce, getting your audience not only to listen but to act is a daily challenge. Even with an excellent product, service, or resource, it can be frustrating to watch your audience's interest fade without turning into concrete actions. This is where calls-to-action (CTAs) come into play. CTAs are much more than just buttons or persuasive phrases: they are the bridge that connects your audience with what you offer. """) # Cómo Utilizar Quick Prompt st.sidebar.subheader("How to Use Quick Prompt") st.sidebar.write(""" Quick Prompt is an intuitive, easy-to-use tool that helps you create attractive and effective CTAs. Here is how you can feed the necessary variables to generate CTAs that inspire your audience to act: """) # Sección 1: Definir tu Público Objetivo st.sidebar.subheader("1. Define Your Target Audience") st.sidebar.write(""" Understand and connect with your audience by answering these key questions: - Who is your audience? - What are their interests and needs? - What problems can they solve with your product? Examples: - University students looking for tools to improve their productivity. - Entrepreneurs wanting to learn marketing skills to grow their businesses. - Professionals looking to improve time management and achieve their career goals. """) # Sección 2: Especificar el Producto st.sidebar.subheader("2. Specify the Product") st.sidebar.write(""" Here, define the service or resource you're promoting. The CTA should be clear and directly related to the product. Examples: - "Free guide on efficient study techniques." - "Online digital marketing course for entrepreneurs." - "Exclusive webinar on time management for team leaders." """) # Sección 3: Determinar la Acción Deseada st.sidebar.subheader("3. Determine the Desired Action") st.sidebar.write(""" Define the specific action you want your audience to take. This can vary from a download to a registration or subscription. Examples: - Download a free PDF with useful resources. - Sign up for an online course on digital skills. - Register for an exclusive event or webinar. """) # Sección 4: Seleccionar el Número de CTAs st.sidebar.subheader("4. Select the Number of CTAs") st.sidebar.write(""" Decide how many CTAs you want to create in one session. This may depend on the number of offers or products you are promoting. Examples: - Generate 1 direct CTA for a single product. - Create 3 varied CTAs for a landing page with multiple resources. - Design 5 personalized CTAs for different audience types. """) # Sección 5: Ajustar la Creatividad st.sidebar.subheader("5. Adjust the Creativity") st.sidebar.write(""" Quick Prompt includes a slider that allows you to adjust the creativity of your CTAs. Here are creativity ranges according to values from 0 to 1, with three examples in each range: """) # Rango de Creatividad Baja st.sidebar.write("**Low Creativity (0.0 - 0.3)**") st.sidebar.write(""" This range is direct and simple. The CTAs are clear, concise, and traditional. Examples: - "Download the free productivity guide." - "Sign up for the course today." - "Register for the webinar now." """) # Rango de Creatividad Media st.sidebar.write("**Medium Creativity (0.4 - 0.7)**") st.sidebar.write(""" In this range, CTAs become more persuasive, with a friendly tone that engages the reader, but without being too innovative. Examples: - "Improve your day with our free guide. Download it now!" - "Join our course and start growing today." - "Register for the webinar and discover new opportunities." """) # Rango de Creatividad Alta st.sidebar.write("**High Creativity (0.8 - 1.0)**") st.sidebar.write(""" In this range, the CTAs are more creative and dynamic, generating excitement or urgency. The language is more appealing and visual. Examples: - "Conquer your productivity with our essential guide! Download it now." - "Take a leap in your career. Join the course and transform your future today." - "Don't miss this unique opportunity. Register and secure your spot in the webinar." """) # Footer del manual st.sidebar.write("With Quick Prompt, transforming interest into action has never been easier.") # Centrar el título y el subtítulo st.markdown("
{generated_ctas}