File size: 1,506 Bytes
68385f9 9cb1768 68385f9 9cb1768 68385f9 a62cfd3 68385f9 a62cfd3 68385f9 | 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 | 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);
|