import streamlit as st st.set_page_config(page_title="AI Lead Magnet Generator", layout="wide") import requests import os from datetime import datetime # Configure OpenAI API (using OPENAI_API_KEY) OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions" # Google Apps Script endpoint - REPLACE WITH YOUR NEW DEPLOYMENT URL GOOGLE_APPS_SCRIPT_URL = "https://script.google.com/macros/s/YOUR_SCRIPT_ID_HERE/exec" def extract_lead_magnet_title(content): """Extracts the main title from the lead magnet content.""" if not content: return "Lead Magnet Generated" try: import re lines = content.split('\n') for line in lines: line = line.strip() # Look for titles in various formats if line.startswith('#') or line.startswith('**') or line.isupper(): clean_title = line.replace('#', '').replace('*', '').strip() if len(clean_title) > 10 and len(clean_title) < 100: return clean_title # If no clear title found, return first meaningful line for line in lines: line = line.strip() if len(line) > 20 and not line.startswith('Here') and not line.startswith('Based'): return line[:80] + "..." if len(line) > 80 else line return "Custom Lead Magnet Generated" except Exception as e: return "Lead Magnet Generated" def save_to_google_apps_script(data): """Saves the submitted lead magnet data via Google Apps Script.""" try: response = requests.post( GOOGLE_APPS_SCRIPT_URL, json=data, timeout=30, headers={'Content-Type': 'application/json'} ) if response.status_code == 200: try: result = response.json() if result.get('result') == 'success': return True, "Lead magnet data saved successfully! We'll be in touch soon." else: return False, f"Script error: {result.get('message', 'Unknown error')}" except: # If response is not JSON, treat as success if status is 200 return True, "Lead magnet data saved successfully! We'll be in touch soon." else: return False, f"Submission failed with status code: {response.status_code}" except requests.exceptions.Timeout: return False, "Request timed out. Please try again later." except Exception as e: return False, f"Error submitting data: {str(e)}" def generate_lead_magnet(industry, audience, offer, lead_magnet_type, pain_points=None, goals=None, company_name=None): """Generates a comprehensive lead magnet using OpenAI GPT-4.""" # Include optional information if provided pain_points_text = f"Target Audience Pain Points: {pain_points}" if pain_points else "" goals_text = f"Business Goals: {goals}" if goals else "" company_text = f"Company: {company_name}" if company_name else "" prompt = f"""As an expert marketing strategist and copywriter, create a compelling lead magnet for the following business: Industry: {industry} Target Audience: {audience} Primary Offer/Service: {offer} Lead Magnet Type: {lead_magnet_type} {company_text} {pain_points_text} {goals_text} Please create a complete, actionable lead magnet that includes: 1. **Compelling Title:** A magnetic headline that clearly communicates value 2. **Hook & Problem Statement:** Identify the specific problem your audience faces 3. **Value Proposition:** Explain exactly what they'll get and why it matters 4. **Main Content:** Provide substantial, actionable content based on the lead magnet type: - If Checklist: Create 7-12 specific, actionable items - If Guide: Provide step-by-step instructions with clear sections - If Template: Create a framework they can immediately use - If Cheat Sheet: Provide quick reference tips and shortcuts - If Resource List: Curate valuable tools, websites, or resources - If Mini-Course: Outline 3-5 lessons with key takeaways - If Assessment: Create questions that provide personalized insights 5. **Call-to-Action:** Clear next steps to engage with your business 6. **Bonus Section:** Additional value or quick wins 7. **Contact Information Section:** How they can learn more about your services Make the content specific to the {industry} industry and directly address the needs of {audience}. Ensure the lead magnet naturally leads to your {offer} without being overly promotional. The content should be valuable enough that people would pay for it, but serves as a perfect introduction to working with you. Format the response with clear markdown headers and make it ready to use as a complete lead magnet.""" headers = { "Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json" } data = { "model": "gpt-4", "messages": [ {"role": "system", "content": "You are a world-class marketing strategist and copywriter specializing in creating high-converting lead magnets. You understand how to balance providing genuine value while naturally leading prospects toward a business's services. Your lead magnets are known for their actionable content and professional presentation."}, {"role": "user", "content": prompt} ], "temperature": 0.7, "max_tokens": 4000 } try: response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except Exception as e: st.error(f"API Error: {str(e)}") return None # Streamlit UI st.title("🧲 AI Lead Magnet Generator") st.markdown("### Create compelling lead magnets tailored to your industry, audience, and offer") # Main form with required fields st.markdown("#### Required Information") col1, col2 = st.columns(2) with col1: industry = st.text_input("Your Industry*", placeholder="e.g., Digital Marketing, Real Estate, Fitness, Consulting", help="What industry or niche are you in?") audience = st.text_input("Target Audience*", placeholder="e.g., Small business owners, New parents, Recent graduates", help="Who specifically are you trying to reach?") with col2: offer = st.text_input("Your Primary Offer/Service*", placeholder="e.g., Marketing consulting, Personal training, Web design", help="What is your main product or service?") lead_magnet_type = st.selectbox("Lead Magnet Type*", ["Checklist", "Ultimate Guide", "Template", "Cheat Sheet", "Resource List", "Mini-Course", "Assessment/Quiz", "Toolkit", "Blueprint"]) # Optional fields for better customization st.markdown("#### Optional Information (for better customization)") col1, col2 = st.columns(2) with col1: company_name = st.text_input("Company Name", placeholder="Your business name (optional)") pain_points = st.text_area("Audience Pain Points", placeholder="What specific problems does your audience face?", help="The more specific, the better your lead magnet will be") with col2: goals = st.text_area("Your Business Goals", placeholder="What do you want to achieve with this lead magnet?", help="e.g., Generate leads for coaching, Build email list, Establish authority") additional_notes = st.text_area("Additional Notes", placeholder="Any other specific requirements or ideas?") # Generate button if st.button("🚀 Generate My Lead Magnet", type="primary"): if not all([industry, audience, offer, lead_magnet_type]): st.error("Please fill in all required fields marked with *") else: # Add timestamp timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with st.spinner("Creating your personalized lead magnet... This may take a moment."): # Generate lead magnet lead_magnet_content = generate_lead_magnet( industry=industry, audience=audience, offer=offer, lead_magnet_type=lead_magnet_type, pain_points=pain_points, goals=goals, company_name=company_name ) if lead_magnet_content: # Extract title for saving lead_magnet_title = extract_lead_magnet_title(lead_magnet_content) # Format data for Google Apps Script form_data = { "timestamp": timestamp, "company_name": company_name if company_name else "Not provided", "industry": industry, "target_audience": audience, "primary_offer": offer, "lead_magnet_type": lead_magnet_type, "pain_points": pain_points if pain_points else "Not specified", "business_goals": goals if goals else "Not specified", "additional_notes": additional_notes if additional_notes else "None", "lead_magnet_title": lead_magnet_title, "content_preview": lead_magnet_content[:500] + "..." if len(lead_magnet_content) > 500 else lead_magnet_content } # Save via Google Apps Script (optional - comment out if not needed) # save_success, save_message = save_to_google_apps_script(form_data) # if save_success: # st.success(save_message) # else: # st.warning(save_message) # Display the lead magnet st.success("🎉 Your lead magnet has been generated!") # Create download section st.markdown("---") col1, col2, col3 = st.columns([1, 2, 1]) with col2: st.download_button( label="📥 Download Lead Magnet", data=lead_magnet_content, file_name=f"lead_magnet_{industry.replace(' ', '_').lower()}_{timestamp.split()[0]}.md", mime="text/markdown", type="primary" ) st.markdown("---") st.markdown("### Your Generated Lead Magnet:") st.markdown(lead_magnet_content) else: st.error("Unable to generate your lead magnet. Please check your OpenAI API key and try again.") # Footer st.markdown("---") st.markdown("### 💡 Tips for Using Your Lead Magnet:") col1, col2 = st.columns(2) with col1: st.markdown(""" **Design & Format:** - Convert to PDF for professional look - Add your branding and colors - Include images or graphics - Make it visually appealing """) with col2: st.markdown(""" **Distribution:** - Gate it behind email signup - Promote on social media - Add to your website - Use in email signatures """) st.markdown("### Need help implementing your lead magnet? Consider our marketing services!")