import gradio as gr from groq import Groq import os # 1. Securely fetch the API key from Hugging Face Secrets api_key = os.environ.get("GROQ_API_KEY") # Initialize the Groq client if api_key: client = Groq(api_key=api_key) else: print("Error: GROQ_API_KEY not found in environment variables.") # 2. Define the generator function def generate_linkedin_post(topic, tone): if not api_key: return "Error: API Key is missing. Please add GROQ_API_KEY to your Space Secrets." system_prompt = f""" You are an expert social media manager and copywriter. Write an engaging, high-quality LinkedIn post about the following topic. The tone of the post should be: {tone}. Include engaging formatting, line breaks, and 2-3 relevant hashtags at the end. Do not include any pleasantries like "Here is your post:", just output the post itself. """ try: response = client.chat.completions.create( model="llama-3.1-8b-instant", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Topic: {topic}"} ], temperature=0.7, max_tokens=500, ) return response.choices[0].message.content except Exception as e: return f"An error occurred: {str(e)}" # 3. Build the UI demo = gr.Interface( fn=generate_linkedin_post, inputs=[ gr.Textbox( label="What is the topic of your post?", placeholder="e.g., Why AI will not replace software engineers, but make them faster.", lines=2 ), gr.Dropdown( label="Select the Tone", choices=["Professional", "Casual & Friendly", "Inspirational", "Controversial/Hot Take", "Educational"], value="Professional" ) ], outputs=gr.Textbox(label="Your Generated LinkedIn Post", lines=10), title="🚀 AI LinkedIn Post Generator", description="Enter a topic and choose a tone to generate a ready-to-publish LinkedIn post instantly using Groq's Llama 3.1 model.", theme=gr.themes.Soft() ) # 4. Launch the app (Do NOT use share=True on Hugging Face) if __name__ == "__main__": demo.launch()