import gradio as gr from huggingface_hub import InferenceClient import os # 1. SETUP: Get the token from the Space secrets # This fixes the "Auth" error by using your private key hf_token = os.getenv("HF_TOKEN") # Initialize the client with your token # We use Qwen 2.5 Coder 32B. It is the best open model for this task. model_id = "Qwen/Qwen2.5-Coder-32B-Instruct" client = InferenceClient(api_key=hf_token) def generate_seo(code_snippet, file_type): """ Generates SEO and JSON-LD using the Authenticated Client. """ if not code_snippet.strip(): return "⚠️ Error: Please paste some code first." # SEO Prompt system_instruction = f""" You are an expert Technical SEO Specialist. Analyze the user's {file_type} code. Your Goal: Generate Google-compliant JSON-LD structured data and SEO meta tags. Output Format (Strict Markdown): ## SEO Metadata **Title:** [Engaging Title, max 60 chars] **Description:** [Summary including keywords, max 160 chars] **Keywords:** [5-8 comma-separated keywords] ## JSON-LD Structured Data ```json [Insert VALID JSON-LD here. - If Python: Use schema.org/SoftwareSourceCode - If HTML: Use schema.org/WebPage or schema.org/TechArticle] ``` """ user_message = f"Analyze this {file_type} code:\n\n{code_snippet}" try: # Chat Completion API (Reliable with Token) response = client.chat_completion( model=model_id, messages=[ {"role": "system", "content": system_instruction}, {"role": "user", "content": user_message} ], max_tokens=1500, temperature=0.2 # Low temp for precise JSON ) return response.choices[0].message.content except Exception as e: # detailed error logging for the UI error_msg = str(e) if "401" in error_msg: return "🔒 Authentication Error: Please check that you added 'HF_TOKEN' to your Space Secrets." elif "429" in error_msg: return "⏳ Rate Limit: The free model is busy. Please wait 1 minute and try again." elif "504" in error_msg: return "⏱️ Timeout: The code snippet might be too long. Try a shorter piece of code." else: return f"❌ System Error: {error_msg}" # UI Layout with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown( """ # ⚡ SEO & JSON-LD Generator (Authenticated) **Status:** ✅ Connected to Qwen 2.5 Coder """ ) with gr.Row(): with gr.Column(scale=1): input_type = gr.Radio(["python", "html"], label="Select File Type", value="python") code_input = gr.Code(language="python", label="Paste Code Here", lines=15) submit_btn = gr.Button("✨ Generate SEO Data", variant="primary", size="lg") with gr.Column(scale=1): # This component displays the result output_markdown = gr.Markdown(label="Results will appear here...") # Dynamic syntax highlighting input_type.change(lambda x: gr.Code(language=x), inputs=input_type, outputs=code_input) # Button Click Action submit_btn.click( fn=generate_seo, inputs=[code_input, input_type], outputs=output_markdown ) if __name__ == "__main__": demo.launch()