import os import gradio as gr from groq import Groq from typing import Tuple # ============================================================================ # GROQ API KEY FROM HUGGING FACE SECRETS # ============================================================================ GROQ_API_KEY = os.getenv("GROQ_API_KEY") if not GROQ_API_KEY: raise ValueError("❌ GROQ_API_KEY secret is not set. Please add it in Space Settings → Secrets.") client = Groq(api_key=GROQ_API_KEY) # ============================================================================ # PLATFORM GUIDELINES # ============================================================================ PLATFORM_GUIDELINES = { "Facebook": { "style": "friendly_conversational", "tone_description": "Warm, relatable, engaging", "emoji_usage": "Generous (2-5 emojis)", "length": "100-200 words", "structure": "Story-like, personal touch", "cta": "Question or engagement hook at the end", "hashtags": "2-5 relevant hashtags", }, "LinkedIn": { "style": "professional_insightful", "tone_description": "Authoritative, value-driven, business-focused", "emoji_usage": "Minimal (0-2 emojis)", "length": "150-300 words", "structure": "Hook → Insight → Value → CTA", "cta": "Professional call-to-action", "hashtags": "3-5 industry-relevant hashtags", }, "WhatsApp": { "style": "casual_direct", "tone_description": "Personal, conversational, urgent", "emoji_usage": "Moderate (1-3 emojis)", "length": "50-100 words", "structure": "Short lines, bullet points, scannable", "cta": "Direct and simple", "hashtags": "None or minimal", }, } def get_platform_prompt(platform: str, topic: str, tone: str) -> str: guidelines = PLATFORM_GUIDELINES.get(platform, PLATFORM_GUIDELINES["Facebook"]) return f"""You are an expert social media content creator. Generate a high-quality post for {platform} about: {topic} Tone: {tone} Rules for {platform}: - Style: {guidelines['style']} - Tone: {guidelines['tone_description']} - Emojis: {guidelines['emoji_usage']} - Length: {guidelines['length']} - Structure: {guidelines['structure']} - CTA: {guidelines['cta']} - Hashtags: {guidelines['hashtags']} Write naturally and engagingly. Output ONLY the final post. No explanations.""" def generate_social_media_post(platform: str, topic: str, tone: str) -> Tuple[str, str]: if not platform or platform not in ["Facebook", "LinkedIn", "WhatsApp"]: return "❌ Error: Please select a valid platform.", "" if not topic or len(topic.strip()) < 3: return "❌ Error: Please provide a topic (at least 3 characters).", "" if not tone or tone not in ["Informative", "Promotional", "Casual", "Humorous"]: return "❌ Error: Please select a valid tone.", "" try: system_prompt = get_platform_prompt(platform, topic, tone) chat_completion = client.chat.completions.create( messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Generate the {platform} post now."} ], model="llama-3.3-70b-versatile", max_tokens=600, temperature=0.7, top_p=0.9, ) generated_post = chat_completion.choices[0].message.content.strip() guidelines = PLATFORM_GUIDELINES[platform] platform_info = f""" 📱 **{platform} Post Generated Successfully!** **Guidelines Applied:** - Style: {guidelines['style']} - Tone: {tone} - Emojis: {guidelines['emoji_usage']} **Tips:** 1. Copy the post above 2. Paste directly on {platform} """ return generated_post, platform_info except Exception as e: return f"❌ Error: {str(e)}", "" # ============================================================================ # GRADIO INTERFACE # ============================================================================ def create_gradio_interface(): with gr.Blocks(title="Social Post AI") as demo: gr.Markdown(""" # 🚀 Social Post AI ### Instant Smart Captions for Facebook • LinkedIn • WhatsApp """) with gr.Row(): platform_input = gr.Dropdown( choices=["Facebook", "LinkedIn", "WhatsApp"], value="Facebook", label="📱 Select Platform" ) tone_input = gr.Dropdown( choices=["Informative", "Promotional", "Casual", "Humorous"], value="Informative", label="🎭 Select Tone" ) topic_input = gr.Textbox( label="📌 Topic / Idea", placeholder="e.g. Launching a new AI product, Team celebration, Special weekend offer", lines=2 ) generate_btn = gr.Button("✨ Generate Post", variant="primary", size="large") post_output = gr.Textbox( label="✅ Your Generated Post (Ready to Copy)", lines=12, interactive=True ) info_output = gr.Markdown() gr.Examples( examples=[ ["Facebook", "Launching a new AI product", "Promotional"], ["LinkedIn", "Company milestone achievement", "Informative"], ["WhatsApp", "Weekend team outing", "Casual"], ], inputs=[platform_input, topic_input, tone_input], label="💡 Try These Examples" ) generate_btn.click( fn=generate_social_media_post, inputs=[platform_input, topic_input, tone_input], outputs=[post_output, info_output] ) return demo # ============================================================================ # LAUNCH FOR HUGGING FACE SPACES # ============================================================================ if __name__ == "__main__": print("🎉 Social Post AI is starting...") print("📊 Powered by Groq + Llama 3.3-70B") demo = create_gradio_interface() demo.launch( server_name="0.0.0.0", server_port=7860 )