@gradio/client 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1080 @@
1
+ var fn = new Intl.Collator(0, { numeric: 1 }).compare;
2
+ function semiver(a, b, bool) {
3
+ a = a.split(".");
4
+ b = b.split(".");
5
+ return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1);
6
+ }
7
+ function determine_protocol(endpoint) {
8
+ if (endpoint.startsWith("http")) {
9
+ const { protocol, host } = new URL(endpoint);
10
+ if (host.endsWith("hf.space")) {
11
+ return {
12
+ ws_protocol: "wss",
13
+ host,
14
+ http_protocol: protocol
15
+ };
16
+ } else {
17
+ return {
18
+ ws_protocol: protocol === "https:" ? "wss" : "ws",
19
+ http_protocol: protocol,
20
+ host
21
+ };
22
+ }
23
+ }
24
+ return {
25
+ ws_protocol: "wss",
26
+ http_protocol: "https:",
27
+ host: endpoint
28
+ };
29
+ }
30
+ const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
31
+ const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
32
+ async function process_endpoint(app_reference, token) {
33
+ const headers = {};
34
+ if (token) {
35
+ headers.Authorization = `Bearer ${token}`;
36
+ }
37
+ const _app_reference = app_reference.trim();
38
+ if (RE_SPACE_NAME.test(_app_reference)) {
39
+ try {
40
+ const res = await fetch(
41
+ `https://huggingface.co/api/spaces/${_app_reference}/host`,
42
+ { headers }
43
+ );
44
+ if (res.status !== 200)
45
+ throw new Error("Space metadata could not be loaded.");
46
+ const _host = (await res.json()).host;
47
+ return {
48
+ space_id: app_reference,
49
+ ...determine_protocol(_host)
50
+ };
51
+ } catch (e) {
52
+ throw new Error("Space metadata could not be loaded." + e.message);
53
+ }
54
+ }
55
+ if (RE_SPACE_DOMAIN.test(_app_reference)) {
56
+ const { ws_protocol, http_protocol, host } = determine_protocol(_app_reference);
57
+ return {
58
+ space_id: host.replace(".hf.space", ""),
59
+ ws_protocol,
60
+ http_protocol,
61
+ host
62
+ };
63
+ }
64
+ return {
65
+ space_id: false,
66
+ ...determine_protocol(_app_reference)
67
+ };
68
+ }
69
+ function map_names_to_ids(fns) {
70
+ let apis = {};
71
+ fns.forEach(({ api_name }, i) => {
72
+ if (api_name)
73
+ apis[api_name] = i;
74
+ });
75
+ return apis;
76
+ }
77
+ const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
78
+ async function discussions_enabled(space_id) {
79
+ try {
80
+ const r = await fetch(
81
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
82
+ {
83
+ method: "HEAD"
84
+ }
85
+ );
86
+ const error = r.headers.get("x-error-message");
87
+ if (error && RE_DISABLED_DISCUSSION.test(error))
88
+ return false;
89
+ else
90
+ return true;
91
+ } catch (e) {
92
+ return false;
93
+ }
94
+ }
95
+ async function get_space_hardware(space_id, token) {
96
+ const headers = {};
97
+ if (token) {
98
+ headers.Authorization = `Bearer ${token}`;
99
+ }
100
+ try {
101
+ const res = await fetch(
102
+ `https://huggingface.co/api/spaces/${space_id}/runtime`,
103
+ { headers }
104
+ );
105
+ if (res.status !== 200)
106
+ throw new Error("Space hardware could not be obtained.");
107
+ const { hardware } = await res.json();
108
+ return hardware;
109
+ } catch (e) {
110
+ throw new Error(e.message);
111
+ }
112
+ }
113
+ async function set_space_hardware(space_id, new_hardware, token) {
114
+ const headers = {};
115
+ if (token) {
116
+ headers.Authorization = `Bearer ${token}`;
117
+ }
118
+ try {
119
+ const res = await fetch(
120
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
121
+ { headers, body: JSON.stringify(new_hardware) }
122
+ );
123
+ if (res.status !== 200)
124
+ throw new Error(
125
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
126
+ );
127
+ const { hardware } = await res.json();
128
+ return hardware;
129
+ } catch (e) {
130
+ throw new Error(e.message);
131
+ }
132
+ }
133
+ async function set_space_timeout(space_id, timeout, token) {
134
+ const headers = {};
135
+ if (token) {
136
+ headers.Authorization = `Bearer ${token}`;
137
+ }
138
+ try {
139
+ const res = await fetch(
140
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
141
+ { headers, body: JSON.stringify({ seconds: timeout }) }
142
+ );
143
+ if (res.status !== 200)
144
+ throw new Error(
145
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
146
+ );
147
+ const { hardware } = await res.json();
148
+ return hardware;
149
+ } catch (e) {
150
+ throw new Error(e.message);
151
+ }
152
+ }
153
+ const hardware_types = [
154
+ "cpu-basic",
155
+ "cpu-upgrade",
156
+ "t4-small",
157
+ "t4-medium",
158
+ "a10g-small",
159
+ "a10g-large",
160
+ "a100-large"
161
+ ];
162
+ const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
163
+ const BROKEN_CONNECTION_MSG = "Connection errored out.";
164
+ async function post_data(url, body, token) {
165
+ const headers = { "Content-Type": "application/json" };
166
+ if (token) {
167
+ headers.Authorization = `Bearer ${token}`;
168
+ }
169
+ try {
170
+ var response = await fetch(url, {
171
+ method: "POST",
172
+ body: JSON.stringify(body),
173
+ headers
174
+ });
175
+ } catch (e) {
176
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
177
+ }
178
+ const output = await response.json();
179
+ return [output, response.status];
180
+ }
181
+ let NodeBlob;
182
+ async function upload_files(root, files, token) {
183
+ const headers = {};
184
+ if (token) {
185
+ headers.Authorization = `Bearer ${token}`;
186
+ }
187
+ const formData = new FormData();
188
+ files.forEach((file) => {
189
+ formData.append("files", file);
190
+ });
191
+ try {
192
+ var response = await fetch(`${root}/upload`, {
193
+ method: "POST",
194
+ body: formData,
195
+ headers
196
+ });
197
+ } catch (e) {
198
+ return { error: BROKEN_CONNECTION_MSG };
199
+ }
200
+ const output = await response.json();
201
+ return { files: output };
202
+ }
203
+ async function duplicate(app_reference, options) {
204
+ const { hf_token, private: _private, hardware, timeout } = options;
205
+ if (hardware && !hardware_types.includes(hardware)) {
206
+ throw new Error(
207
+ `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
208
+ );
209
+ }
210
+ const headers = {
211
+ Authorization: `Bearer ${hf_token}`
212
+ };
213
+ const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
214
+ headers
215
+ })).json()).name;
216
+ const space_name = app_reference.split("/")[1];
217
+ const body = {
218
+ repository: `${user}/${space_name}`
219
+ };
220
+ if (_private) {
221
+ body.private = true;
222
+ }
223
+ try {
224
+ const response = await fetch(
225
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
226
+ {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/json", ...headers },
229
+ body: JSON.stringify(body)
230
+ }
231
+ );
232
+ if (response.status === 409) {
233
+ return client(`${user}/${space_name}`, options);
234
+ } else {
235
+ const duplicated_space = await response.json();
236
+ let original_hardware;
237
+ if (!hardware) {
238
+ original_hardware = await get_space_hardware(app_reference, hf_token);
239
+ }
240
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
241
+ await set_space_hardware(
242
+ `${user}/${space_name}`,
243
+ requested_hardware,
244
+ hf_token
245
+ );
246
+ await set_space_timeout(
247
+ `${user}/${space_name}`,
248
+ timeout || 300,
249
+ hf_token
250
+ );
251
+ return client(duplicated_space.url, options);
252
+ }
253
+ } catch (e) {
254
+ throw new Error(e);
255
+ }
256
+ }
257
+ async function client(app_reference, options = { normalise_files: true }) {
258
+ return new Promise(async (res) => {
259
+ const { status_callback, hf_token, normalise_files } = options;
260
+ const return_obj = {
261
+ predict,
262
+ submit,
263
+ view_api
264
+ // duplicate
265
+ };
266
+ let transform_files = normalise_files ?? true;
267
+ if (typeof window === "undefined" || !("WebSocket" in window)) {
268
+ const ws = await import("./wrapper-b7460963.js");
269
+ NodeBlob = (await import("node:buffer")).Blob;
270
+ global.WebSocket = ws.WebSocket;
271
+ }
272
+ const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token);
273
+ const session_hash = Math.random().toString(36).substring(2);
274
+ const last_status = {};
275
+ let config;
276
+ let api_map = {};
277
+ let jwt = false;
278
+ if (hf_token && space_id) {
279
+ jwt = await get_jwt(space_id, hf_token);
280
+ }
281
+ async function config_success(_config) {
282
+ config = _config;
283
+ api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []);
284
+ try {
285
+ api = await view_api(config);
286
+ } catch (e) {
287
+ console.error(`Could not get api details: ${e.message}`);
288
+ }
289
+ return {
290
+ config,
291
+ ...return_obj
292
+ };
293
+ }
294
+ let api;
295
+ async function handle_space_sucess(status) {
296
+ if (status_callback)
297
+ status_callback(status);
298
+ if (status.status === "running")
299
+ try {
300
+ config = await resolve_config(`${http_protocol}//${host}`, hf_token);
301
+ const _config = await config_success(config);
302
+ res(_config);
303
+ } catch (e) {
304
+ if (status_callback) {
305
+ status_callback({
306
+ status: "error",
307
+ message: "Could not load this space.",
308
+ load_status: "error",
309
+ detail: "NOT_FOUND"
310
+ });
311
+ }
312
+ }
313
+ }
314
+ try {
315
+ config = await resolve_config(`${http_protocol}//${host}`, hf_token);
316
+ const _config = await config_success(config);
317
+ res(_config);
318
+ } catch (e) {
319
+ if (space_id) {
320
+ check_space_status(
321
+ space_id,
322
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
323
+ handle_space_sucess
324
+ );
325
+ } else {
326
+ if (status_callback)
327
+ status_callback({
328
+ status: "error",
329
+ message: "Could not load this space.",
330
+ load_status: "error",
331
+ detail: "NOT_FOUND"
332
+ });
333
+ }
334
+ }
335
+ function predict(endpoint, data, event_data) {
336
+ let data_returned = false;
337
+ let status_complete = false;
338
+ return new Promise((res2, rej) => {
339
+ const app = submit(endpoint, data, event_data);
340
+ app.on("data", (d) => {
341
+ data_returned = true;
342
+ if (status_complete) {
343
+ app.destroy();
344
+ }
345
+ res2(d);
346
+ }).on("status", (status) => {
347
+ if (status.stage === "error")
348
+ rej(status);
349
+ if (status.stage === "complete" && data_returned) {
350
+ app.destroy();
351
+ }
352
+ if (status.stage === "complete") {
353
+ status_complete = true;
354
+ }
355
+ });
356
+ });
357
+ }
358
+ function submit(endpoint, data, event_data) {
359
+ let fn_index;
360
+ let api_info;
361
+ if (typeof endpoint === "number") {
362
+ fn_index = endpoint;
363
+ api_info = api.unnamed_endpoints[fn_index];
364
+ } else {
365
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
366
+ fn_index = api_map[trimmed_endpoint];
367
+ api_info = api.named_endpoints[endpoint.trim()];
368
+ }
369
+ if (typeof fn_index !== "number") {
370
+ throw new Error(
371
+ "There is no endpoint matching that name of fn_index matching that number."
372
+ );
373
+ }
374
+ let websocket;
375
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
376
+ let payload;
377
+ let complete = false;
378
+ const listener_map = {};
379
+ handle_blob(
380
+ `${http_protocol}//${host + config.path}`,
381
+ data,
382
+ api_info,
383
+ hf_token
384
+ ).then((_payload) => {
385
+ payload = { data: _payload || [], event_data, fn_index };
386
+ if (skip_queue(fn_index, config)) {
387
+ fire_event({
388
+ type: "status",
389
+ endpoint: _endpoint,
390
+ stage: "pending",
391
+ queue: false,
392
+ fn_index,
393
+ time: /* @__PURE__ */ new Date()
394
+ });
395
+ post_data(
396
+ `${http_protocol}//${host + config.path}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}`,
397
+ {
398
+ ...payload,
399
+ session_hash
400
+ },
401
+ hf_token
402
+ ).then(([output, status_code]) => {
403
+ transform_files ? transform_output(
404
+ output.data,
405
+ api_info,
406
+ config.root,
407
+ config.root_url
408
+ ) : output.data;
409
+ if (status_code == 200) {
410
+ fire_event({
411
+ type: "data",
412
+ endpoint: _endpoint,
413
+ fn_index,
414
+ data: output.data,
415
+ time: /* @__PURE__ */ new Date()
416
+ });
417
+ fire_event({
418
+ type: "status",
419
+ endpoint: _endpoint,
420
+ fn_index,
421
+ stage: "complete",
422
+ eta: output.average_duration,
423
+ queue: false,
424
+ time: /* @__PURE__ */ new Date()
425
+ });
426
+ } else {
427
+ fire_event({
428
+ type: "status",
429
+ stage: "error",
430
+ endpoint: _endpoint,
431
+ fn_index,
432
+ message: output.error,
433
+ queue: false,
434
+ time: /* @__PURE__ */ new Date()
435
+ });
436
+ }
437
+ }).catch((e) => {
438
+ fire_event({
439
+ type: "status",
440
+ stage: "error",
441
+ message: e.message,
442
+ endpoint: _endpoint,
443
+ fn_index,
444
+ queue: false,
445
+ time: /* @__PURE__ */ new Date()
446
+ });
447
+ });
448
+ } else {
449
+ fire_event({
450
+ type: "status",
451
+ stage: "pending",
452
+ queue: true,
453
+ endpoint: _endpoint,
454
+ fn_index,
455
+ time: /* @__PURE__ */ new Date()
456
+ });
457
+ let url = new URL(`${ws_protocol}://${host}${config.path}
458
+ /queue/join`);
459
+ if (jwt) {
460
+ url.searchParams.set("__sign", jwt);
461
+ }
462
+ websocket = new WebSocket(url);
463
+ websocket.onclose = (evt) => {
464
+ if (!evt.wasClean) {
465
+ fire_event({
466
+ type: "status",
467
+ stage: "error",
468
+ message: BROKEN_CONNECTION_MSG,
469
+ queue: true,
470
+ endpoint: _endpoint,
471
+ fn_index,
472
+ time: /* @__PURE__ */ new Date()
473
+ });
474
+ }
475
+ };
476
+ websocket.onmessage = function(event) {
477
+ const _data = JSON.parse(event.data);
478
+ const { type, status, data: data2 } = handle_message(
479
+ _data,
480
+ last_status[fn_index]
481
+ );
482
+ if (type === "update" && status && !complete) {
483
+ fire_event({
484
+ type: "status",
485
+ endpoint: _endpoint,
486
+ fn_index,
487
+ time: /* @__PURE__ */ new Date(),
488
+ ...status
489
+ });
490
+ if (status.stage === "error") {
491
+ websocket.close();
492
+ }
493
+ } else if (type === "hash") {
494
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
495
+ return;
496
+ } else if (type === "data") {
497
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
498
+ } else if (type === "complete") {
499
+ complete = status;
500
+ } else if (type === "generating") {
501
+ fire_event({
502
+ type: "status",
503
+ time: /* @__PURE__ */ new Date(),
504
+ ...status,
505
+ stage: status == null ? void 0 : status.stage,
506
+ queue: true,
507
+ endpoint: _endpoint,
508
+ fn_index
509
+ });
510
+ }
511
+ if (data2) {
512
+ fire_event({
513
+ type: "data",
514
+ time: /* @__PURE__ */ new Date(),
515
+ data: transform_files ? transform_output(
516
+ data2.data,
517
+ api_info,
518
+ config.root,
519
+ config.root_url
520
+ ) : data2.data,
521
+ endpoint: _endpoint,
522
+ fn_index
523
+ });
524
+ if (complete) {
525
+ fire_event({
526
+ type: "status",
527
+ time: /* @__PURE__ */ new Date(),
528
+ ...complete,
529
+ stage: status == null ? void 0 : status.stage,
530
+ queue: true,
531
+ endpoint: _endpoint,
532
+ fn_index
533
+ });
534
+ websocket.close();
535
+ }
536
+ }
537
+ };
538
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
539
+ addEventListener(
540
+ "open",
541
+ () => websocket.send(JSON.stringify({ hash: session_hash }))
542
+ );
543
+ }
544
+ }
545
+ });
546
+ function fire_event(event) {
547
+ const narrowed_listener_map = listener_map;
548
+ let listeners = narrowed_listener_map[event.type] || [];
549
+ listeners == null ? void 0 : listeners.forEach((l) => l(event));
550
+ }
551
+ function on(eventType, listener) {
552
+ const narrowed_listener_map = listener_map;
553
+ let listeners = narrowed_listener_map[eventType] || [];
554
+ narrowed_listener_map[eventType] = listeners;
555
+ listeners == null ? void 0 : listeners.push(listener);
556
+ return { on, off, cancel, destroy };
557
+ }
558
+ function off(eventType, listener) {
559
+ const narrowed_listener_map = listener_map;
560
+ let listeners = narrowed_listener_map[eventType] || [];
561
+ listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
562
+ narrowed_listener_map[eventType] = listeners;
563
+ return { on, off, cancel, destroy };
564
+ }
565
+ async function cancel() {
566
+ const _status = {
567
+ stage: "complete",
568
+ queue: false,
569
+ time: /* @__PURE__ */ new Date()
570
+ };
571
+ complete = _status;
572
+ fire_event({
573
+ ..._status,
574
+ type: "status",
575
+ endpoint: _endpoint,
576
+ fn_index
577
+ });
578
+ if (websocket && websocket.readyState === 0) {
579
+ websocket.addEventListener("open", () => {
580
+ websocket.close();
581
+ });
582
+ } else {
583
+ websocket.close();
584
+ }
585
+ try {
586
+ await fetch(`${http_protocol}//${host + config.path}/reset`, {
587
+ headers: { "Content-Type": "application/json" },
588
+ method: "POST",
589
+ body: JSON.stringify({ fn_index, session_hash })
590
+ });
591
+ } catch (e) {
592
+ console.warn(
593
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
594
+ );
595
+ }
596
+ }
597
+ function destroy() {
598
+ for (const event_type in listener_map) {
599
+ listener_map[event_type].forEach((fn2) => {
600
+ off(event_type, fn2);
601
+ });
602
+ }
603
+ }
604
+ return {
605
+ on,
606
+ off,
607
+ cancel,
608
+ destroy
609
+ };
610
+ }
611
+ async function view_api(config2) {
612
+ if (api)
613
+ return api;
614
+ const headers = { "Content-Type": "application/json" };
615
+ if (hf_token) {
616
+ headers.Authorization = `Bearer ${hf_token}`;
617
+ }
618
+ try {
619
+ let response;
620
+ if (semiver(config2.version || "2.0.0", "3.30") < 0) {
621
+ response = await fetch(
622
+ "https://gradio-space-api-fetcher-v2.hf.space/api",
623
+ {
624
+ method: "POST",
625
+ body: JSON.stringify({
626
+ serialize: false,
627
+ config: JSON.stringify(config2)
628
+ }),
629
+ headers
630
+ }
631
+ );
632
+ } else {
633
+ response = await fetch(`${http_protocol}//${host}/info`, {
634
+ headers
635
+ });
636
+ }
637
+ let api_info = await response.json();
638
+ if ("api" in api_info) {
639
+ api_info = api_info.api;
640
+ }
641
+ if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
642
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
643
+ }
644
+ const x = transform_api_info(api_info, config2, api_map);
645
+ return x;
646
+ } catch (e) {
647
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
648
+ }
649
+ }
650
+ });
651
+ }
652
+ function transform_output(data, api_info, root_url, remote_url) {
653
+ let transformed_data = data.map((d, i) => {
654
+ var _a, _b, _c, _d;
655
+ if (((_b = (_a = api_info.returns) == null ? void 0 : _a[i]) == null ? void 0 : _b.component) === "File") {
656
+ return normalise_file(d, root_url, remote_url);
657
+ } else if (((_d = (_c = api_info.returns) == null ? void 0 : _c[i]) == null ? void 0 : _d.component) === "Gallery") {
658
+ return d.map((img) => {
659
+ return Array.isArray(img) ? [normalise_file(img[0], root_url, remote_url), img[1]] : [normalise_file(img, root_url, remote_url), null];
660
+ });
661
+ } else if (typeof d === "object" && d.is_file) {
662
+ return normalise_file(d, root_url, remote_url);
663
+ } else {
664
+ return d;
665
+ }
666
+ });
667
+ return transformed_data;
668
+ }
669
+ function normalise_file(file, root, root_url) {
670
+ if (file == null)
671
+ return null;
672
+ if (typeof file === "string") {
673
+ return {
674
+ name: "file_data",
675
+ data: file
676
+ };
677
+ } else if (Array.isArray(file)) {
678
+ const normalized_file = [];
679
+ for (const x of file) {
680
+ if (x === null) {
681
+ normalized_file.push(null);
682
+ } else {
683
+ normalized_file.push(normalise_file(x, root, root_url));
684
+ }
685
+ }
686
+ return normalized_file;
687
+ } else if (file.is_file) {
688
+ if (!root_url) {
689
+ file.data = root + "/file=" + file.name;
690
+ } else {
691
+ file.data = "/proxy=" + root_url + "/file=" + file.name;
692
+ }
693
+ }
694
+ return file;
695
+ }
696
+ function get_type(type, component, serializer, signature_type) {
697
+ switch (type.type) {
698
+ case "string":
699
+ return "string";
700
+ case "boolean":
701
+ return "boolean";
702
+ case "number":
703
+ return "number";
704
+ }
705
+ if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
706
+ return "any";
707
+ } else if (serializer === "ListStringSerializable") {
708
+ return "string[]";
709
+ } else if (component === "Image") {
710
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
711
+ } else if (serializer === "FileSerializable") {
712
+ if ((type == null ? void 0 : type.type) === "array") {
713
+ return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
714
+ } else {
715
+ return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
716
+ }
717
+ } else if (serializer === "GallerySerializable") {
718
+ return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
719
+ }
720
+ }
721
+ function get_description(type, serializer) {
722
+ if (serializer === "GallerySerializable") {
723
+ return "array of [file, label] tuples";
724
+ } else if (serializer === "ListStringSerializable") {
725
+ return "array of strings";
726
+ } else if (serializer === "FileSerializable") {
727
+ return "array of files or single file";
728
+ } else {
729
+ return type.description;
730
+ }
731
+ }
732
+ function transform_api_info(api_info, config, api_map) {
733
+ const new_data = {
734
+ named_endpoints: {},
735
+ unnamed_endpoints: {}
736
+ };
737
+ for (const key in api_info) {
738
+ const cat = api_info[key];
739
+ for (const endpoint in cat) {
740
+ const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")];
741
+ const info = cat[endpoint];
742
+ new_data[key][endpoint] = {};
743
+ new_data[key][endpoint].parameters = {};
744
+ new_data[key][endpoint].returns = {};
745
+ new_data[key][endpoint].type = config.dependencies[dep_index].types;
746
+ new_data[key][endpoint].parameters = info.parameters.map(
747
+ ({ label, component, type, serializer }) => ({
748
+ label,
749
+ component,
750
+ type: get_type(type, component, serializer, "parameter"),
751
+ description: get_description(type, serializer)
752
+ })
753
+ );
754
+ new_data[key][endpoint].returns = info.returns.map(
755
+ ({ label, component, type, serializer }) => ({
756
+ label,
757
+ component,
758
+ type: get_type(type, component, serializer, "return"),
759
+ description: get_description(type, serializer)
760
+ })
761
+ );
762
+ }
763
+ }
764
+ return new_data;
765
+ }
766
+ async function get_jwt(space, token) {
767
+ try {
768
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
769
+ headers: {
770
+ Authorization: `Bearer ${token}`
771
+ }
772
+ });
773
+ const jwt = (await r.json()).token;
774
+ return jwt || false;
775
+ } catch (e) {
776
+ console.error(e);
777
+ return false;
778
+ }
779
+ }
780
+ async function handle_blob(endpoint, data, api_info, token) {
781
+ const blob_refs = await walk_and_store_blobs(
782
+ data,
783
+ void 0,
784
+ [],
785
+ true,
786
+ api_info
787
+ );
788
+ return new Promise((res) => {
789
+ Promise.all(
790
+ blob_refs.map(async ({ path, blob, data: data2, type }) => {
791
+ if (blob) {
792
+ const file_url = (await upload_files(endpoint, [blob], token)).files[0];
793
+ return { path, file_url, type };
794
+ } else {
795
+ return { path, base64: data2, type };
796
+ }
797
+ })
798
+ ).then((r) => {
799
+ r.forEach(({ path, file_url, base64, type }) => {
800
+ if (base64) {
801
+ update_object(data, base64, path);
802
+ } else if (type === "Gallery") {
803
+ update_object(data, file_url, path);
804
+ } else if (file_url) {
805
+ const o = {
806
+ is_file: true,
807
+ name: `${file_url}`,
808
+ data: null
809
+ // orig_name: "file.csv"
810
+ };
811
+ update_object(data, o, path);
812
+ }
813
+ });
814
+ res(data);
815
+ }).catch(console.log);
816
+ });
817
+ }
818
+ function update_object(object, newValue, stack) {
819
+ while (stack.length > 1) {
820
+ object = object[stack.shift()];
821
+ }
822
+ object[stack.shift()] = newValue;
823
+ }
824
+ async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) {
825
+ if (Array.isArray(param)) {
826
+ let blob_refs = [];
827
+ await Promise.all(
828
+ param.map(async (v, i) => {
829
+ var _a;
830
+ let new_path = path.slice();
831
+ new_path.push(i);
832
+ const array_refs = await walk_and_store_blobs(
833
+ param[i],
834
+ root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type,
835
+ new_path,
836
+ false,
837
+ api_info
838
+ );
839
+ blob_refs = blob_refs.concat(array_refs);
840
+ })
841
+ );
842
+ return blob_refs;
843
+ } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
844
+ const is_image = type === "Image";
845
+ return [
846
+ {
847
+ path,
848
+ blob: is_image ? false : new NodeBlob([param]),
849
+ data: is_image ? `${param.toString("base64")}` : false,
850
+ type
851
+ }
852
+ ];
853
+ } else if (param instanceof Blob || typeof window !== "undefined" && param instanceof File) {
854
+ if (type === "Image") {
855
+ let data;
856
+ if (typeof window !== "undefined") {
857
+ data = await image_to_data_uri(param);
858
+ } else {
859
+ const buffer = await param.arrayBuffer();
860
+ data = Buffer.from(buffer).toString("base64");
861
+ }
862
+ return [{ path, data, type }];
863
+ } else {
864
+ return [{ path, blob: param, type }];
865
+ }
866
+ } else if (typeof param === "object") {
867
+ let blob_refs = [];
868
+ for (let key in param) {
869
+ if (param.hasOwnProperty(key)) {
870
+ let new_path = path.slice();
871
+ new_path.push(key);
872
+ blob_refs = blob_refs.concat(
873
+ await walk_and_store_blobs(
874
+ param[key],
875
+ void 0,
876
+ new_path,
877
+ false,
878
+ api_info
879
+ )
880
+ );
881
+ }
882
+ }
883
+ return blob_refs;
884
+ } else {
885
+ return [];
886
+ }
887
+ }
888
+ function image_to_data_uri(blob) {
889
+ return new Promise((resolve, _) => {
890
+ const reader = new FileReader();
891
+ reader.onloadend = () => resolve(reader.result);
892
+ reader.readAsDataURL(blob);
893
+ });
894
+ }
895
+ function skip_queue(id, config) {
896
+ var _a, _b, _c, _d;
897
+ return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false;
898
+ }
899
+ async function resolve_config(endpoint, token) {
900
+ const headers = {};
901
+ if (token) {
902
+ headers.Authorization = `Bearer ${token}`;
903
+ }
904
+ if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876") {
905
+ const path = window.gradio_config.root;
906
+ const config = window.gradio_config;
907
+ config.root = endpoint + config.root;
908
+ return { ...config, path };
909
+ } else if (endpoint) {
910
+ let response = await fetch(`${endpoint}/config`, { headers });
911
+ if (response.status === 200) {
912
+ const config = await response.json();
913
+ config.path = config.path ?? "";
914
+ config.root = endpoint;
915
+ return config;
916
+ } else {
917
+ throw new Error("Could not get config.");
918
+ }
919
+ }
920
+ throw new Error("No config or app endpoint found");
921
+ }
922
+ async function check_space_status(id, type, status_callback) {
923
+ let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
924
+ let response;
925
+ let _status;
926
+ try {
927
+ response = await fetch(endpoint);
928
+ _status = response.status;
929
+ if (_status !== 200) {
930
+ throw new Error();
931
+ }
932
+ response = await response.json();
933
+ } catch (e) {
934
+ status_callback({
935
+ status: "error",
936
+ load_status: "error",
937
+ message: "Could not get space status",
938
+ detail: "NOT_FOUND"
939
+ });
940
+ return;
941
+ }
942
+ if (!response || _status !== 200)
943
+ return;
944
+ const {
945
+ runtime: { stage },
946
+ id: space_name
947
+ } = response;
948
+ switch (stage) {
949
+ case "STOPPED":
950
+ case "SLEEPING":
951
+ status_callback({
952
+ status: "sleeping",
953
+ load_status: "pending",
954
+ message: "Space is asleep. Waking it up...",
955
+ detail: stage
956
+ });
957
+ setTimeout(() => {
958
+ check_space_status(id, type, status_callback);
959
+ }, 1e3);
960
+ break;
961
+ case "RUNNING":
962
+ case "RUNNING_BUILDING":
963
+ status_callback({
964
+ status: "running",
965
+ load_status: "complete",
966
+ message: "",
967
+ detail: stage
968
+ });
969
+ break;
970
+ case "BUILDING":
971
+ status_callback({
972
+ status: "building",
973
+ load_status: "pending",
974
+ message: "Space is building...",
975
+ detail: stage
976
+ });
977
+ setTimeout(() => {
978
+ check_space_status(id, type, status_callback);
979
+ }, 1e3);
980
+ break;
981
+ default:
982
+ status_callback({
983
+ status: "space_error",
984
+ load_status: "error",
985
+ message: "This space is experiencing an issue.",
986
+ detail: stage,
987
+ discussions_enabled: await discussions_enabled(space_name)
988
+ });
989
+ break;
990
+ }
991
+ }
992
+ function handle_message(data, last_status) {
993
+ const queue = true;
994
+ switch (data.msg) {
995
+ case "send_data":
996
+ return { type: "data" };
997
+ case "send_hash":
998
+ return { type: "hash" };
999
+ case "queue_full":
1000
+ return {
1001
+ type: "update",
1002
+ status: {
1003
+ queue,
1004
+ message: QUEUE_FULL_MSG,
1005
+ stage: "error",
1006
+ code: data.code,
1007
+ success: data.success
1008
+ }
1009
+ };
1010
+ case "estimation":
1011
+ return {
1012
+ type: "update",
1013
+ status: {
1014
+ queue,
1015
+ stage: last_status || "pending",
1016
+ code: data.code,
1017
+ size: data.queue_size,
1018
+ position: data.rank,
1019
+ eta: data.rank_eta,
1020
+ success: data.success
1021
+ }
1022
+ };
1023
+ case "progress":
1024
+ return {
1025
+ type: "update",
1026
+ status: {
1027
+ queue,
1028
+ stage: "pending",
1029
+ code: data.code,
1030
+ progress_data: data.progress_data,
1031
+ success: data.success
1032
+ }
1033
+ };
1034
+ case "process_generating":
1035
+ return {
1036
+ type: "generating",
1037
+ status: {
1038
+ queue,
1039
+ message: !data.success ? data.output.error : null,
1040
+ stage: data.success ? "generating" : "error",
1041
+ code: data.code,
1042
+ progress_data: data.progress_data,
1043
+ eta: data.average_duration
1044
+ },
1045
+ data: data.success ? data.output : null
1046
+ };
1047
+ case "process_completed":
1048
+ return {
1049
+ type: "complete",
1050
+ status: {
1051
+ queue,
1052
+ message: !data.success ? data.output.error : void 0,
1053
+ stage: data.success ? "complete" : "error",
1054
+ code: data.code,
1055
+ progress_data: data.progress_data,
1056
+ eta: data.output.average_duration
1057
+ },
1058
+ data: data.success ? data.output : null
1059
+ };
1060
+ case "process_starts":
1061
+ return {
1062
+ type: "update",
1063
+ status: {
1064
+ queue,
1065
+ stage: "pending",
1066
+ code: data.code,
1067
+ size: data.rank,
1068
+ position: 0,
1069
+ success: data.success
1070
+ }
1071
+ };
1072
+ }
1073
+ return { type: "none", status: { stage: "error", queue } };
1074
+ }
1075
+ export {
1076
+ client,
1077
+ duplicate,
1078
+ post_data,
1079
+ upload_files
1080
+ };