import gradio as gr import requests import json import os # --------------------------- # Hugging Face API Settings # --------------------------- HF_API_URL = "https://router.huggingface.co/v1/chat/completions" HF_API_TOKEN = os.environ.get("HF_TOKEN") if HF_API_TOKEN is None: raise ValueError("HF_TOKEN not found! Please add it as a secret in your Hugging Face Space.") headers = { "Authorization": f"Bearer {HF_API_TOKEN}", "Content-Type": "application/json" } # --------------------------- # Function to generate analogy with loading placeholder # --------------------------- def generate_analogy(topic, theme): # Immediately show loading text in the Textbox yield "⏳ Generating analogy...\nPlease wait." prompt = ( f"Explain the topic '{topic}' using an analogy themed around '{theme}'. " f"Use clear, beginner-friendly language. Include line breaks and short paragraphs " f"so it can be read in a Textbox." ) payload = { "model": "deepseek-ai/DeepSeek-V3.2:novita", "stream": False, "messages": [{"role": "user", "content": prompt}] } try: response = requests.post(HF_API_URL, headers=headers, data=json.dumps(payload)) data = response.json() # Preserve line breaks for Textbox text = data["choices"][0]["message"]["content"].replace("\r\n", "\n") yield text except Exception: yield "Error: Could not generate analogy." # --------------------------- # Gradio UI # --------------------------- themes = ["Love Island", "One Piece", "Spiderman", "Premier League"] with gr.Blocks() as demo: gr.Markdown("## Simple Analogy App") gr.Markdown("Turn any topic into a themed analogy!") with gr.Row(): topic_input = gr.Textbox(label="Enter any topic", placeholder="e.g. Quantum Physics") theme_input = gr.Dropdown(choices=themes, label="Choose a Theme") generate_button = gr.Button("Generate Analogy") output = gr.Textbox( label="Generated Analogy", value="", # always visible lines=20, max_lines=40 ) # Connect button to generator function generate_button.click( fn=generate_analogy, inputs=[topic_input, theme_input], outputs=output ) demo.launch()