/
client.ts
1330 lines (1218 loc) 路 30.4 KB
/
client.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import semiver from "semiver";
import {
process_endpoint,
RE_SPACE_NAME,
map_names_to_ids,
discussions_enabled,
get_space_hardware,
set_space_hardware,
set_space_timeout,
hardware_types
} from "./utils.js";
import type {
EventType,
EventListener,
ListenerMap,
Event,
Payload,
PostResponse,
UploadResponse,
Status,
SpaceStatus,
SpaceStatusCallback,
FileData
} from "./types.js";
import type { Config } from "./types.js";
type event = <K extends EventType>(
eventType: K,
listener: EventListener<K>
) => SubmitReturn;
type predict = (
endpoint: string | number,
data?: unknown[],
event_data?: unknown
) => Promise<unknown>;
type client_return = {
predict: predict;
config: Config;
submit: (
endpoint: string | number,
data?: unknown[],
event_data?: unknown
) => SubmitReturn;
view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
};
type SubmitReturn = {
on: event;
off: event;
cancel: () => Promise<void>;
destroy: () => void;
};
const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
const BROKEN_CONNECTION_MSG = "Connection errored out.";
export let NodeBlob;
export async function duplicate(
app_reference: string,
options: {
hf_token: `hf_${string}`;
private?: boolean;
status_callback: SpaceStatusCallback;
hardware?: (typeof hardware_types)[number];
timeout?: number;
}
) {
const { hf_token, private: _private, hardware, timeout } = options;
if (hardware && !hardware_types.includes(hardware)) {
throw new Error(
`Invalid hardware type provided. Valid types are: ${hardware_types
.map((v) => `"${v}"`)
.join(",")}.`
);
}
const headers = {
Authorization: `Bearer ${hf_token}`
};
const user = (
await (
await fetch(`https://huggingface.co/api/whoami-v2`, {
headers
})
).json()
).name;
const space_name = app_reference.split("/")[1];
const body: {
repository: string;
private?: boolean;
} = {
repository: `${user}/${space_name}`
};
if (_private) {
body.private = true;
}
try {
const response = await fetch(
`https://huggingface.co/api/spaces/${app_reference}/duplicate`,
{
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify(body)
}
);
if (response.status === 409) {
return client(`${user}/${space_name}`, options);
} else {
const duplicated_space = await response.json();
let original_hardware;
if (!hardware) {
original_hardware = await get_space_hardware(app_reference, hf_token);
}
const requested_hardware = hardware || original_hardware || "cpu-basic";
await set_space_hardware(
`${user}/${space_name}`,
requested_hardware,
hf_token
);
await set_space_timeout(
`${user}/${space_name}`,
timeout || 300,
hf_token
);
return client(duplicated_space.url, options);
}
} catch (e: any) {
throw new Error(e);
}
}
/**
* We need to inject a customized fetch implementation for the Wasm version.
*/
export function api_factory(fetch_implementation: typeof fetch) {
return { post_data, upload_files, client, handle_blob };
async function post_data(
url: string,
body: unknown,
token?: `hf_${string}`
): Promise<[PostResponse, number]> {
const headers: {
Authorization?: string;
"Content-Type": "application/json";
} = { "Content-Type": "application/json" };
if (token) {
headers.Authorization = `Bearer ${token}`;
}
try {
var response = await fetch_implementation(url, {
method: "POST",
body: JSON.stringify(body),
headers
});
} catch (e) {
return [{ error: BROKEN_CONNECTION_MSG }, 500];
}
const output: PostResponse = await response.json();
return [output, response.status];
}
async function upload_files(
root: string,
files: Array<File>,
token?: `hf_${string}`
): Promise<UploadResponse> {
const headers: {
Authorization?: string;
} = {};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const chunkSize = 1000;
const uploadResponses = [];
for (let i = 0; i < files.length; i += chunkSize) {
const chunk = files.slice(i, i + chunkSize);
const formData = new FormData();
chunk.forEach((file) => {
formData.append("files", file);
});
try {
var response = await fetch_implementation(`${root}/upload`, {
method: "POST",
body: formData,
headers
});
} catch (e) {
return { error: BROKEN_CONNECTION_MSG };
}
const output: UploadResponse["files"] = await response.json();
uploadResponses.push(...output);
}
return { files: uploadResponses };
}
async function client(
app_reference: string,
options: {
hf_token?: `hf_${string}`;
status_callback?: SpaceStatusCallback;
normalise_files?: boolean;
} = { normalise_files: true }
): Promise<client_return> {
return new Promise(async (res) => {
const { status_callback, hf_token, normalise_files } = options;
const return_obj = {
predict,
submit,
view_api
// duplicate
};
const transform_files = normalise_files ?? true;
if (typeof window === "undefined" || !("WebSocket" in window)) {
const ws = await import("ws");
NodeBlob = (await import("node:buffer")).Blob;
//@ts-ignore
global.WebSocket = ws.WebSocket;
}
const { ws_protocol, http_protocol, host, space_id } =
await process_endpoint(app_reference, hf_token);
const session_hash = Math.random().toString(36).substring(2);
const last_status: Record<string, Status["stage"]> = {};
let config: Config;
let api_map: Record<string, number> = {};
let jwt: false | string = false;
if (hf_token && space_id) {
jwt = await get_jwt(space_id, hf_token);
}
async function config_success(_config: Config) {
config = _config;
api_map = map_names_to_ids(_config?.dependencies || []);
try {
api = await view_api(config);
} catch (e) {
console.error(`Could not get api details: ${e.message}`);
}
return {
config,
...return_obj
};
}
let api: ApiInfo<JsApiData>;
async function handle_space_sucess(status: SpaceStatus) {
if (status_callback) status_callback(status);
if (status.status === "running")
try {
config = await resolve_config(
fetch_implementation,
`${http_protocol}//${host}`,
hf_token
);
const _config = await config_success(config);
res(_config);
} catch (e) {
console.error(e);
if (status_callback) {
status_callback({
status: "error",
message: "Could not load this space.",
load_status: "error",
detail: "NOT_FOUND"
});
}
}
}
try {
config = await resolve_config(
fetch_implementation,
`${http_protocol}//${host}`,
hf_token
);
const _config = await config_success(config);
res(_config);
} catch (e) {
console.error(e);
if (space_id) {
check_space_status(
space_id,
RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
handle_space_sucess
);
} else {
if (status_callback)
status_callback({
status: "error",
message: "Could not load this space.",
load_status: "error",
detail: "NOT_FOUND"
});
}
}
/**
* Run a prediction.
* @param endpoint - The prediction endpoint to use.
* @param status_callback - A function that is called with the current status of the prediction immediately and every time it updates.
* @return Returns the data for the prediction or an error message.
*/
function predict(
endpoint: string,
data: unknown[],
event_data?: unknown
) {
let data_returned = false;
let status_complete = false;
return new Promise((res, rej) => {
const app = submit(endpoint, data, event_data);
app
.on("data", (d) => {
data_returned = true;
if (status_complete) {
app.destroy();
}
res(d);
})
.on("status", (status) => {
if (status.stage === "error") rej(status);
if (status.stage === "complete" && data_returned) {
app.destroy();
}
if (status.stage === "complete") {
status_complete = true;
}
});
});
}
function submit(
endpoint: string | number,
data: unknown[],
event_data?: unknown
): SubmitReturn {
let fn_index: number;
let api_info;
if (typeof endpoint === "number") {
fn_index = endpoint;
api_info = api.unnamed_endpoints[fn_index];
} else {
const trimmed_endpoint = endpoint.replace(/^\//, "");
fn_index = api_map[trimmed_endpoint];
api_info = api.named_endpoints[endpoint.trim()];
}
if (typeof fn_index !== "number") {
throw new Error(
"There is no endpoint matching that name of fn_index matching that number."
);
}
let websocket: WebSocket;
const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
let payload: Payload;
let complete: false | Record<string, any> = false;
const listener_map: ListenerMap<EventType> = {};
handle_blob(
`${http_protocol}//${host + config.path}`,
data,
api_info,
hf_token
).then((_payload) => {
payload = { data: _payload || [], event_data, fn_index };
if (skip_queue(fn_index, config)) {
fire_event({
type: "status",
endpoint: _endpoint,
stage: "pending",
queue: false,
fn_index,
time: new Date()
});
post_data(
`${http_protocol}//${host + config.path}/run${
_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`
}`,
{
...payload,
session_hash
},
hf_token
)
.then(([output, status_code]) => {
const data = transform_files
? transform_output(
output.data,
api_info,
config.root,
config.root_url
)
: output.data;
if (status_code == 200) {
fire_event({
type: "data",
endpoint: _endpoint,
fn_index,
data: data,
time: new Date()
});
fire_event({
type: "status",
endpoint: _endpoint,
fn_index,
stage: "complete",
eta: output.average_duration,
queue: false,
time: new Date()
});
} else {
fire_event({
type: "status",
stage: "error",
endpoint: _endpoint,
fn_index,
message: output.error,
queue: false,
time: new Date()
});
}
})
.catch((e) => {
fire_event({
type: "status",
stage: "error",
message: e.message,
endpoint: _endpoint,
fn_index,
queue: false,
time: new Date()
});
});
} else {
fire_event({
type: "status",
stage: "pending",
queue: true,
endpoint: _endpoint,
fn_index,
time: new Date()
});
let url = new URL(`${ws_protocol}://${host}${config.path}
/queue/join`);
if (jwt) {
url.searchParams.set("__sign", jwt);
}
websocket = new WebSocket(url);
websocket.onclose = (evt) => {
if (!evt.wasClean) {
fire_event({
type: "status",
stage: "error",
broken: true,
message: BROKEN_CONNECTION_MSG,
queue: true,
endpoint: _endpoint,
fn_index,
time: new Date()
});
}
};
websocket.onmessage = function (event) {
const _data = JSON.parse(event.data);
const { type, status, data } = handle_message(
_data,
last_status[fn_index]
);
if (type === "update" && status && !complete) {
// call 'status' listeners
fire_event({
type: "status",
endpoint: _endpoint,
fn_index,
time: new Date(),
...status
});
if (status.stage === "error") {
websocket.close();
}
} else if (type === "hash") {
websocket.send(JSON.stringify({ fn_index, session_hash }));
return;
} else if (type === "data") {
websocket.send(JSON.stringify({ ...payload, session_hash }));
} else if (type === "complete") {
complete = status;
} else if (type === "log") {
fire_event({
type: "log",
log: data.log,
level: data.level,
endpoint: _endpoint,
fn_index
});
} else if (type === "generating") {
fire_event({
type: "status",
time: new Date(),
...status,
stage: status?.stage!,
queue: true,
endpoint: _endpoint,
fn_index
});
}
if (data) {
fire_event({
type: "data",
time: new Date(),
data: transform_files
? transform_output(
data.data,
api_info,
config.root,
config.root_url
)
: data.data,
endpoint: _endpoint,
fn_index
});
if (complete) {
fire_event({
type: "status",
time: new Date(),
...complete,
stage: status?.stage!,
queue: true,
endpoint: _endpoint,
fn_index
});
websocket.close();
}
}
};
// different ws contract for gradio versions older than 3.6.0
//@ts-ignore
if (semiver(config.version || "2.0.0", "3.6") < 0) {
addEventListener("open", () =>
websocket.send(JSON.stringify({ hash: session_hash }))
);
}
}
});
function fire_event<K extends EventType>(event: Event<K>) {
const narrowed_listener_map: ListenerMap<K> = listener_map;
const listeners = narrowed_listener_map[event.type] || [];
listeners?.forEach((l) => l(event));
}
function on<K extends EventType>(
eventType: K,
listener: EventListener<K>
) {
const narrowed_listener_map: ListenerMap<K> = listener_map;
const listeners = narrowed_listener_map[eventType] || [];
narrowed_listener_map[eventType] = listeners;
listeners?.push(listener);
return { on, off, cancel, destroy };
}
function off<K extends EventType>(
eventType: K,
listener: EventListener<K>
) {
const narrowed_listener_map: ListenerMap<K> = listener_map;
let listeners = narrowed_listener_map[eventType] || [];
listeners = listeners?.filter((l) => l !== listener);
narrowed_listener_map[eventType] = listeners;
return { on, off, cancel, destroy };
}
async function cancel() {
const _status: Status = {
stage: "complete",
queue: false,
time: new Date()
};
complete = _status;
fire_event({
..._status,
type: "status",
endpoint: _endpoint,
fn_index: fn_index
});
if (websocket && websocket.readyState === 0) {
websocket.addEventListener("open", () => {
websocket.close();
});
} else {
websocket.close();
}
try {
await fetch_implementation(
`${http_protocol}//${host + config.path}/reset`,
{
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ fn_index, session_hash })
}
);
} catch (e) {
console.warn(
"The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
);
}
}
function destroy() {
for (const event_type in listener_map) {
listener_map[event_type as "data" | "status"].forEach((fn) => {
off(event_type as "data" | "status", fn);
});
}
}
return {
on,
off,
cancel,
destroy
};
}
async function view_api(config?: Config): Promise<ApiInfo<JsApiData>> {
if (api) return api;
const headers: {
Authorization?: string;
"Content-Type": "application/json";
} = { "Content-Type": "application/json" };
if (hf_token) {
headers.Authorization = `Bearer ${hf_token}`;
}
let response: Response;
// @ts-ignore
if (semiver(config.version || "2.0.0", "3.30") < 0) {
response = await fetch_implementation(
"https://gradio-space-api-fetcher-v2.hf.space/api",
{
method: "POST",
body: JSON.stringify({
serialize: false,
config: JSON.stringify(config)
}),
headers
}
);
} else {
response = await fetch_implementation(`${config.root}/info`, {
headers
});
}
if (!response.ok) {
throw new Error(BROKEN_CONNECTION_MSG);
}
let api_info = (await response.json()) as
| ApiInfo<ApiData>
| { api: ApiInfo<ApiData> };
if ("api" in api_info) {
api_info = api_info.api;
}
if (
api_info.named_endpoints["/predict"] &&
!api_info.unnamed_endpoints["0"]
) {
api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
}
const x = transform_api_info(api_info, config, api_map);
return x;
}
});
}
async function handle_blob(
endpoint: string,
data: unknown[],
api_info,
token?: `hf_${string}`
): Promise<unknown[]> {
const blob_refs = await walk_and_store_blobs(
data,
undefined,
[],
true,
api_info
);
return Promise.all(
blob_refs.map(async ({ path, blob, data, type }) => {
if (blob) {
const file_url = (await upload_files(endpoint, [blob], token))
.files[0];
return { path, file_url, type };
} else {
return { path, base64: data, type };
}
})
).then((r) => {
r.forEach(({ path, file_url, base64, type }) => {
if (base64) {
update_object(data, base64, path);
} else if (type === "Gallery") {
update_object(data, file_url, path);
} else if (file_url) {
const o = {
is_file: true,
name: `${file_url}`,
data: null
// orig_name: "file.csv"
};
update_object(data, o, path);
}
});
return data;
});
}
}
export const { post_data, upload_files, client, handle_blob } =
api_factory(fetch);
function transform_output(
data: any[],
api_info: any,
root_url: string,
remote_url?: string
): unknown[] {
return data.map((d, i) => {
if (api_info.returns?.[i]?.component === "File") {
return normalise_file(d, root_url, remote_url);
} else if (api_info.returns?.[i]?.component === "Gallery") {
return d.map((img) => {
return Array.isArray(img)
? [normalise_file(img[0], root_url, remote_url), img[1]]
: [normalise_file(img, root_url, remote_url), null];
});
} else if (typeof d === "object" && d?.is_file) {
return normalise_file(d, root_url, remote_url);
} else {
return d;
}
});
}
function normalise_file(
file: Array<FileData>,
root: string,
root_url: string | null
): Array<FileData>;
function normalise_file(
file: FileData | string,
root: string,
root_url: string | null
): FileData;
function normalise_file(
file: null,
root: string,
root_url: string | null
): null;
function normalise_file(
file,
root,
root_url
): Array<FileData> | FileData | null {
if (file == null) return null;
if (typeof file === "string") {
return {
name: "file_data",
data: file
};
} else if (Array.isArray(file)) {
const normalized_file: Array<FileData | null> = [];
for (const x of file) {
if (x === null) {
normalized_file.push(null);
} else {
normalized_file.push(normalise_file(x, root, root_url));
}
}
return normalized_file as Array<FileData>;
} else if (file.is_file) {
if (!root_url) {
file.data = root + "/file=" + file.name;
} else {
file.data = "/proxy=" + root_url + "file=" + file.name;
}
}
return file;
}
interface ApiData {
label: string;
type: {
type: any;
description: string;
};
component: string;
example_input?: any;
}
interface JsApiData {
label: string;
type: string;
component: string;
example_input: any;
}
interface EndpointInfo<T extends ApiData | JsApiData> {
parameters: T[];
returns: T[];
}
interface ApiInfo<T extends ApiData | JsApiData> {
named_endpoints: {
[key: string]: EndpointInfo<T>;
};
unnamed_endpoints: {
[key: string]: EndpointInfo<T>;
};
}
function get_type(
type: { [key: string]: any },
component: string,
serializer: string,
signature_type: "return" | "parameter"
) {
switch (type.type) {
case "string":
return "string";
case "boolean":
return "boolean";
case "number":
return "number";
}
if (
serializer === "JSONSerializable" ||
serializer === "StringSerializable"
) {
return "any";
} else if (serializer === "ListStringSerializable") {
return "string[]";
} else if (component === "Image") {
return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
} else if (serializer === "FileSerializable") {
if (type?.type === "array") {
return signature_type === "parameter"
? "(Blob | File | Buffer)[]"
: `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
} else {
return signature_type === "parameter"
? "Blob | File | Buffer"
: `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
}
} else if (serializer === "GallerySerializable") {
return signature_type === "parameter"
? "[(Blob | File | Buffer), (string | null)][]"
: `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
}
}
function get_description(
type: { type: any; description: string },
serializer: string
) {
if (serializer === "GallerySerializable") {
return "array of [file, label] tuples";
} else if (serializer === "ListStringSerializable") {
return "array of strings";
} else if (serializer === "FileSerializable") {
return "array of files or single file";
} else {
return type.description;
}
}
function transform_api_info(
api_info: ApiInfo<ApiData>,
config: Config,
api_map: Record<string, number>
): ApiInfo<JsApiData> {
const new_data = {
named_endpoints: {},
unnamed_endpoints: {}
};
for (const key in api_info) {
const cat = api_info[key];
for (const endpoint in cat) {
const dep_index = config.dependencies[endpoint]
? endpoint
: api_map[endpoint.replace("/", "")];
const info = cat[endpoint];
new_data[key][endpoint] = {};
new_data[key][endpoint].parameters = {};
new_data[key][endpoint].returns = {};
new_data[key][endpoint].type = config.dependencies[dep_index].types;
new_data[key][endpoint].parameters = info.parameters.map(
({ label, component, type, serializer }) => ({
label,
component,
type: get_type(type, component, serializer, "parameter"),
description: get_description(type, serializer)
})
);
new_data[key][endpoint].returns = info.returns.map(
({ label, component, type, serializer }) => ({
label,
component,
type: get_type(type, component, serializer, "return"),
description: get_description(type, serializer)
})
);
}
}
return new_data;
}
async function get_jwt(
space: string,
token: `hf_${string}`
): Promise<string | false> {
try {
const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
headers: {
Authorization: `Bearer ${token}`
}
});
const jwt = (await r.json()).token;
return jwt || false;
} catch (e) {
console.error(e);
return false;
}
}
function update_object(object, newValue, stack) {
while (stack.length > 1) {
object = object[stack.shift()];
}
object[stack.shift()] = newValue;
}
export async function walk_and_store_blobs(
param,