Buckets:

gradio-pr-bot's picture
download
raw
53.4 kB
//#region \0rolldown/runtime.js var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => { if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, { get: ((e) => i[e]).bind(null, d), enumerable: !(s = n(i, d)) || s.enumerable }); return e; }, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", { value: n, enumerable: !0 }) : a, n)), l = "host", u = "queue/data", d = "queue/join", f = "upload", p = "login", m = "config", h = "info", g = "runtime", _ = "sleeptime", v = "heartbeat", ee = "component_server", te = "reset", ne = "cancel", y = "app_id", re = "This application is currently busy. Please try again. ", b = "Connection errored out. ", x = "Could not resolve app config. ", S = "Could not get space status. ", C = "Could not get API info. ", w = "Space metadata could not be loaded. ", T = "Invalid URL. A full URL path is required.", E = "Not authorized to access this space. ", D = "Invalid credentials. Could not login. ", ie = "Login credentials are required to access this space.", O = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", k = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, ae = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", oe = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", A = "File system access is only available in Node.js environments", j = "Root URL not found in client config", M = "Error uploading file"; //#endregion //#region src/helpers/init_helpers.ts async function N(e, t, n) { try { return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: { Authorization: `Bearer ${t}`, ...n ? { Cookie: n } : {} } })).json()).token || !1; } catch { return !1; } } function P(e) { e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client.")); } function F(e) { let t = {}; return e.forEach(({ api_name: e, id: n }) => { e && (t[e] = n); }), t; } function I(e, t) { let n = new URL(e, t), r = new URL(t); return n.hostname === r.hostname ? (n.protocol = r.protocol, n.host = r.host, n.toString().replace(/\/$/, "")) : e; } async function se(e, t = !0) { let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}; if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") { if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") { let t = W(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await L(await this.fetch(t, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !!this.options.auth); r.root = e || r.root, window.gradio_config = { ...r, current_page: window.gradio_config.current_page }; } let r = { ...window.gradio_config }; return r.root = I(r.root, location.href), r; } else if (e) { let t = W(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await L(await this.fetch(t, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !!this.options.auth); return r.root ||= e, r; } throw Error(x); } async function L(e, t) { if (e?.status === 401 && !t) { let t = null; try { t = await e.json(); } catch { throw Error(O); } let n = t?.detail?.auth_message; throw Error(n || "Login credentials are required to access this space."); } else if (e?.status === 401 && t) throw Error(D); if (e?.status === 200) { let t = await e.json(); return t.dependencies?.forEach((e, t) => { e.id === void 0 && (e.id = t); }), t; } else if (e?.status === 401) throw Error(E); throw Error(`${x}(received status ${e?.status} when fetching the app config)`); } async function ce() { let { http_protocol: e, host: t } = await U(this.app_reference, this.options.token); try { if (this.options.auth) { let n = await R(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials); n && this.set_cookies(n); } } catch (e) { throw Error(e.message); } } async function R(e, t, n, r, i, a) { let o = new FormData(); o.append("username", n?.[0]), o.append("password", n?.[1]); let s = {}; i && (s.Authorization = `Bearer ${i}`); let c = await r(`${e}//${t}/${p}`, { headers: s, method: "POST", body: o, credentials: a ?? "same-origin" }); if (c.status === 200) return c.headers.get("set-cookie"); throw c.status === 401 ? Error(D) : Error(w); } function z(e) { if (e.startsWith("http")) { let { protocol: t, host: n, pathname: r } = new URL(e); return { ws_protocol: t === "https:" ? "wss" : "ws", http_protocol: t, host: n + (r === "/" ? "" : r) }; } return { ws_protocol: "wss", http_protocol: "https:", host: new URL(e).host }; } var B = (e) => { let t = []; return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => { let [n, r] = e.split(";")[0].split("="); n && r && t.push(`${n.trim()}=${r.trim()}`); }), t; }, V = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, H = /.*hf\.space\/{0,1}.*$/; async function U(e, t) { let n = {}; t && (n.Authorization = `Bearer ${t}`); let r = e.trim().replace(/\/$/, ""); if (V.test(r)) { let e; try { e = await fetch(`https://huggingface.co/api/spaces/${r}/${l}`, { headers: n }); } catch { throw Error(w); } if (e.status === 401 || e.status === 404) throw Error(k(r, e.status)); let t; try { t = (await e.json()).host; } catch { throw Error(w); } if (!t) throw Error(w); return { space_id: r, ...z(t) }; } if (H.test(r)) { let { ws_protocol: e, http_protocol: t, host: n } = z(r); return { space_id: n.split("/")[0].replace(".hf.space", ""), ws_protocol: e, http_protocol: t, host: n }; } return { space_id: !1, ...z(r) }; } var W = (...e) => { try { return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString())); } catch { throw Error(T); } }; function G(e, t, n) { let r = { named_endpoints: {}, unnamed_endpoints: {} }; return Object.keys(e).forEach((i) => { (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => { let o = a?.parameters ?? [], s = a?.returns ?? [], c = t.dependencies.find((t) => t.api_name === e || t.api_name === e.replace("/", ""))?.id || n[e.replace("/", "")] || -1, l = c === -1 ? void 0 : t.dependencies.find((e) => e.id == c), u = c === -1 ? { generator: !1, cancel: !1 } : l?.types; if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) { let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type); try { e.forEach((e, t) => { e === "state" && o.splice(t, 0, { component: "state", example: null, parameter_default: null, parameter_has_default: !0, parameter_name: null, hidden: !0 }); }); } catch (e) { console.error(e); } } let d = (e, t, n, r) => ({ ...e, description: ue(e?.type, n), type: le(e?.type, t, n, r) || "" }); r[i][e] = { parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")), returns: s.map((e) => d(e, e?.component, e?.serializer, "return")), type: u }; })); }), r; } function le(e, t, n, r) { if (t === "Api") return e.type; switch (e?.type) { case "string": return "string"; case "boolean": return "boolean"; case "number": return "number"; } if (n === "JSONSerializable" || n === "StringSerializable") return "any"; if (n === "ListStringSerializable") return "string[]"; if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string"; if (n === "FileSerializable") return e?.type === "array" ? r === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : r === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}"; if (n === "GallerySerializable") return r === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"; } function ue(e, t) { return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description; } function de(e, t) { switch (e.msg) { case "send_data": return { type: "data" }; case "send_hash": return { type: "hash" }; case "queue_full": return { type: "update", status: { queue: !0, message: re, stage: "error", code: e.code, success: e.success } }; case "heartbeat": return { type: "heartbeat" }; case "unexpected_error": return { type: "unexpected_error", status: { queue: !0, message: e.message, session_not_found: e.session_not_found, stage: "error", success: !1 } }; case "broken_connection": return { type: "broken_connection", status: { queue: !0, message: e.message, stage: "error", success: !1 } }; case "estimation": return { type: "update", status: { queue: !0, stage: t || "pending", code: e.code, size: e.queue_size, position: e.rank, eta: e.rank_eta, success: e.success } }; case "progress": return { type: "update", status: { queue: !0, stage: "pending", code: e.code, progress_data: e.progress_data, success: e.success } }; case "log": return { type: "log", data: e }; case "process_generating": return { type: "generating", status: { queue: !0, message: e.success ? null : e.output.error, stage: e.success ? "generating" : "error", code: e.code, progress_data: e.progress_data, eta: e.average_duration, changed_state_ids: e.success ? e.output.changed_state_ids : void 0 }, data: e.success ? e.output : null }; case "process_streaming": return { type: "streaming", status: { queue: !0, message: e.output.error, stage: "streaming", time_limit: e.time_limit, code: e.code, progress_data: e.progress_data, changed_state_ids: e.output.changed_state_ids, eta: e.eta }, data: e.output }; case "process_completed": return "error" in e.output ? { type: "update", status: { queue: !0, title: e.output.title ?? "Error", message: e.output.error ?? "An error occurred", visible: e.output.visible, duration: e.output.duration, stage: "error", code: e.code, success: e.success } } : { type: "complete", status: { queue: !0, message: e.success ? void 0 : e.output.error, stage: e.success ? "complete" : "error", code: e.code, progress_data: e.progress_data, changed_state_ids: e.success ? e.output.changed_state_ids : void 0, used_cache: e.used_cache, cache_duration: e.cache_duration, avg_time: e.avg_time }, data: e.success ? e.output : null }; case "process_starts": return { type: "update", status: { queue: !0, stage: "pending", code: e.code, size: e.rank, position: 0, success: e.success, eta: e.eta }, original_msg: "process_starts" }; } return { type: "none", status: { stage: "error", queue: !0 } }; } var fe = (e = [], t) => { let n = t ? t.parameters : []; if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e; let r = [], i = Object.keys(e); return n.forEach((t, n) => { if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name]; else if (t.parameter_has_default) r[n] = t.parameter_default; else throw Error(`No value provided for required parameter: ${t.parameter_name}`); }), i.forEach((e) => { if (!n.some((t) => t.parameter_name === e)) throw Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`); }), r.forEach((e, t) => { if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`); }), r; }; //#endregion //#region src/utils/view_api.ts async function K() { if (this.api_info) return this.api_info; let { token: e } = this.options, { config: t } = this, n = {}; if (e && (n.Authorization = `Bearer ${e}`), t) try { let e, r; if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info; else { let i = W(t.root, this.api_prefix, h); if (e = await this.fetch(i, { headers: n, credentials: this.options.credentials ?? "same-origin" }), !e.ok) throw Error(b); r = await e.json(); } return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), G(r, t, this.api_map); } catch (e) { throw Error("Could not get API info. " + e.message); } } //#endregion //#region src/utils/upload_files.ts async function q(e, t, n) { let r = {}; this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`); let i = 1e3, a = [], o; for (let s = 0; s < t.length; s += i) { let c = t.slice(s, s + i), l = new FormData(); c.forEach((e) => { l.append("files", e); }); try { let t = n ? `${e}${this.api_prefix}/${f}?upload_id=${n}` : `${e}${this.api_prefix}/${f}`; o = await this.fetch(t, { method: "POST", body: l, headers: r, credentials: this.options.credentials ?? "same-origin" }); } catch (e) { throw Error(b + e.message); } if (!o.ok) { let e = await o.text(); return { error: `HTTP ${o.status}: ${e}` }; } let u = await o.json(); u && a.push(...u); } return { files: a }; } var pe = { si: { radix: 1e3, unit: [ "b", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb" ] }, iec: { radix: 1024, unit: [ "b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib" ] }, jedec: { radix: 1024, unit: [ "b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb" ] } }; function me(e, t = 1, n = "jedec") { e = Math.abs(e); let { radix: r, unit: i } = pe[n] || pe.jedec, a = 0; for (; e >= r;) e /= r, ++a; return `${e.toFixed(t)} ${i[a]}`; } //#endregion //#region src/upload.ts async function he(e, t, n, r) { let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity)); if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${me(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`); return await Promise.all(await this.upload_files(t, i, n).then(async (n) => { if (n.error) throw Error(n.error); return n.files ? n.files.map((n, r) => new J({ ...e[r], path: n, url: `${t}${this.api_prefix}/file=${n}` })) : []; })); } async function ge(e, t) { return e.map((e) => new J({ path: e.name, orig_name: e.name, blob: e, size: e.size, mime_type: e.type, is_stream: t })); } var J = class { path; url; orig_name; size; blob; is_stream; mime_type; alt_text; b64; meta = { _type: "gradio.FileData" }; constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) { this.path = e, this.url = t, this.orig_name = n, this.size = r, this.blob = t ? void 0 : i, this.is_stream = a, this.mime_type = o, this.alt_text = s, this.b64 = c; } }, _e = class { type; command; meta; fileData; constructor(e, t) { this.type = "command", this.command = e, this.meta = t; } }, ve = typeof process < "u" && process.versions && process.versions.node; function ye(e, t, n) { for (; n.length > 1;) { let t = n.shift(); if (typeof t == "string" || typeof t == "number") e = e[t]; else throw Error("Invalid key type"); } let r = n.shift(); if (typeof r == "string" || typeof r == "number") e[r] = t; else throw Error("Invalid key type"); } async function Y(e, t = void 0, n = [], r = !1, i = void 0) { if (Array.isArray(e)) { let a = []; return await Promise.all(e.map(async (o, s) => { let c = n.slice(); c.push(String(s)); let l = await Y(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i); a = a.concat(l); })), a; } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{ path: n, blob: e instanceof Blob ? e : new Blob([e]), type: t }]; else if (typeof e == "object" && e) { let t = []; for (let r of Object.keys(e)) { let a = [...n, r], o = e[r]; t = t.concat(await Y(o, void 0, a, !1, i)); } return t; } return []; } function be(e, t) { let n = t?.dependencies?.find((t) => t.id == e)?.queue; return n == null ? !t.enable_queue : !n; } function xe(e, t) { return new Promise((n, r) => { let i = new MessageChannel(); i.port1.onmessage = (({ data: e }) => { i.port1.close(), n(e); }), window.parent.postMessage(e, t, [i.port2]); }); } function Se(e) { if (typeof e == "string") { if (e.startsWith("http://") || e.startsWith("https://")) return { path: e, url: e, orig_name: e.split("/").pop() ?? "unknown", meta: { _type: "gradio.FileData" } }; if (ve) return new _e("upload_file", { path: e, name: e, orig_path: e }); } else if (typeof File < "u" && e instanceof File) return e; else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]); else if (e instanceof Blob) return e; throw Error("Invalid input: must be a URL, File, Blob, or Buffer object."); } function X(e, t, n, r, i = !1) { if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input."); if (r === "output" && i) return e; let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs; for (let t = 0; t < s.length; t++) { let r = s[t]; if (n.find((e) => e.id === r)?.type === "state") { if (i) if (e.length === s.length) { let t = e[o]; a.push(t), o++; } else a.push(null); else { o++; continue; } continue; } else { let t = e[o]; a.push(t), o++; } } return a; } //#endregion //#region src/utils/handle_blob.ts async function Ce(e, t, n) { let r = this; await we(r, t); let i = await Y(t, void 0, [], !0, n); return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => { if (!n) return { path: t, type: i }; let a = await r.upload_files(e, [n]); return { path: t, file_url: a.files && a.files[0], type: i, name: typeof File < "u" && n instanceof File ? n?.name : void 0 }; }))).forEach(({ path: e, file_url: n, type: r, name: i }) => { r === "Gallery" ? ye(t, n, e) : n && ye(t, new J({ path: n, orig_name: i }), e); }), t; } async function we(e, t) { if (!(e.config?.root || e.config?.root_url)) throw Error(j); await Te(e, t); } async function Te(e, t, n = []) { for (let r in t) t[r] instanceof _e ? await Ee(e, t, r) : typeof t[r] == "object" && t[r] !== null && await Te(e, t[r], [...n, r]); } async function Ee(e, t, n) { let r = t[n], i = e.config?.root || e.config?.root_url; if (!i) throw Error(j); try { let a, o; if (typeof process < "u" && process.versions && process.versions.node) { let e = await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1)); o = (await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1))).resolve(process.cwd(), r.meta.path), a = await e.readFile(o); } else throw Error(A); let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0]; u && (t[n] = new J({ path: u, orig_name: r.meta.name || "" })); } catch (e) { console.error(M, e); } } //#endregion //#region src/utils/post_data.ts async function De(e, t, n) { let r = { "Content-Type": "application/json" }; this.options.token && (r.Authorization = `Bearer ${this.options.token}`); try { var i = await this.fetch(e, { method: "POST", body: JSON.stringify(t), headers: { ...r, ...n }, credentials: this.options.credentials ?? "same-origin" }); } catch { return [{ error: b }, 500]; } let a, o; try { a = await i.json(), o = i.status; } catch (e) { a = { error: `Could not parse server response: ${e}` }, o = 500; } return [a, o]; } //#endregion //#region src/utils/predict.ts async function Oe(e, t = {}) { let n = !1, r = !1; if (!this.config) throw Error("Could not resolve app config"); if (typeof e == "number") this.config.dependencies.find((t) => t.id == e); else { let t = e.replace(/^\//, ""); this.config.dependencies.find((e) => e.id == this.api_map[t]); } let i = this.submit(e, t, null, null, !0), a; for await (let e of i) { if (e.type === "data" && (n = !0, a = e, r)) return a; if (e.type === "status") { if (e.stage === "error") { let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction."); throw Object.assign(r, n), r; } if (e.stage === "complete" && (r = !0, n)) return a; } } return a; } //#endregion //#region src/helpers/spaces.ts async function Z(e, t, n) { let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a; try { if (i = await fetch(r), a = i.status, a !== 200) throw Error(); i = await i.json(); } catch { n({ status: "error", load_status: "error", message: S, detail: "NOT_FOUND" }); return; } if (!i || a !== 200) return; let { runtime: { stage: o }, id: s } = i; switch (o) { case "STOPPED": case "SLEEPING": n({ status: "sleeping", load_status: "pending", message: "Space is asleep. Waking it up...", detail: o }), setTimeout(() => { Z(e, t, n); }, 1e3); break; case "PAUSED": n({ status: "paused", load_status: "error", message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", detail: o, discussions_enabled: await je(s) }); break; case "RUNNING": case "RUNNING_BUILDING": n({ status: "running", load_status: "complete", message: "Space is running.", detail: o }); break; case "BUILDING": n({ status: "building", load_status: "pending", message: "Space is building...", detail: o }), setTimeout(() => { Z(e, t, n); }, 1e3); break; case "APP_STARTING": n({ status: "starting", load_status: "pending", message: "Space is starting...", detail: o }), setTimeout(() => { Z(e, t, n); }, 1e3); break; default: n({ status: "space_error", load_status: "error", message: "This space is experiencing an issue.", detail: o, discussions_enabled: await je(s) }); break; } } var ke = async (e, t) => { let n = 0; return new Promise((r) => { Z(e, V.test(e) ? "space_name" : "subdomain", (i) => { t(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (n < 12 ? (n++, setTimeout(() => { ke(e, t).then(r); }, 5e3)) : r()); }); }); }, Ae = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; async function je(e) { try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message"); return !(!t.ok || n && Ae.test(n)); } catch { return !1; } } async function Me(e, t) { let n = {}; t && (n.Authorization = `Bearer ${t}`); try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/${g}`, { headers: n }); if (t.status !== 200) throw Error("Space hardware could not be obtained."); let { hardware: r } = await t.json(); return r.current; } catch (e) { throw Error(e.message); } } async function Ne(e, t, n) { let r = {}; n && (r.Authorization = `Bearer ${n}`); let i = { seconds: t }; try { let t = await fetch(`https://huggingface.co/api/spaces/${e}/${_}`, { method: "POST", headers: { "Content-Type": "application/json", ...r }, body: JSON.stringify(i) }); if (t.status !== 200) throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."); return await t.json(); } catch (e) { throw Error(e.message); } } var Pe = [ "cpu-basic", "cpu-upgrade", "cpu-xl", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a10g-largex2", "a10g-largex4", "a100-large", "zero-a10g", "h100", "h100x8" ]; //#endregion //#region src/utils/duplicate.ts async function Fe(e, t) { P(t); let { token: n, private: r, hardware: i, timeout: a, auth: o } = t; if (i && !Pe.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${Pe.map((e) => `"${e}"`).join(",")}.`); let { http_protocol: s, host: c } = await U(e, n), l = null; if (o) { let e = await R(s, c, o, fetch, void 0, t.credentials); e && (l = B(e)); } let u = { Authorization: `Bearer ${n}`, "Content-Type": "application/json", ...l ? { Cookie: l.join("; ") } : {} }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` }; r && (p.private = !0); let m; try { i || (m = await Me(e, n)); } catch (e) { throw Error(w + e.message); } p.hardware = i || m || "cpu-basic"; try { let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, { method: "POST", headers: u, body: JSON.stringify(p) }); if (r.status === 409) try { return await $.connect(`${d}/${f}`, t); } catch (e) { throw console.error("Failed to connect Client instance:", e), e; } else if (r.status !== 200) throw Error(r.statusText); let i = await r.json(); return await Ne(`${d}/${f}`, a || 300, n), await $.connect(Ie(i.url), t); } catch (e) { throw Error(e); } } function Ie(e) { let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/); if (t) return t[1]; } //#endregion //#region src/helpers/zerogpu.ts var Le = "supports-zerogpu-headers", Re = !1; function ze() { return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function"; } function Be(e) { return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null; } function Ve() { if (!ze() || Re) return; window.addEventListener("message", (e) => { e.data === Le && (window.supports_zerogpu_headers = !0); }), Re = !0; let e = Be(window.location.hostname); e && window.parent !== window && window.parent.postMessage(Le, e); } //#endregion //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/deps/jsr.io/@std/streams/0.221.0/text_line_stream.js var He = class extends TransformStream { #e = ""; constructor(e = { allowCR: !1 }) { super({ transform: (t, n) => { for (t = this.#e + t;;) { let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1; if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) { n.enqueue(t.slice(0, i)), t = t.slice(i + 1); continue; } if (r === -1) break; let a = t[r - 1] === "\r" ? r - 1 : r; n.enqueue(t.slice(0, a)), t = t.slice(r + 1); } this.#e = t; }, flush: (t) => { if (this.#e === "") return; let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e; t.enqueue(n); } }); } }; //#endregion //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.js function Ue(e) { let t = new TextDecoderStream(), n = new He({ allowCR: !0 }); return e.pipeThrough(t).pipeThrough(n); } function We(e) { let t = /[:]\s*/.exec(e), n = t && t.index; if (n) return [e.substring(0, n), e.substring(n + t[0].length)]; } function Ge(e, t, n) { e.get(t) || e.set(t, n); } //#endregion //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.js async function* Ke(e, t) { if (!e.body) return; let n = Ue(e.body), r, i = n.getReader(), a; for (;;) { if (t && t.aborted) return i.cancel(); if (r = await i.read(), r.done) return; if (!r.value) { a && (yield a), a = void 0; continue; } let [e, n] = We(r.value) || []; e === "data" ? (a ||= {}, a[e] = a[e] ? a[e] + "\n" + n : n) : e === "event" ? (a ||= {}, a[e] = n) : e === "id" ? (a ||= {}, a[e] = String(+n) === n ? +n : n) : e === "retry" && (a ||= {}, a[e] = +n || void 0); } } async function qe(e, t) { let n = new Request(e, t); Ge(n.headers, "Accept", "text/event-stream"), Ge(n.headers, "Content-Type", "application/json"); let r = await fetch(n); if (!r.ok) throw r; return Ke(r, n.signal); } //#endregion //#region src/utils/stream.ts async function Je() { let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this; if (!i) throw Error("Could not resolve app config"); r.open = !0; let s = null, c = new URLSearchParams({ session_hash: this.session_hash }).toString(), l = new URL(`${i.root}${this.api_prefix}/${u}?${c}`); if (a && l.searchParams.set("__sign", a), s = this.stream(l), !s) { console.warn("Cannot connect to SSE endpoint: " + l.toString()); return; } s.onmessage = async function(a) { let s = JSON.parse(a.data); if (s.msg === "close_stream") { Q(r, o.abort_controller); return; } let c = s.event_id; if (!c) await Promise.all(Object.keys(e).map((t) => e[t](s))); else if (e[c] && i) { s.msg === "process_completed" && [ "sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3" ].includes(i.protocol) && t.delete(c); let n = e[c]; typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, s) : n(s); } else n[c] || (n[c] = []), n[c].push(s); }, s.onerror = async function(t) { console.error(t), await Promise.all(Object.keys(e).map((t) => e[t]({ msg: "broken_connection", message: b }))); }; } function Q(e, t) { e && (e.open = !1, t?.abort()); } function Ye(e, t, n) { e[t] ? n.data.forEach((r, i) => { let a = Xe(i < e[t].length ? e[t][i] : null, r); e[t][i] = a, n.data[i] = a; }) : (e[t] = [], n.data.forEach((n, r) => { e[t][r] = n; })); } function Xe(e, t) { return t.forEach(([t, n, r]) => { e = Ze(e, n, t, r); }), e; } function Ze(e, t, n, r) { if (t.length === 0) { if (n === "replace") return r; if (n === "append") return e + r; throw Error(`Unsupported action: ${n}`); } let i = e; for (let e = 0; e < t.length - 1; e++) i = i[t[e]]; let a = t[t.length - 1]; switch (n) { case "replace": i[a] = r; break; case "append": i[a] += r; break; case "add": Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r; break; case "delete": Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a]; break; default: throw Error(`Unknown action: ${n}`); } return e; } function Qe(e, t = {}) { let n = { close: () => { console.warn("Method not implemented."); }, onerror: null, onmessage: null, onopen: null, readyState: 0, url: e.toString(), withCredentials: !1, CONNECTING: 0, OPEN: 1, CLOSED: 2, addEventListener: () => { throw Error("Method not implemented."); }, dispatchEvent: () => { throw Error("Method not implemented."); }, removeEventListener: () => { throw Error("Method not implemented."); } }; return qe(e, t).then(async (e) => { n.readyState = n.OPEN; try { for await (let t of e) n.onmessage && n.onmessage(t); n.readyState = n.CLOSED; } catch (e) { n.onerror && n.onerror(e), n.readyState = n.CLOSED; } }).catch((e) => { console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED; }), n; } //#endregion //#region src/utils/submit.ts function $e(e, t = {}, n, r, i, a) { try { let { token: o } = this.options, { fetch: s, app_reference: c, config: l, session_hash: f, api_info: p, api_map: m, stream_status: h, pending_stream_messages: g, pending_diff_streams: _, event_callbacks: v, unclosed_events: ee, post_data: y, options: x, api_prefix: S } = this, C = a || { "x-gradio-user": "api" }, w = this; if (!p) throw Error(ae); if (!l) throw Error("Could not resolve app config"); let { fn_index: T, endpoint_info: E, dependency: D } = tt(p, e, m, l), ie = fe(t, E), O, k = l.protocol ?? "ws"; if (k === "ws") throw Error(oe); let A = "", j = typeof e == "number" ? "/predict" : e, M, N = null, P = !1, F = {}, I = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", se = x?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {}; function L(e) { (i || se[e.type]) && ue(e); } async function ce() { let e = {}, t = {}; e = { event_id: N }, t = { event_id: N, session_hash: f, fn_index: T }; try { if (!l) throw Error("Could not resolve app config"); "event_id" in t && await s(`${l.root}${S}/${ne}`, { headers: { "Content-Type": "application/json" }, method: "POST", body: JSON.stringify(t) }), await s(`${l.root}${S}/${te}`, { headers: { "Content-Type": "application/json" }, method: "POST", body: JSON.stringify(e) }); } catch { console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."); } } let R = async (e) => { await this._resolve_heartbeat(e); }; async function z(e) { if (!l) return; let t = e.render_id; l.components = [...l.components.filter((e) => e.props.rendered_in !== t), ...e.components], l.dependencies = [...l.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies]; let n = l.components.some((e) => e.type === "state"), r = l.dependencies.some((e) => e.targets.some((e) => e[1] === "unload")); l.connect_heartbeat = n || r, await R(l), L({ type: "render", data: e, endpoint: j, fn_index: T }); } let B = this.handle_blob(l.root, ie, E).then(async (e) => { if (M = { data: X(e, D, l.components, "input", !0) || [], event_data: n, fn_index: T, trigger_id: r }, be(T, l)) L({ type: "status", endpoint: j, stage: "pending", queue: !1, fn_index: T, time: /* @__PURE__ */ new Date() }), y(`${l.root}${S}/run${j.startsWith("/") ? j : `/${j}`}${I ? "?" + I : ""}`, { ...M, session_hash: f }, C).then(async ([e, t]) => { let i = e.data; if (t == 200) L({ type: "data", endpoint: j, fn_index: T, data: X(i, D, l.components, "output", x.with_null_state), time: /* @__PURE__ */ new Date(), event_data: n, trigger_id: r }), e.render_config && await z(e.render_config), L({ type: "status", endpoint: j, fn_index: T, stage: "complete", eta: e.average_duration, queue: !1, time: /* @__PURE__ */ new Date() }); else { let t = e?.error === b; L({ type: "status", stage: "error", endpoint: j, fn_index: T, message: e.error, broken: t, queue: !1, time: /* @__PURE__ */ new Date() }); } }).catch((e) => { L({ type: "status", stage: "error", message: e.message, endpoint: j, fn_index: T, queue: !1, time: /* @__PURE__ */ new Date() }); }); else if (k == "sse") { L({ type: "status", stage: "pending", queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date() }); var t = new URLSearchParams({ fn_index: T.toString(), session_hash: f }).toString(); let e = new URL(`${l.root}${S}/${u}?${I ? I + "&" : ""}${t}`); if (this.jwt && e.searchParams.set("__sign", this.jwt), O = this.stream(e), !O) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString())); O.onmessage = async function(e) { let { type: t, status: i, data: a } = de(JSON.parse(e.data), F[T]); if (t === "update" && i && !P) L({ type: "status", endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date(), ...i }), i.stage === "error" && (O?.close(), W()); else if (t === "data") { let [e, t] = await y(`${l.root}${S}/queue/data`, { ...M, session_hash: f, event_id: N }); t !== 200 && (L({ type: "status", stage: "error", message: b, queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date() }), O?.close(), W()); } else t === "complete" ? P = i : t === "log" ? L({ type: "log", title: a.title, log: a.log, level: a.level, endpoint: j, duration: a.duration, visible: a.visible, fn_index: T }) : (t === "generating" || t === "streaming") && L({ type: "status", time: /* @__PURE__ */ new Date(), ...i, stage: i?.stage, queue: !0, endpoint: j, fn_index: T }); a && (L({ type: "data", time: /* @__PURE__ */ new Date(), data: X(a.data, D, l.components, "output", x.with_null_state), endpoint: j, fn_index: T, event_data: n, trigger_id: r }), P && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...P, stage: i?.stage, queue: !0, endpoint: j, fn_index: T }), O?.close(), W())); }; } else if (k == "sse_v1" || k == "sse_v2" || k == "sse_v2.1" || k == "sse_v3") { L({ type: "status", stage: "pending", queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date() }); let e = ""; typeof window < "u" && typeof document < "u" && (e = window?.location?.hostname); let t = Be(e); return (typeof window < "u" && typeof document < "u" && window.parent != window && t && window.supports_zerogpu_headers ? xe("zerogpu-headers", t) : Promise.resolve(null)).then((e) => { let t = { ...C, ...e || {} }; return y(`${l.root}${S}/${d}?${I}`, { ...M, session_hash: f }, t); }).then(async ([e, t]) => { if (e.event_id && (A = e.event_id), t === 503) L({ type: "status", stage: "error", message: re, queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date(), visible: !0 }), W(); else if (t === 422) L({ type: "status", stage: "error", message: e.detail, queue: !0, endpoint: j, fn_index: T, code: "validation_error", time: /* @__PURE__ */ new Date(), visible: !0 }), W(); else if (t !== 200) { let t = e?.error === b; L({ type: "status", stage: "error", broken: t, message: t ? b : e.detail || e.error, queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date(), visible: !0 }), W(); } else { N = e.event_id, A = N; let t = async function(e) { try { let { type: t, status: n, data: r, original_msg: i } = de(e, F[T]); if (t == "heartbeat") return; if (t === "update" && n && !P) L({ type: "status", endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date(), original_msg: i, ...n }); else if (t === "complete") P = n; else if (t == "unexpected_error" || t == "broken_connection") { console.error("Unexpected error", n?.message); let e = t === "broken_connection"; L({ type: "status", stage: "error", message: n?.message || "An Unexpected Error Occurred!", queue: !0, endpoint: j, broken: e, session_not_found: n?.session_not_found, fn_index: T, time: /* @__PURE__ */ new Date() }); } else if (t === "log") { L({ type: "log", title: r.title, log: r.log, level: r.level, endpoint: j, duration: r.duration, visible: r.visible, fn_index: T }); return; } else (t === "generating" || t === "streaming") && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...n, stage: n?.stage, queue: !0, endpoint: j, fn_index: T }), r && D.connection !== "stream" && [ "sse_v2", "sse_v2.1", "sse_v3" ].includes(k) && Ye(_, N, r)); r && (L({ type: "data", time: /* @__PURE__ */ new Date(), data: X(r.data, D, l.components, "output", x.with_null_state), endpoint: j, fn_index: T }), r.render_config && await z(r.render_config), P && (L({ type: "status", time: /* @__PURE__ */ new Date(), ...P, stage: n?.stage, queue: !0, endpoint: j, fn_index: T }), W())), (n?.stage === "complete" || n?.stage === "error") && (v[N] && delete v[N], N in _ && delete _[N], W()); } catch (e) { console.error("Unexpected client exception", e), L({ type: "status", stage: "error", message: "An Unexpected Error Occurred!", queue: !0, endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date() }), [ "sse_v2", "sse_v2.1", "sse_v3" ].includes(k) && (Q(h, w.abort_controller), h.open = !1, W()); } }; N in g && (g[N].forEach((e) => t(e)), delete g[N]), v[N] = t, ee.add(N), h.open || await this.open_stream(); } }); } }); B.catch((e) => { L({ type: "status", stage: "error", message: e instanceof Error ? e.message : String(e), queue: !be(T, l), endpoint: j, fn_index: T, time: /* @__PURE__ */ new Date() }), W(); }); let V = !1, H = [], U = []; function W() { for (V = !0; U.length > 0;) U.shift()({ value: void 0, done: !0 }); } function G(e) { U.length > 0 ? U.shift()(e) : H.push(e); } function le(e) { G(et(e)), W(); } function ue(e) { G({ value: e, done: !1 }); } function K() { return H.length > 0 ? Promise.resolve(H.shift()) : V ? Promise.resolve({ value: void 0, done: !0 }) : new Promise((e) => U.push(e)); } let q = { [Symbol.asyncIterator]: () => q, next: K, throw: async (e) => (le(e), K()), return: async () => (W(), { value: void 0, done: !0 }), cancel: ce, send_chunk: (e) => { this.post_data(`${l.root}${S}/stream/${A}`, { ...e, session_hash: this.session_hash }); }, close_stream: () => { this.post_data(`${l.root}${S}/stream/${A}/close`, {}), W(); }, event_id: () => A, wait_for_id: async () => (await B, N) }; return q; } catch (e) { throw console.error("Submit function encountered an error:", e), e; } } function et(e) { return { then: (t, n) => n(e) }; } function tt(e, t, n, r) { let i, a, o; if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t); else { let s = t.replace(/^\//, ""); i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]); } if (typeof i != "number" || !o) { let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", "); throw Error(`No endpoint matching ${JSON.stringify(t)} was found. ` + (e ? `Valid named endpoints are: ${e}. ` : "This app exposes no named endpoints. ") + "An fn_index (number) of an existing dependency can also be used."); } return { fn_index: i, endpoint_info: a, dependency: o }; } //#endregion //#region src/client.ts var $ = class { app_reference; options; deep_link = null; config; api_prefix = ""; api_info; api_map = {}; session_hash = Math.random().toString(36).substring(2); jwt = !1; last_status = {}; cookies = null; stream_status = { open: !1 }; closed = !1; pending_stream_messages = {}; pending_diff_streams = {}; event_callbacks = {}; unclosed_events = /* @__PURE__ */ new Set(); heartbeat_event = null; abort_controller = null; stream_instance = null; current_payload; get_url_config(e = null) { if (!this.config) throw Error(x); e === null && (e = window.location.href); let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i; return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i); } get_page_config(e) { if (!this.config) throw Error(x); let t = this.config; return e in t.page || (e = ""), { ...t, current_page: e, layout: t.page[e].layout, components: t.components.filter((n) => t.page[e].components.includes(n.id)), dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id)) }; } fetch(e, t) { let n = new Headers(t?.headers || {}); return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { n.append(t, e); }), fetch(e, { ...t, headers: n }); } stream(e) { let t = new Headers(); return this && this.cookies && t.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, n) => { t.append(n, e); }), this && this.options.token && t.append("Authorization", `Bearer ${this.options.token}`), this.abort_controller = new AbortController(), this.stream_instance = Qe(e.toString(), { credentials: this.options.credentials ?? "same-origin", headers: t, signal: this.abort_controller.signal }), this.stream_instance; } view_api; upload_files; upload; handle_blob; post_data; submit; predict; open_stream; resolve_config; resolve_cookies; constructor(e, t = { events: ["data"] }) { this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, t.events ||= ["data"], P(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = K.bind(this), this.upload_files = q.bind(this), this.handle_blob = Ce.bind(this), this.post_data = De.bind(this), this.submit = $e.bind(this), this.predict = Oe.bind(this), this.open_stream = Je.bind(this), this.resolve_config = se.bind(this), this.resolve_cookies = ce.bind(this), this.upload = he.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this); } async init() { Ve(), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then((e) => e?.config && this._resolve_heartbeat(e.config)); try { this.api_info = await this.view_api(); } catch (e) { console.error(e.message); } this.api_map = F(this.config?.dependencies || []); } async _resolve_heartbeat(e) { if (e && (this.config = e, this.api_prefix = e.api_prefix || "", this.config && this.config.connect_heartbeat && this.config.space_id && this.options.token && (this.jwt = await N(this.config.space_id, this.options.token, this.cookies))), e.space_id && this.options.token && (this.jwt = await N(e.space_id, this.options.token)), this.config && this.config.connect_heartbeat) { let e = new URL(`${this.config.root}${this.api_prefix}/${v}/${this.session_hash}`); this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_event ||= this.stream(e); } } static async connect(e, t = { events: ["data"] }) { let n = new this(e, t); return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n; } async reconnect() { let e = new URL(`${this.config.root}${this.api_prefix}/${y}`), t; try { let n = await this.fetch(e); if (!n.ok) throw Error(); t = (await n.json()).app_id; } catch { return "broken"; } return t === this.config.app_id ? "connected" : "changed"; } close() { this.closed = !0, Q(this.stream_status, this.abort_controller); } async refresh() { if (!this.config) throw Error(x); let e = await this.resolve_config(this.config.root, !1); if (!e) throw Error(x); this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = F(e.dependencies || []); try { this.api_info = await this.view_api(); } catch (e) { console.error(C + e.message); } return this.get_url_config(); } set_current_payload(e) { this.current_payload = e; } static async duplicate(e, t = { events: ["data"] }) { return Fe(e, t); } async _resolve_config() { let { http_protocol: e, host: t, space_id: n } = await U(this.app_reference, this.options.token), { status_callback: r } = this.options; n && r && await ke(n, r); let i; try { let n = `${e}//${t}`; if (i = await this.resolve_config(n), !i) throw Error(x); return this.config_success(i); } catch (e) { if (n && r) Z(n, V.test(n) ? "space_name" : "subdomain", this.handle_space_success); else throw r && r({ status: "error", message: "Could not load this space.", load_status: "error", detail: "NOT_FOUND" }), e instanceof Error ? e : Error(String(e)); } } async config_success(e) { if (this.config = e, this.api_prefix = e.api_prefix || "", this.config.auth_required) return this.prepare_return_obj(); try { this.api_info = await this.view_api(); } catch (e) { console.error(C + e.message); } return this.prepare_return_obj(); } async handle_space_success(e) { if (!this) throw Error(x); let { status_callback: t } = this.options; if (t && t(e), e.status === "running") try { if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(x); return await this.config_success(this.config); } catch (e) { throw t && t({ status: "error", message: "Could not load this space.", load_status: "error", detail: "NOT_FOUND" }), e; } } async component_server(e, t, n) { if (!this.config) throw Error(x); let r = {}, { token: i } = this.options, { session_hash: a } = this; i && (r.Authorization = `Bearer ${this.options.token}`); let o, s = this.config.components.find((t) => t.id === e); o = s?.props?.root_url ? s.props.root_url : this.config.root; let c; if (typeof n == "object" && n && "binary" in n) { let r = n; c = new FormData(); for (let e in r.data) e !== "binary" && c.append(e, r.data[e]); c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a); } else c = JSON.stringify({ data: n, component_id: e, fn_name: t, session_hash: a }), r["Content-Type"] = "application/json"; i && (r.Authorization = `Bearer ${i}`); try { let e = await this.fetch(`${o}${this.api_prefix}/${ee}/`, { method: "POST", body: c, headers: r, credentials: this.options.credentials ?? "same-origin" }); if (!e.ok) throw Error("Could not connect to component server: " + e.statusText); return await e.json(); } catch (e) { console.warn(e); } } set_cookies(e) { this.cookies = B(e).join("; "); } prepare_return_obj() { return { config: this.config, predict: this.predict, submit: this.submit, view_api: this.view_api, component_server: this.component_server }; } }; async function nt(e, t = { events: ["data"] }) { return await $.connect(e, t); } async function rt(e, t) { return await $.duplicate(e, t); } //#endregion export { $ as Client, J as FileData, ie as MISSING_CREDENTIALS_MSG, nt as client, rt as duplicate, Se as handle_file, Oe as predict, ge as prepare_files, $e as submit, o as t, he as upload, q as upload_files };
//#region \0rolldown/runtime.js
var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => {
if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
get: ((e) => i[e]).bind(null, d),
enumerable: !(s = n(i, d)) || s.enumerable
});
return e;
}, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", {
value: n,
enumerable: !0
}) : a, n)), l = "host", u = "queue/data", d = "queue/join", f = "upload", p = "login", m = "config", h = "info", g = "runtime", _ = "sleeptime", v = "heartbeat", ee = "component_server", te = "reset", ne = "cancel", y = "app_id", re = "This application is currently busy. Please try again. ", b = "Connection errored out. ", x = "Could not resolve app config. ", S = "Could not get space status. ", C = "Could not get API info. ", w = "Space metadata could not be loaded. ", T = "Invalid URL. A full URL path is required.", E = "Not authorized to access this space. ", D = "Invalid credentials. Could not login. ", ie = "Login credentials are required to access this space.", O = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", k = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, ae = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", oe = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", A = "File system access is only available in Node.js environments", j = "Root URL not found in client config", M = "Error uploading file";
//#endregion
//#region src/helpers/init_helpers.ts
async function N(e, t, n) {
try {
return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: {
Authorization: `Bearer ${t}`,
...n ? { Cookie: n } : {}
} })).json()).token || !1;
} catch {
return !1;
}
}
function P(e) {
e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."));
}
function F(e) {
let t = {};
return e.forEach(({ api_name: e, id: n }) => {
e && (t[e] = n);
}), t;
}
function I(e, t) {
let n = new URL(e, t), r = new URL(t);
return n.hostname === r.hostname ? (n.protocol = r.protocol, n.host = r.host, n.toString().replace(/\/$/, "")) : e;
}
async function se(e, t = !0) {
let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {};
if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") {
if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") {
let t = W(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await L(await this.fetch(t, {
headers: n,
credentials: this.options.credentials ?? "same-origin"
}), !!this.options.auth);
r.root = e || r.root, window.gradio_config = {
...r,
current_page: window.gradio_config.current_page
};
}
let r = { ...window.gradio_config };
return r.root = I(r.root, location.href), r;
} else if (e) {
let t = W(e, this.deep_link ? m + "?deep_link=" + this.deep_link : m), r = await L(await this.fetch(t, {
headers: n,
credentials: this.options.credentials ?? "same-origin"
}), !!this.options.auth);
return r.root ||= e, r;
}
throw Error(x);
}
async function L(e, t) {
if (e?.status === 401 && !t) {
let t = null;
try {
t = await e.json();
} catch {
throw Error(O);
}
let n = t?.detail?.auth_message;
throw Error(n || "Login credentials are required to access this space.");
} else if (e?.status === 401 && t) throw Error(D);
if (e?.status === 200) {
let t = await e.json();
return t.dependencies?.forEach((e, t) => {
e.id === void 0 && (e.id = t);
}), t;
} else if (e?.status === 401) throw Error(E);
throw Error(`${x}(received status ${e?.status} when fetching the app config)`);
}
async function ce() {
let { http_protocol: e, host: t } = await U(this.app_reference, this.options.token);
try {
if (this.options.auth) {
let n = await R(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials);
n && this.set_cookies(n);
}
} catch (e) {
throw Error(e.message);
}
}
async function R(e, t, n, r, i, a) {
let o = new FormData();
o.append("username", n?.[0]), o.append("password", n?.[1]);
let s = {};
i && (s.Authorization = `Bearer ${i}`);
let c = await r(`${e}//${t}/${p}`, {
headers: s,
method: "POST",
body: o,
credentials: a ?? "same-origin"

Xet Storage Details

Size:
53.4 kB
·
Xet hash:
ba36443ec8a6bb85029b326afe5b3d17719dc95812de5c92eba602989a41fbdc

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.