import streamlit as st st.set_page_config(page_title="AI Social Media Platform Quiz", layout="wide") import requests import os import json 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/AKfycbw4M8y2bcb5yBCB2j8RlbVqrMMJBBIfmIVhda55fGzhuHdcRoZ6Zb7BRg3oBTUTIkFs/exec" def extract_platform_recommendations(recommendations_text): """Extracts brief summaries of the platform recommendations from the full text.""" if not recommendations_text: return "No recommendations generated" try: import re # Look for platform names and recommendations in various formats platforms = ['Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube', 'Pinterest', 'Twitter', 'X'] platform_mentions = [] lines = recommendations_text.split('\n') for line in lines: line = line.strip() if not line: continue # Check if line contains platform names for platform in platforms: if platform.lower() in line.lower(): # Clean up the line and extract relevant info clean_line = line.replace('*', '').replace('#', '').strip() if len(clean_line) > 10 and len(clean_line) < 150: platform_mentions.append(clean_line) break # Remove duplicates while preserving order unique_mentions = [] for mention in platform_mentions: if mention not in unique_mentions: unique_mentions.append(mention) # Return up to 3 platform recommendations, joined by semicolons return '; '.join(unique_mentions[:3]) if unique_mentions else "Platform recommendations generated" except Exception as e: return f"Error extracting recommendations: {str(e)}" def save_to_google_apps_script(data): """Saves the submitted quiz 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, "Quiz results submitted successfully! Your personalized recommendations have been generated." 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, "Quiz results submitted successfully! Your personalized recommendations have been generated." 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_platform_recommendations(business_type, audience_location, camera_comfort, content_style, primary_goal): """Generates social media platform recommendations using OpenAI GPT-4.""" # Build the prompt based on quiz answers prompt = f"""As an expert social media strategist, analyze the following quiz responses and provide personalized social media platform recommendations: Quiz Responses: - Business Type: {business_type} - Audience Behavior: {audience_location} - Camera Comfort Level: {camera_comfort} - Preferred Content Style: {content_style} - Primary Goal: {primary_goal} Based on these responses, provide: 1. **Top 3 Recommended Platforms** (ranked by priority) - For each platform, explain WHY it's a good fit based on their specific answers - Include specific features or strategies they should focus on 2. **Platform-Specific Strategy Recommendations** - Best content types for each recommended platform - Optimal posting frequency and timing - Key features to leverage (Stories, Reels, etc.) 3. **Getting Started Action Plan** - First 3 steps they should take on their top platform - Content ideas for their first week - Metrics to track for success 4. **Platforms to Avoid (and Why)** - Briefly mention 1-2 platforms that wouldn't be the best fit - Explain why based on their responses Requirements: - Prioritize platforms that align with their business type and goals - Consider their comfort level with video/camera content - Match recommendations to where their audience actually spends time - Provide actionable, specific advice they can implement immediately - Keep explanations clear and beginner-friendly - Focus on 2-3 platforms max to avoid overwhelming them Make the recommendations practical and tailored specifically to their quiz responses.""" headers = { "Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json" } data = { "model": "gpt-4", "messages": [ { "role": "system", "content": "You are an expert social media strategist who specializes in helping businesses choose the right social media platforms. You provide clear, actionable recommendations based on business needs, audience behavior, and content preferences." }, {"role": "user", "content": prompt} ], "temperature": 0.7, "max_tokens": 2500 } 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 Social Media Platform Quiz") st.markdown("### Discover which social media platforms will be most effective for your business") st.markdown("*Take this 5-question quiz to get personalized platform recommendations powered by AI*") # Quiz Form st.markdown("---") st.markdown("## 📋 Answer These 5 Quick Questions") # Question 1 st.markdown("### Question 1: What type of business do you run?") business_type = st.radio("", [ "Local brick-and-mortar (café, salon, etc.)", "E-commerce or product brand", "Professional services (law, consulting, real estate)", "Creative or personal brand", "Nonprofit or community org" ], key="q1") # Question 2 st.markdown("### Question 2: Where is your audience most likely to hang out?") audience_location = st.radio("", [ "Scrolling reels or stories during downtime", "Browsing events or checking reviews", "Watching how-to videos or reviews", "Looking for professional or B2B connections", "Searching for design inspiration" ], key="q2") # Question 3 st.markdown("### Question 3: How comfortable are you with being on camera?") camera_comfort = st.radio("", [ "I love it — I'm ready to go viral", "I don't mind being on camera occasionally", "Not me — I'd rather show products, services, or graphics", "I'm fine with someone else doing it", "Doesn't matter, I prefer written content anyway" ], key="q3") # Question 4 st.markdown("### Question 4: What's your primary content style?") content_style = st.radio("", [ "Quick photos + captions", "Before/after or transformation stories", "Long-form education or storytelling", "Snappy videos and entertainment", "Infographics, visuals, or curated looks" ], key="q4") # Question 5 st.markdown("### Question 5: What's your top goal with social media right now?") primary_goal = st.radio("", [ "Build local awareness", "Get people to contact or book", "Generate leads/sales", "Grow a community", "Establish authority and credibility" ], key="q5") # Optional business name for personalization st.markdown("---") business_name = st.text_input("Business Name (Optional)", placeholder="e.g., Acme Coffee Shop - helps us personalize your recommendations") # Generate recommendations button st.markdown("---") if st.button("🚀 Get My Platform Recommendations", type="primary"): # Check if all questions are answered (all have default selections, so this validates they've made choices) if all([business_type, audience_location, camera_comfort, content_style, primary_goal]): # Add timestamp timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with st.spinner("Analyzing your responses and generating personalized recommendations..."): # Generate platform recommendations recommendations = generate_platform_recommendations( business_type, audience_location, camera_comfort, content_style, primary_goal ) if recommendations: # Extract platform summaries for the Google Sheet platform_summaries = extract_platform_recommendations(recommendations) # Format data for Google Apps Script quiz_data = { "timestamp": timestamp, "business_name": business_name if business_name else "Not specified", "business_type": business_type, "audience_location": audience_location, "camera_comfort": camera_comfort, "content_style": content_style, "primary_goal": primary_goal, "platform_recommendations": platform_summaries } # Save via Google Apps Script save_success, save_message = save_to_google_apps_script(quiz_data) if save_success: st.success(save_message) else: st.warning(save_message) # Display the recommendations st.markdown("---") st.markdown("## 🎯 Your Personalized Platform Recommendations") st.markdown(recommendations) # Add download option st.markdown("---") filename_business = business_name.replace(" ", "_") if business_name else "business" st.download_button( label="📥 Download Recommendations as Text File", data=recommendations, file_name=f"{filename_business}_social_media_recommendations_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt", mime="text/plain" ) # Call-to-action section st.markdown("---") st.markdown("### 🚀 Ready to Implement Your Strategy?") st.markdown(""" **Next Steps:** 1. **Start with your #1 recommended platform** - focus your energy here first 2. **Create your first week of content** using the specific ideas provided 3. **Set up your posting schedule** based on the recommended timing 4. **Track the suggested metrics** to measure your success 5. **Expand to platform #2** once you've established consistency on platform #1 """) else: st.error("Unable to generate recommendations. Please check your OpenAI API key and try again.") else: st.error("Please answer all 5 questions to get your recommendations.") # Footer sections st.markdown("---") st.markdown("### 💡 Why This Quiz Works:") st.markdown(""" - **Personalized Analysis**: AI analyzes your specific business type, audience, and goals - **Actionable Recommendations**: Get specific strategies, not generic advice - **Avoid Platform Overload**: Focus on 2-3 platforms that actually fit your business - **Beginner-Friendly**: Clear next steps whether you're new to social media or looking to optimize """) st.markdown("---") st.markdown("### 🔥 Common Platform Combinations by Business Type:") col1, col2, col3 = st.columns(3) with col1: st.markdown("**Local Businesses**") st.markdown("• Instagram + Facebook") st.markdown("• Google Business Profile") st.markdown("• Local community focus") with col2: st.markdown("**E-commerce Brands**") st.markdown("• Instagram + TikTok") st.markdown("• Pinterest for discovery") st.markdown("• YouTube for tutorials") with col3: st.markdown("**Professional Services**") st.markdown("• LinkedIn + YouTube") st.markdown("• Industry authority building") st.markdown("• Long-form content focus") st.markdown("---") st.markdown("*Powered by OpenAI GPT-4 | Built with Streamlit*")