test / frontend /app.js
parthmax24's picture
Claude Opus 5
Serve custom UI at root, keeping Gradio as an invisible GPU engine
9cb1768
Raw History Blame Contribute Delete
1.51 kB
const promptEl = document.getElementById("prompt");
const outputEl = document.getElementById("output");
const runBtn = document.getElementById("run");
// Gradio 5 namespaces its REST API under /gradio_api; Gradio 4 serves it at
// the root. Try both so the frontend survives an SDK version bump.
const API_BASES = ["/gradio_api/call/infer", "/call/infer"];
async function startJob(data) {
for (const base of API_BASES) {
const res = await fetch(base, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data }),
});
if (res.ok) {
const { event_id } = await res.json();
return { base, event_id };
}
}
throw new Error("Gradio API endpoint not found");
}
async function generate() {
const prompt = promptEl.value.trim();
if (!prompt) return;
runBtn.disabled = true;
outputEl.textContent = "";
try {
const { base, event_id } = await startJob([prompt]);
const es = new EventSource(`${base}/${event_id}`);
es.addEventListener("message", (e) => {
const payload = JSON.parse(e.data);
outputEl.textContent = payload[0] ?? "";
});
es.addEventListener("complete", () => {
es.close();
runBtn.disabled = false;
});
es.addEventListener("error", () => {
es.close();
runBtn.disabled = false;
});
} catch (err) {
outputEl.textContent = `Error: ${err.message}`;
runBtn.disabled = false;
}
}
runBtn.addEventListener("click", generate);