File size: 2,312 Bytes
c50b20c a9cdef6 9fe12e0 c50b20c 51306fe a9cdef6 51306fe a9cdef6 c8e781c c50b20c a9cdef6 51306fe a9cdef6 51306fe a9cdef6 51306fe a9cdef6 c8e781c a9cdef6 51306fe a9cdef6 51306fe a9cdef6 51306fe a9cdef6 c8e781c 51306fe 9fe12e0 c8e781c 9fe12e0 c8e781c 51306fe c8e781c 51306fe c8e781c 51306fe c8e781c a9cdef6 c50b20c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
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()
|