fffiloni commited on
Commit
4fedb7c
1 Parent(s): 85e6869

Upload 27 files

Browse files
node_modules/@gradio/.DS_Store ADDED
Binary file (6.15 kB). View file
 
node_modules/@gradio/client/.DS_Store ADDED
Binary file (6.15 kB). View file
 
node_modules/@gradio/client/CHANGELOG.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @gradio/client
2
+
3
+ ## 0.10.1
4
+
5
+ ### Fixes
6
+
7
+ - [#7055](https://github.com/gradio-app/gradio/pull/7055) [`3c3cf86`](https://github.com/gradio-app/gradio/commit/3c3cf8618a8cad1ef66a7f96664923d2c9f5e0e2) - Fix UI freeze on rapid generators. Thanks [@aliabid94](https://github.com/aliabid94)!
8
+
9
+ ## 0.10.0
10
+
11
+ ### Features
12
+
13
+ - [#6931](https://github.com/gradio-app/gradio/pull/6931) [`6c863af`](https://github.com/gradio-app/gradio/commit/6c863af92fa9ceb5c638857eb22cc5ddb718d549) - Fix functional tests. Thanks [@aliabid94](https://github.com/aliabid94)!
14
+ - [#6820](https://github.com/gradio-app/gradio/pull/6820) [`649cd4d`](https://github.com/gradio-app/gradio/commit/649cd4d68041d11fcbe31f8efa455345ac49fc74) - Use `EventSource_factory` in `open_stream()` for Wasm. Thanks [@whitphx](https://github.com/whitphx)!
15
+
16
+ ## 0.9.4
17
+
18
+ ### Fixes
19
+
20
+ - [#6863](https://github.com/gradio-app/gradio/pull/6863) [`d406855`](https://github.com/gradio-app/gradio/commit/d4068557953746662235d595ec435c42ceb24414) - Fix JS Client when app is running behind a proxy. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
21
+
22
+ ## 0.9.3
23
+
24
+ ### Features
25
+
26
+ - [#6814](https://github.com/gradio-app/gradio/pull/6814) [`828fb9e`](https://github.com/gradio-app/gradio/commit/828fb9e6ce15b6ea08318675a2361117596a1b5d) - Refactor queue so that there are separate queues for each concurrency id. Thanks [@aliabid94](https://github.com/aliabid94)!
27
+
28
+ ## 0.9.2
29
+
30
+ ### Features
31
+
32
+ - [#6798](https://github.com/gradio-app/gradio/pull/6798) [`245d58e`](https://github.com/gradio-app/gradio/commit/245d58eff788e8d44a59d37a2d9b26d0f08a62b4) - Improve how server/js client handle unexpected errors. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
33
+
34
+ ## 0.9.1
35
+
36
+ ### Fixes
37
+
38
+ - [#6693](https://github.com/gradio-app/gradio/pull/6693) [`34f9431`](https://github.com/gradio-app/gradio/commit/34f943101bf7dd6b8a8974a6131c1ed7c4a0dac0) - Python client properly handles hearbeat and log messages. Also handles responses longer than 65k. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
39
+
40
+ ## 0.9.0
41
+
42
+ ### Features
43
+
44
+ - [#6398](https://github.com/gradio-app/gradio/pull/6398) [`67ddd40`](https://github.com/gradio-app/gradio/commit/67ddd40b4b70d3a37cb1637c33620f8d197dbee0) - Lite v4. Thanks [@whitphx](https://github.com/whitphx)!
45
+
46
+ ### Fixes
47
+
48
+ - [#6556](https://github.com/gradio-app/gradio/pull/6556) [`d76bcaa`](https://github.com/gradio-app/gradio/commit/d76bcaaaf0734aaf49a680f94ea9d4d22a602e70) - Fix api event drops. Thanks [@aliabid94](https://github.com/aliabid94)!
49
+
50
+ ## 0.8.2
51
+
52
+ ### Features
53
+
54
+ - [#6511](https://github.com/gradio-app/gradio/pull/6511) [`71f1a1f99`](https://github.com/gradio-app/gradio/commit/71f1a1f9931489d465c2c1302a5c8d768a3cd23a) - Mark `FileData.orig_name` optional on the frontend aligning the type definition on the Python side. Thanks [@whitphx](https://github.com/whitphx)!
55
+
56
+ ## 0.8.1
57
+
58
+ ### Fixes
59
+
60
+ - [#6383](https://github.com/gradio-app/gradio/pull/6383) [`324867f63`](https://github.com/gradio-app/gradio/commit/324867f63c920113d89a565892aa596cf8b1e486) - Fix event target. Thanks [@aliabid94](https://github.com/aliabid94)!
61
+
62
+ ## 0.8.0
63
+
64
+ ### Features
65
+
66
+ - [#6307](https://github.com/gradio-app/gradio/pull/6307) [`f1409f95e`](https://github.com/gradio-app/gradio/commit/f1409f95ed39c5565bed6a601e41f94e30196a57) - Provide status updates on file uploads. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
67
+
68
+ ## 0.7.2
69
+
70
+ ### Fixes
71
+
72
+ - [#6327](https://github.com/gradio-app/gradio/pull/6327) [`bca6c2c80`](https://github.com/gradio-app/gradio/commit/bca6c2c80f7e5062427019de45c282238388af95) - Restore query parameters in request. Thanks [@aliabid94](https://github.com/aliabid94)!
73
+
74
+ ## 0.7.1
75
+
76
+ ### Features
77
+
78
+ - [#6137](https://github.com/gradio-app/gradio/pull/6137) [`2ba14b284`](https://github.com/gradio-app/gradio/commit/2ba14b284f908aa13859f4337167a157075a68eb) - JS Param. Thanks [@dawoodkhan82](https://github.com/dawoodkhan82)!
79
+
80
+ ## 0.7.0
81
+
82
+ ### Features
83
+
84
+ - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)!
85
+ - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Image v4. Thanks [@pngwn](https://github.com/pngwn)!
86
+ - [#5498](https://github.com/gradio-app/gradio/pull/5498) [`287fe6782`](https://github.com/gradio-app/gradio/commit/287fe6782825479513e79a5cf0ba0fbfe51443d7) - Swap websockets for SSE. Thanks [@pngwn](https://github.com/pngwn)!
87
+
88
+ ## 0.7.0-beta.1
89
+
90
+ ### Features
91
+
92
+ - [#6143](https://github.com/gradio-app/gradio/pull/6143) [`e4f7b4b40`](https://github.com/gradio-app/gradio/commit/e4f7b4b409323b01aa01b39e15ce6139e29aa073) - fix circular dependency with client + upload. Thanks [@pngwn](https://github.com/pngwn)!
93
+ - [#6094](https://github.com/gradio-app/gradio/pull/6094) [`c476bd5a5`](https://github.com/gradio-app/gradio/commit/c476bd5a5b70836163b9c69bf4bfe068b17fbe13) - Image v4. Thanks [@pngwn](https://github.com/pngwn)!
94
+ - [#6069](https://github.com/gradio-app/gradio/pull/6069) [`bf127e124`](https://github.com/gradio-app/gradio/commit/bf127e1241a41401e144874ea468dff8474eb505) - Swap websockets for SSE. Thanks [@aliabid94](https://github.com/aliabid94)!
95
+
96
+ ## 0.7.0-beta.0
97
+
98
+ ### Features
99
+
100
+ - [#6016](https://github.com/gradio-app/gradio/pull/6016) [`83e947676`](https://github.com/gradio-app/gradio/commit/83e947676d327ca2ab6ae2a2d710c78961c771a0) - Format js in v4 branch. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
101
+
102
+ ### Fixes
103
+
104
+ - [#6046](https://github.com/gradio-app/gradio/pull/6046) [`dbb7de5e0`](https://github.com/gradio-app/gradio/commit/dbb7de5e02c53fee05889d696d764d212cb96c74) - fix tests. Thanks [@pngwn](https://github.com/pngwn)!
105
+
106
+ ## 0.6.0
107
+
108
+ ### Features
109
+
110
+ - [#5972](https://github.com/gradio-app/gradio/pull/5972) [`11a300791`](https://github.com/gradio-app/gradio/commit/11a3007916071f0791844b0a37f0fb4cec69cea3) - Lite: Support opening the entrypoint HTML page directly in browser via the `file:` protocol. Thanks [@whitphx](https://github.com/whitphx)!
111
+
112
+ ## 0.5.2
113
+
114
+ ### Fixes
115
+
116
+ - [#5840](https://github.com/gradio-app/gradio/pull/5840) [`4e62b8493`](https://github.com/gradio-app/gradio/commit/4e62b8493dfce50bafafe49f1a5deb929d822103) - Ensure websocket polyfill doesn't load if there is already a `global.Webocket` property set. Thanks [@Jay2theWhy](https://github.com/Jay2theWhy)!
117
+
118
+ ## 0.5.1
119
+
120
+ ### Fixes
121
+
122
+ - [#5816](https://github.com/gradio-app/gradio/pull/5816) [`796145e2c`](https://github.com/gradio-app/gradio/commit/796145e2c48c4087bec17f8ec0be4ceee47170cb) - Fix calls to the component server so that `gr.FileExplorer` works on Spaces. Thanks [@abidlabs](https://github.com/abidlabs)!
123
+
124
+ ## 0.5.0
125
+
126
+ ### Highlights
127
+
128
+ #### new `FileExplorer` component ([#5672](https://github.com/gradio-app/gradio/pull/5672) [`e4a307ed6`](https://github.com/gradio-app/gradio/commit/e4a307ed6cde3bbdf4ff2f17655739addeec941e))
129
+
130
+ Thanks to a new capability that allows components to communicate directly with the server _without_ passing data via the value, we have created a new `FileExplorer` component.
131
+
132
+ This component allows you to populate the explorer by passing a glob, but only provides the selected file(s) in your prediction function.
133
+
134
+ Users can then navigate the virtual filesystem and select files which will be accessible in your predict function. This component will allow developers to build more complex spaces, with more flexible input options.
135
+
136
+ ![output](https://github.com/pngwn/MDsveX/assets/12937446/ef108f0b-0e84-4292-9984-9dc66b3e144d)
137
+
138
+ For more information check the [`FileExplorer` documentation](https://gradio.app/docs/fileexplorer).
139
+
140
+ Thanks [@aliabid94](https://github.com/aliabid94)!
141
+
142
+ ### Features
143
+
144
+ - [#5787](https://github.com/gradio-app/gradio/pull/5787) [`caeee8bf7`](https://github.com/gradio-app/gradio/commit/caeee8bf7821fd5fe2f936ed82483bed00f613ec) - ensure the client does not depend on `window` when running in a node environment. Thanks [@gibiee](https://github.com/gibiee)!
145
+
146
+ ### Fixes
147
+
148
+ - [#5776](https://github.com/gradio-app/gradio/pull/5776) [`c0fef4454`](https://github.com/gradio-app/gradio/commit/c0fef44541bfa61568bdcfcdfc7d7d79869ab1df) - Revert replica proxy logic and instead implement using the `root` variable. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
149
+
150
+ ## 0.4.2
151
+
152
+ ### Features
153
+
154
+ - [#5124](https://github.com/gradio-app/gradio/pull/5124) [`6e56a0d9b`](https://github.com/gradio-app/gradio/commit/6e56a0d9b0c863e76c69e1183d9d40196922b4cd) - Lite: Websocket queueing. Thanks [@whitphx](https://github.com/whitphx)!
155
+
156
+ ## 0.4.1
157
+
158
+ ### Fixes
159
+
160
+ - [#5705](https://github.com/gradio-app/gradio/pull/5705) [`78e7cf516`](https://github.com/gradio-app/gradio/commit/78e7cf5163e8d205e8999428fce4c02dbdece25f) - ensure internal data has updated before dispatching `success` or `then` events. Thanks [@pngwn](https://github.com/pngwn)!
161
+
162
+ ## 0.4.0
163
+
164
+ ### Features
165
+
166
+ - [#5682](https://github.com/gradio-app/gradio/pull/5682) [`c57f1b75e`](https://github.com/gradio-app/gradio/commit/c57f1b75e272c76b0af4d6bd0c7f44743ff34f26) - Fix functional tests. Thanks [@abidlabs](https://github.com/abidlabs)!
167
+ - [#5681](https://github.com/gradio-app/gradio/pull/5681) [`40de3d217`](https://github.com/gradio-app/gradio/commit/40de3d2178b61ebe424b6f6228f94c0c6f679bea) - add query parameters to the `gr.Request` object through the `query_params` attribute. Thanks [@DarhkVoyd](https://github.com/DarhkVoyd)!
168
+ - [#5653](https://github.com/gradio-app/gradio/pull/5653) [`ea0e00b20`](https://github.com/gradio-app/gradio/commit/ea0e00b207b4b90a10e9d054c4202d4e705a29ba) - Prevent Clients from accessing API endpoints that set `api_name=False`. Thanks [@abidlabs](https://github.com/abidlabs)!
169
+
170
+ ## 0.3.1
171
+
172
+ ### Fixes
173
+
174
+ - [#5412](https://github.com/gradio-app/gradio/pull/5412) [`26fef8c7`](https://github.com/gradio-app/gradio/commit/26fef8c7f85a006c7e25cdbed1792df19c512d02) - Skip view_api request in js client when auth enabled. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
175
+
176
+ ## 0.3.0
177
+
178
+ ### Features
179
+
180
+ - [#5267](https://github.com/gradio-app/gradio/pull/5267) [`119c8343`](https://github.com/gradio-app/gradio/commit/119c834331bfae60d4742c8f20e9cdecdd67e8c2) - Faster reload mode. Thanks [@freddyaboulton](https://github.com/freddyaboulton)!
181
+
182
+ ## 0.2.1
183
+
184
+ ### Features
185
+
186
+ - [#5173](https://github.com/gradio-app/gradio/pull/5173) [`730f0c1d`](https://github.com/gradio-app/gradio/commit/730f0c1d54792eb11359e40c9f2326e8a6e39203) - Ensure gradio client works as expected for functions that return nothing. Thanks [@raymondtri](https://github.com/raymondtri)!
187
+
188
+ ## 0.2.0
189
+
190
+ ### Features
191
+
192
+ - [#5133](https://github.com/gradio-app/gradio/pull/5133) [`61129052`](https://github.com/gradio-app/gradio/commit/61129052ed1391a75c825c891d57fa0ad6c09fc8) - Update dependency esbuild to ^0.19.0. Thanks [@renovate](https://github.com/apps/renovate)!
193
+ - [#5035](https://github.com/gradio-app/gradio/pull/5035) [`8b4eb8ca`](https://github.com/gradio-app/gradio/commit/8b4eb8cac9ea07bde31b44e2006ca2b7b5f4de36) - JS Client: Fixes cannot read properties of null (reading 'is_file'). Thanks [@raymondtri](https://github.com/raymondtri)!
194
+
195
+ ### Fixes
196
+
197
+ - [#5075](https://github.com/gradio-app/gradio/pull/5075) [`67265a58`](https://github.com/gradio-app/gradio/commit/67265a58027ef1f9e4c0eb849a532f72eaebde48) - Allow supporting >1000 files in `gr.File()` and `gr.UploadButton()`. Thanks [@abidlabs](https://github.com/abidlabs)!
198
+
199
+ ## 0.1.4
200
+
201
+ ### Patch Changes
202
+
203
+ - [#4717](https://github.com/gradio-app/gradio/pull/4717) [`ab5d1ea0`](https://github.com/gradio-app/gradio/commit/ab5d1ea0de87ed888779b66fd2a705583bd29e02) Thanks [@whitphx](https://github.com/whitphx)! - Fix the package description
204
+
205
+ ## 0.1.3
206
+
207
+ ### Patch Changes
208
+
209
+ - [#4357](https://github.com/gradio-app/gradio/pull/4357) [`0dbd8f7f`](https://github.com/gradio-app/gradio/commit/0dbd8f7fee4b4877f783fa7bc493f98bbfc3d01d) Thanks [@pngwn](https://github.com/pngwn)! - Various internal refactors and cleanups.
210
+
211
+ ## 0.1.2
212
+
213
+ ### Patch Changes
214
+
215
+ - [#4273](https://github.com/gradio-app/gradio/pull/4273) [`1d0f0a9d`](https://github.com/gradio-app/gradio/commit/1d0f0a9db096552e67eb2197c932342587e9e61e) Thanks [@pngwn](https://github.com/pngwn)! - Ensure websocket error messages are correctly handled.
216
+
217
+ - [#4315](https://github.com/gradio-app/gradio/pull/4315) [`b525b122`](https://github.com/gradio-app/gradio/commit/b525b122dd8569bbaf7e06db5b90d622d2e9073d) Thanks [@whitphx](https://github.com/whitphx)! - Refacor types.
218
+
219
+ - [#4271](https://github.com/gradio-app/gradio/pull/4271) [`1151c525`](https://github.com/gradio-app/gradio/commit/1151c5253554cb87ebd4a44a8a470ac215ff782b) Thanks [@pngwn](https://github.com/pngwn)! - Ensure the full root path is always respected when making requests to a gradio app server.
220
+
221
+ ## 0.1.1
222
+
223
+ ### Patch Changes
224
+
225
+ - [#4201](https://github.com/gradio-app/gradio/pull/4201) [`da5b4ee1`](https://github.com/gradio-app/gradio/commit/da5b4ee11721175858ded96e5710225369097f74) Thanks [@pngwn](https://github.com/pngwn)! - Ensure semiver is bundled so CDN links work correctly.
226
+
227
+ - [#4202](https://github.com/gradio-app/gradio/pull/4202) [`a26e9afd`](https://github.com/gradio-app/gradio/commit/a26e9afde319382993e6ddc77cc4e56337a31248) Thanks [@pngwn](https://github.com/pngwn)! - Ensure all URLs returned by the client are complete URLs with the correct host instead of an absolute path relative to a server.
228
+
229
+ ## 0.1.0
230
+
231
+ ### Minor Changes
232
+
233
+ - [#4185](https://github.com/gradio-app/gradio/pull/4185) [`67239ca9`](https://github.com/gradio-app/gradio/commit/67239ca9b2fe3796853fbf7bf865c9e4b383200d) Thanks [@pngwn](https://github.com/pngwn)! - Update client for initial release
234
+
235
+ ### Patch Changes
236
+
237
+ - [#3692](https://github.com/gradio-app/gradio/pull/3692) [`48e8b113`](https://github.com/gradio-app/gradio/commit/48e8b113f4b55e461d9da4f153bf72aeb4adf0f1) Thanks [@pngwn](https://github.com/pngwn)! - Ensure client works in node, create ESM bundle and generate typescript declaration files.
238
+
239
+ - [#3605](https://github.com/gradio-app/gradio/pull/3605) [`ae4277a9`](https://github.com/gradio-app/gradio/commit/ae4277a9a83d49bdadfe523b0739ba988128e73b) Thanks [@pngwn](https://github.com/pngwn)! - Update readme.
node_modules/@gradio/client/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
node_modules/@gradio/client/README.md ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## JavaScript Client Library
2
+
3
+ A javascript (and typescript) client to call Gradio APIs.
4
+
5
+ ## Installation
6
+
7
+ The Gradio JavaScript client is available on npm as `@gradio/client`. You can install it as below:
8
+
9
+ ```sh
10
+ npm i @gradio/client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ The JavaScript Gradio Client exposes two named imports, `client` and `duplicate`.
16
+
17
+ ### `client`
18
+
19
+ The client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API.
20
+
21
+ The simplest example looks like this:
22
+
23
+ ```ts
24
+ import { client } from "@gradio/client";
25
+
26
+ const app = await client("user/space-name");
27
+ const result = await app.predict("/predict");
28
+ ```
29
+
30
+ This function accepts two arguments: `source` and `options`:
31
+
32
+ #### `source`
33
+
34
+ This is the url or name of the gradio app whose API you wish to connect to. This parameter is required and should always be a string. For example:
35
+
36
+ ```ts
37
+ client("user/space-name");
38
+ ```
39
+
40
+ #### `options`
41
+
42
+ The options object can optionally be passed a second parameter. This object has two properties, `hf_token` and `status_callback`.
43
+
44
+ ##### `hf_token`
45
+
46
+ This should be a Hugging Face personal access token and is required if you wish to make calls to a private gradio api. This option is optional and should be a string starting with `"hf_"`.
47
+
48
+ Example:
49
+
50
+ ```ts
51
+ import { client } from "@gradio/client";
52
+
53
+ const app = await client("user/space-name", { hf_token: "hf_..." });
54
+ ```
55
+
56
+ ##### `status_callback`
57
+
58
+ This should be a function which will notify your of the status of a space if it is not running. If the gradio API you are connecting to is awake and running or is not hosted on Hugging Face space then this function will do nothing.
59
+
60
+ **Additional context**
61
+
62
+ Applications hosted on Hugging Face spaces can be in a number of different states. As spaces are a GitOps tool and will rebuild when new changes are pushed to the repository, they have various building, running and error states. If a space is not 'running' then the function passed as the `status_callback` will notify you of the current state of the space and the status of the space as it changes. Spaces that are building or sleeping can take longer than usual to respond, so you can use this information to give users feedback about the progress of their action.
63
+
64
+ ```ts
65
+ import { client, type SpaceStatus } from "@gradio/client";
66
+
67
+ const app = await client("user/space-name", {
68
+ // The space_status parameter does not need to be manually annotated, this is just for illustration.
69
+ space_status: (space_status: SpaceStatus) => console.log(space_status)
70
+ });
71
+ ```
72
+
73
+ ```ts
74
+ interface SpaceStatusNormal {
75
+ status: "sleeping" | "running" | "building" | "error" | "stopped";
76
+ detail:
77
+ | "SLEEPING"
78
+ | "RUNNING"
79
+ | "RUNNING_BUILDING"
80
+ | "BUILDING"
81
+ | "NOT_FOUND";
82
+ load_status: "pending" | "error" | "complete" | "generating";
83
+ message: string;
84
+ }
85
+
86
+ interface SpaceStatusError {
87
+ status: "space_error";
88
+ detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR";
89
+ load_status: "error";
90
+ message: string;
91
+ discussions_enabled: boolean;
92
+
93
+ type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
94
+ ```
95
+
96
+ The gradio client returns an object with a number of methods and properties:
97
+
98
+ #### `predict`
99
+
100
+ The `predict` method allows you to call an api endpoint and get a prediction result:
101
+
102
+ ```ts
103
+ import { client } from "@gradio/client";
104
+
105
+ const app = await client("user/space-name");
106
+ const result = await app.predict("/predict");
107
+ ```
108
+
109
+ `predict` accepts two parameters, `endpoint` and `payload`. It returns a promise that resolves to the prediction result.
110
+
111
+ ##### `endpoint`
112
+
113
+ This is the endpoint for an api request and is required. The default endpoint for a `gradio.Interface` is `"/predict"`. Explicitly named endpoints have a custom name. The endpoint names can be found on the "View API" page of a space.
114
+
115
+ ```ts
116
+ import { client } from "@gradio/client";
117
+
118
+ const app = await client("user/space-name");
119
+ const result = await app.predict("/predict");
120
+ ```
121
+
122
+ ##### `payload`
123
+
124
+ The `payload` argument is generally optional but this depends on the API itself. If the API endpoint depends on values being passed in then it is required for the API request to succeed. The data that should be passed in is detailed on the "View API" page of a space, or accessible via the `view_api()` method of the client.
125
+
126
+ ```ts
127
+ import { client } from "@gradio/client";
128
+
129
+ const app = await client("user/space-name");
130
+ const result = await app.predict("/predict", [1, "Hello", "friends"]);
131
+ ```
132
+
133
+ #### `submit`
134
+
135
+ The `submit` method provides a more flexible way to call an API endpoint, providing you with status updates about the current progress of the prediction as well as supporting more complex endpoint types.
136
+
137
+ ```ts
138
+ import { client } from "@gradio/client";
139
+
140
+ const app = await client("user/space-name");
141
+ const submission = app.submit("/predict", payload);
142
+ ```
143
+
144
+ The `submit` method accepts the same [`endpoint`](#endpoint) and [`payload`](#payload) arguments as `predict`.
145
+
146
+ The `submit` method does not return a promise and should not be awaited, instead it returns an object with a `on`, `off`, and `cancel` methods.
147
+
148
+ ##### `on`
149
+
150
+ The `on` method allows you to subscribe to events related to the submitted API request. There are two types of event that can be subscribed to: `"data"` updates and `"status"` updates.
151
+
152
+ `"data"` updates are issued when the API computes a value, the callback provided as the second argument will be called when such a value is sent to the client. The shape of the data depends on the way the API itself is constructed. This event may fire more than once if that endpoint supports emmitting new values over time.
153
+
154
+ `"status` updates are issued when the status of a request changes. This information allows you to offer feedback to users when the queue position of the request changes, or when the request changes from queued to processing.
155
+
156
+ The status payload look like this:
157
+
158
+ ```ts
159
+ interface Status {
160
+ queue: boolean;
161
+ code?: string;
162
+ success?: boolean;
163
+ stage: "pending" | "error" | "complete" | "generating";
164
+ size?: number;
165
+ position?: number;
166
+ eta?: number;
167
+ message?: string;
168
+ progress_data?: Array<{
169
+ progress: number | null;
170
+ index: number | null;
171
+ length: number | null;
172
+ unit: string | null;
173
+ desc: string | null;
174
+ }>;
175
+ time?: Date;
176
+ }
177
+ ```
178
+
179
+ Usage of these subscribe callback looks like this:
180
+
181
+ ```ts
182
+ import { client } from "@gradio/client";
183
+
184
+ const app = await client("user/space-name");
185
+ const submission = app
186
+ .submit("/predict", payload)
187
+ .on("data", (data) => console.log(data))
188
+ .on("status", (status: Status) => console.log(status));
189
+ ```
190
+
191
+ ##### `off`
192
+
193
+ The `off` method unsubscribes from a specific event of the submitted job and works similarly to `document.removeEventListener`; both the event name and the original callback must be passed in to successfully unsubscribe:
194
+
195
+ ```ts
196
+ import { client } from "@gradio/client";
197
+
198
+ const app = await client("user/space-name");
199
+ const handle_data = (data) => console.log(data);
200
+
201
+ const submission = app.submit("/predict", payload).on("data", handle_data);
202
+
203
+ // later
204
+ submission.off("/predict", handle_data);
205
+ ```
206
+
207
+ ##### `destroy`
208
+
209
+ The `destroy` method will remove all subscriptions to a job, regardless of whether or not they are `"data"` or `"status"` events. This is a convenience method for when you do not want to unsubscribe use the `off` method.
210
+
211
+ ```js
212
+ import { client } from "@gradio/client";
213
+
214
+ const app = await client("user/space-name");
215
+ const handle_data = (data) => console.log(data);
216
+
217
+ const submission = app.submit("/predict", payload).on("data", handle_data);
218
+
219
+ // later
220
+ submission.destroy();
221
+ ```
222
+
223
+ ##### `cancel`
224
+
225
+ Certain types of gradio function can run repeatedly and in some cases indefinitely. the `cancel` method will stop such an endpoints and prevent the API from issuing additional updates.
226
+
227
+ ```ts
228
+ import { client } from "@gradio/client";
229
+
230
+ const app = await client("user/space-name");
231
+ const submission = app
232
+ .submit("/predict", payload)
233
+ .on("data", (data) => console.log(data));
234
+
235
+ // later
236
+
237
+ submission.cancel();
238
+ ```
239
+
240
+ #### `view_api`
241
+
242
+ The `view_api` method provides details about the API you are connected to. It returns a JavaScript object of all named endpoints, unnamed endpoints and what values they accept and return. This method does not accept arguments.
243
+
244
+ ```ts
245
+ import { client } from "@gradio/client";
246
+
247
+ const app = await client("user/space-name");
248
+ const api_info = await app.view_api();
249
+
250
+ console.log(api_info);
251
+ ```
252
+
253
+ #### `config`
254
+
255
+ The `config` property contains the configuration for the gradio application you are connected to. This object may contain useful meta information about the application.
256
+
257
+ ```ts
258
+ import { client } from "@gradio/client";
259
+
260
+ const app = await client("user/space-name");
261
+ console.log(app.config);
262
+ ```
263
+
264
+ ### `duplicate`
265
+
266
+ The duplicate function will attempt to duplicate the space that is referenced and return an instance of `client` connected to that space. If the space has already been duplicated then it will not create a new duplicate and will instead connect to the existing duplicated space. The huggingface token that is passed in will dictate the user under which the space is created.
267
+
268
+ `duplicate` accepts the same arguments as `client` with the addition of a `private` options property dictating whether the duplicated space should be private or public. A huggingface token is required for duplication to work.
269
+
270
+ ```ts
271
+ import { duplicate } from "@gradio/client";
272
+
273
+ const app = await duplicate("user/space-name", {
274
+ hf_token: "hf_..."
275
+ });
276
+ ```
277
+
278
+ This function accepts two arguments: `source` and `options`:
279
+
280
+ #### `source`
281
+
282
+ The space to duplicate and connect to. [See `client`'s `source` parameter](#source).
283
+
284
+ #### `options`
285
+
286
+ Accepts all options that `client` accepts, except `hf_token` is required. [See `client`'s `options` parameter](#source).
287
+
288
+ `duplicate` also accepts one additional `options` property.
289
+
290
+ ##### `private`
291
+
292
+ This is an optional property specific to `duplicate`'s options object and will determine whether the space should be public or private. Spaces duplicated via the `duplicate` method are public by default.
293
+
294
+ ```ts
295
+ import { duplicate } from "@gradio/client";
296
+
297
+ const app = await duplicate("user/space-name", {
298
+ hf_token: "hf_...",
299
+ private: true
300
+ });
301
+ ```
302
+
303
+ ##### `timeout`
304
+
305
+ This is an optional property specific to `duplicate`'s options object and will set the timeout in minutes before the duplicated space will go to sleep.
306
+
307
+ ```ts
308
+ import { duplicate } from "@gradio/client";
309
+
310
+ const app = await duplicate("user/space-name", {
311
+ hf_token: "hf_...",
312
+ private: true,
313
+ timeout: 5
314
+ });
315
+ ```
316
+
317
+ ##### `hardware`
318
+
319
+ This is an optional property specific to `duplicate`'s options object and will set the hardware for the duplicated space. By default the hardware used will match that of the original space. If this cannot be obtained it will default to `"cpu-basic"`. For hardware upgrades (beyond the basic CPU tier), you may be required to provide [billing information on Hugging Face](https://huggingface.co/settings/billing).
320
+
321
+ Possible hardware options are:
322
+
323
+ - `"cpu-basic"`
324
+ - `"cpu-upgrade"`
325
+ - `"t4-small"`
326
+ - `"t4-medium"`
327
+ - `"a10g-small"`
328
+ - `"a10g-large"`
329
+ - `"a100-large"`
330
+
331
+ ```ts
332
+ import { duplicate } from "@gradio/client";
333
+
334
+ const app = await duplicate("user/space-name", {
335
+ hf_token: "hf_...",
336
+ private: true,
337
+ hardware: "a10g-small"
338
+ });
339
+ ```
node_modules/@gradio/client/dist/client.d.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { hardware_types } from "./utils.js";
2
+ import type { EventType, EventListener, PostResponse, UploadResponse, SpaceStatusCallback } from "./types.js";
3
+ import type { Config } from "./types.js";
4
+ type event = <K extends EventType>(eventType: K, listener: EventListener<K>) => SubmitReturn;
5
+ type predict = (endpoint: string | number, data?: unknown[], event_data?: unknown) => Promise<unknown>;
6
+ type client_return = {
7
+ predict: predict;
8
+ config: Config;
9
+ submit: (endpoint: string | number, data?: unknown[], event_data?: unknown, trigger_id?: number | null) => SubmitReturn;
10
+ component_server: (component_id: number, fn_name: string, data: unknown[]) => any;
11
+ view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
12
+ };
13
+ type SubmitReturn = {
14
+ on: event;
15
+ off: event;
16
+ cancel: () => Promise<void>;
17
+ destroy: () => void;
18
+ };
19
+ export declare let NodeBlob: any;
20
+ export declare function duplicate(app_reference: string, options: {
21
+ hf_token: `hf_${string}`;
22
+ private?: boolean;
23
+ status_callback: SpaceStatusCallback;
24
+ hardware?: (typeof hardware_types)[number];
25
+ timeout?: number;
26
+ }): Promise<client_return>;
27
+ interface Client {
28
+ post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>;
29
+ upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise<UploadResponse>;
30
+ client: (app_reference: string, options: {
31
+ hf_token?: `hf_${string}`;
32
+ status_callback?: SpaceStatusCallback;
33
+ normalise_files?: boolean;
34
+ }) => Promise<client_return>;
35
+ handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo<JsApiData>, token?: `hf_${string}`) => Promise<unknown[]>;
36
+ }
37
+ export declare function api_factory(fetch_implementation: typeof fetch, EventSource_factory: (url: URL) => EventSource): Client;
38
+ export declare const post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>, upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise<UploadResponse>, client: (app_reference: string, options: {
39
+ hf_token?: `hf_${string}`;
40
+ status_callback?: SpaceStatusCallback;
41
+ normalise_files?: boolean;
42
+ }) => Promise<client_return>, handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo<JsApiData>, token?: `hf_${string}`) => Promise<unknown[]>;
43
+ interface ApiData {
44
+ label: string;
45
+ type: {
46
+ type: any;
47
+ description: string;
48
+ };
49
+ component: string;
50
+ example_input?: any;
51
+ }
52
+ interface JsApiData {
53
+ label: string;
54
+ type: string;
55
+ component: string;
56
+ example_input: any;
57
+ }
58
+ interface EndpointInfo<T extends ApiData | JsApiData> {
59
+ parameters: T[];
60
+ returns: T[];
61
+ }
62
+ interface ApiInfo<T extends ApiData | JsApiData> {
63
+ named_endpoints: {
64
+ [key: string]: EndpointInfo<T>;
65
+ };
66
+ unnamed_endpoints: {
67
+ [key: string]: EndpointInfo<T>;
68
+ };
69
+ }
70
+ export declare function walk_and_store_blobs(param: any, type?: any, path?: any[], root?: boolean, api_info?: any): Promise<{
71
+ path: string[];
72
+ type: string;
73
+ blob: Blob | false;
74
+ }[]>;
75
+ export {};
76
+ //# sourceMappingURL=client.d.ts.map
node_modules/@gradio/client/dist/client.d.ts.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAIA,OAAO,EAQN,cAAc,EAEd,MAAM,YAAY,CAAC;AAEpB,OAAO,KAAK,EACX,SAAS,EACT,aAAa,EAIb,YAAY,EACZ,cAAc,EAGd,mBAAmB,EACnB,MAAM,YAAY,CAAC;AAIpB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,KAAK,KAAK,GAAG,CAAC,CAAC,SAAS,SAAS,EAChC,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,KACtB,YAAY,CAAC;AAClB,KAAK,OAAO,GAAG,CACd,QAAQ,EAAE,MAAM,GAAG,MAAM,EACzB,IAAI,CAAC,EAAE,OAAO,EAAE,EAChB,UAAU,CAAC,EAAE,OAAO,KAChB,OAAO,CAAC,OAAO,CAAC,CAAC;AAEtB,KAAK,aAAa,GAAG;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CACP,QAAQ,EAAE,MAAM,GAAG,MAAM,EACzB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G,CAAC;QACV,WAAW,EAAE,MAAM,CAAC;KACpB,CAAC;IACF,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,GAAG,CAAC;CACpB;AAED,UAAU,SAAS;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,GAAG,CAAC;CACnB;AAED,UAAU,YAAY,CAAC,CAAC,SAAS,OAAO,GAAG,SAAS;IACnD,UAAU,EAAE,CAAC,EAAE,CAAC;IAChB,OAAO,EAAE,CAAC,EAAE,CAAC;CACb;AACD,UAAU,OAAO,CAAC,CAAC,SAAS,OAAO,GAAG,SAAS;IAC9C,eAAe,EAAE;QAChB,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;KAC/B,CAAC;IACF,iBAAiB,EAAE;QAClB,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;KAC/B,CAAC;CACF;AAiID,wBAAsB,oBAAoB,CACzC,KAAK,KAAA,EACL,IAAI,MAAY,EAChB,IAAI,QAAK,EACT,IAAI,UAAQ,EACZ,QAAQ,MAAY,GAClB,OAAO,CACT;IACC,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,IAAI,GAAG,KAAK,CAAC;CACnB,EAAE,CACH,CAmDA"}
node_modules/@gradio/client/dist/index.d.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export { client, post_data, upload_files, duplicate, api_factory } from "./client.js";
2
+ export type { SpaceStatus } from "./types.js";
3
+ export { normalise_file, FileData, upload, get_fetchable_url_or_file, prepare_files } from "./upload.js";
4
+ //# sourceMappingURL=index.d.ts.map
node_modules/@gradio/client/dist/index.d.ts.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 resolve_root(base_url, root_path, prioritize_base) {
8
+ if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
9
+ return prioritize_base ? base_url : root_path;
10
+ }
11
+ return base_url + root_path;
12
+ }
13
+ function determine_protocol(endpoint) {
14
+ if (endpoint.startsWith("http")) {
15
+ const { protocol, host } = new URL(endpoint);
16
+ if (host.endsWith("hf.space")) {
17
+ return {
18
+ ws_protocol: "wss",
19
+ host,
20
+ http_protocol: protocol
21
+ };
22
+ }
23
+ return {
24
+ ws_protocol: protocol === "https:" ? "wss" : "ws",
25
+ http_protocol: protocol,
26
+ host
27
+ };
28
+ } else if (endpoint.startsWith("file:")) {
29
+ return {
30
+ ws_protocol: "ws",
31
+ http_protocol: "http:",
32
+ host: "lite.local"
33
+ // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`.
34
+ };
35
+ }
36
+ return {
37
+ ws_protocol: "wss",
38
+ http_protocol: "https:",
39
+ host: endpoint
40
+ };
41
+ }
42
+ const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
43
+ const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
44
+ async function process_endpoint(app_reference, token) {
45
+ const headers = {};
46
+ if (token) {
47
+ headers.Authorization = `Bearer ${token}`;
48
+ }
49
+ const _app_reference = app_reference.trim();
50
+ if (RE_SPACE_NAME.test(_app_reference)) {
51
+ try {
52
+ const res = await fetch(
53
+ `https://huggingface.co/api/spaces/${_app_reference}/host`,
54
+ { headers }
55
+ );
56
+ if (res.status !== 200)
57
+ throw new Error("Space metadata could not be loaded.");
58
+ const _host = (await res.json()).host;
59
+ return {
60
+ space_id: app_reference,
61
+ ...determine_protocol(_host)
62
+ };
63
+ } catch (e) {
64
+ throw new Error("Space metadata could not be loaded." + e.message);
65
+ }
66
+ }
67
+ if (RE_SPACE_DOMAIN.test(_app_reference)) {
68
+ const { ws_protocol, http_protocol, host } = determine_protocol(_app_reference);
69
+ return {
70
+ space_id: host.replace(".hf.space", ""),
71
+ ws_protocol,
72
+ http_protocol,
73
+ host
74
+ };
75
+ }
76
+ return {
77
+ space_id: false,
78
+ ...determine_protocol(_app_reference)
79
+ };
80
+ }
81
+ function map_names_to_ids(fns) {
82
+ let apis = {};
83
+ fns.forEach(({ api_name }, i) => {
84
+ if (api_name)
85
+ apis[api_name] = i;
86
+ });
87
+ return apis;
88
+ }
89
+ const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
90
+ async function discussions_enabled(space_id) {
91
+ try {
92
+ const r = await fetch(
93
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
94
+ {
95
+ method: "HEAD"
96
+ }
97
+ );
98
+ const error = r.headers.get("x-error-message");
99
+ if (error && RE_DISABLED_DISCUSSION.test(error))
100
+ return false;
101
+ return true;
102
+ } catch (e) {
103
+ return false;
104
+ }
105
+ }
106
+ async function get_space_hardware(space_id, token) {
107
+ const headers = {};
108
+ if (token) {
109
+ headers.Authorization = `Bearer ${token}`;
110
+ }
111
+ try {
112
+ const res = await fetch(
113
+ `https://huggingface.co/api/spaces/${space_id}/runtime`,
114
+ { headers }
115
+ );
116
+ if (res.status !== 200)
117
+ throw new Error("Space hardware could not be obtained.");
118
+ const { hardware } = await res.json();
119
+ return hardware;
120
+ } catch (e) {
121
+ throw new Error(e.message);
122
+ }
123
+ }
124
+ async function set_space_hardware(space_id, new_hardware, token) {
125
+ const headers = {};
126
+ if (token) {
127
+ headers.Authorization = `Bearer ${token}`;
128
+ }
129
+ try {
130
+ const res = await fetch(
131
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
132
+ { headers, body: JSON.stringify(new_hardware) }
133
+ );
134
+ if (res.status !== 200)
135
+ throw new Error(
136
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
137
+ );
138
+ const { hardware } = await res.json();
139
+ return hardware;
140
+ } catch (e) {
141
+ throw new Error(e.message);
142
+ }
143
+ }
144
+ async function set_space_timeout(space_id, timeout, token) {
145
+ const headers = {};
146
+ if (token) {
147
+ headers.Authorization = `Bearer ${token}`;
148
+ }
149
+ try {
150
+ const res = await fetch(
151
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
152
+ { headers, body: JSON.stringify({ seconds: timeout }) }
153
+ );
154
+ if (res.status !== 200)
155
+ throw new Error(
156
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
157
+ );
158
+ const { hardware } = await res.json();
159
+ return hardware;
160
+ } catch (e) {
161
+ throw new Error(e.message);
162
+ }
163
+ }
164
+ const hardware_types = [
165
+ "cpu-basic",
166
+ "cpu-upgrade",
167
+ "t4-small",
168
+ "t4-medium",
169
+ "a10g-small",
170
+ "a10g-large",
171
+ "a100-large"
172
+ ];
173
+ function normalise_file(file, server_url, proxy_url) {
174
+ if (file == null) {
175
+ return null;
176
+ }
177
+ if (Array.isArray(file)) {
178
+ const normalized_file = [];
179
+ for (const x of file) {
180
+ if (x == null) {
181
+ normalized_file.push(null);
182
+ } else {
183
+ normalized_file.push(normalise_file(x, server_url, proxy_url));
184
+ }
185
+ }
186
+ return normalized_file;
187
+ }
188
+ if (file.is_stream) {
189
+ if (proxy_url == null) {
190
+ return new FileData({
191
+ ...file,
192
+ url: server_url + "/stream/" + file.path
193
+ });
194
+ }
195
+ return new FileData({
196
+ ...file,
197
+ url: "/proxy=" + proxy_url + "stream/" + file.path
198
+ });
199
+ }
200
+ return new FileData({
201
+ ...file,
202
+ url: get_fetchable_url_or_file(file.path, server_url, proxy_url)
203
+ });
204
+ }
205
+ function is_url(str) {
206
+ try {
207
+ const url = new URL(str);
208
+ return url.protocol === "http:" || url.protocol === "https:";
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ function get_fetchable_url_or_file(path, server_url, proxy_url) {
214
+ if (path == null) {
215
+ return proxy_url ? `/proxy=${proxy_url}file=` : `${server_url}/file=`;
216
+ }
217
+ if (is_url(path)) {
218
+ return path;
219
+ }
220
+ return proxy_url ? `/proxy=${proxy_url}file=${path}` : `${server_url}/file=${path}`;
221
+ }
222
+ async function upload(file_data, root, upload_id, upload_fn = upload_files) {
223
+ let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
224
+ (file_data2) => file_data2.blob
225
+ );
226
+ return await Promise.all(
227
+ await upload_fn(root, files, void 0, upload_id).then(
228
+ async (response) => {
229
+ if (response.error) {
230
+ throw new Error(response.error);
231
+ } else {
232
+ if (response.files) {
233
+ return response.files.map((f, i) => {
234
+ const file = new FileData({ ...file_data[i], path: f });
235
+ return normalise_file(file, root, null);
236
+ });
237
+ }
238
+ return [];
239
+ }
240
+ }
241
+ )
242
+ );
243
+ }
244
+ async function prepare_files(files, is_stream) {
245
+ return files.map(
246
+ (f, i) => new FileData({
247
+ path: f.name,
248
+ orig_name: f.name,
249
+ blob: f,
250
+ size: f.size,
251
+ mime_type: f.type,
252
+ is_stream
253
+ })
254
+ );
255
+ }
256
+ class FileData {
257
+ constructor({
258
+ path,
259
+ url,
260
+ orig_name,
261
+ size,
262
+ blob,
263
+ is_stream,
264
+ mime_type,
265
+ alt_text
266
+ }) {
267
+ this.path = path;
268
+ this.url = url;
269
+ this.orig_name = orig_name;
270
+ this.size = size;
271
+ this.blob = url ? void 0 : blob;
272
+ this.is_stream = is_stream;
273
+ this.mime_type = mime_type;
274
+ this.alt_text = alt_text;
275
+ }
276
+ }
277
+ const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
278
+ const BROKEN_CONNECTION_MSG = "Connection errored out.";
279
+ let NodeBlob;
280
+ async function duplicate(app_reference, options) {
281
+ const { hf_token, private: _private, hardware, timeout } = options;
282
+ if (hardware && !hardware_types.includes(hardware)) {
283
+ throw new Error(
284
+ `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
285
+ );
286
+ }
287
+ const headers = {
288
+ Authorization: `Bearer ${hf_token}`
289
+ };
290
+ const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
291
+ headers
292
+ })).json()).name;
293
+ const space_name = app_reference.split("/")[1];
294
+ const body = {
295
+ repository: `${user}/${space_name}`
296
+ };
297
+ if (_private) {
298
+ body.private = true;
299
+ }
300
+ try {
301
+ const response = await fetch(
302
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
303
+ {
304
+ method: "POST",
305
+ headers: { "Content-Type": "application/json", ...headers },
306
+ body: JSON.stringify(body)
307
+ }
308
+ );
309
+ if (response.status === 409) {
310
+ return client(`${user}/${space_name}`, options);
311
+ }
312
+ const duplicated_space = await response.json();
313
+ let original_hardware;
314
+ if (!hardware) {
315
+ original_hardware = await get_space_hardware(app_reference, hf_token);
316
+ }
317
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
318
+ await set_space_hardware(
319
+ `${user}/${space_name}`,
320
+ requested_hardware,
321
+ hf_token
322
+ );
323
+ await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
324
+ return client(duplicated_space.url, options);
325
+ } catch (e) {
326
+ throw new Error(e);
327
+ }
328
+ }
329
+ function api_factory(fetch_implementation, EventSource_factory) {
330
+ return { post_data: post_data2, upload_files: upload_files2, client: client2, handle_blob: handle_blob2 };
331
+ async function post_data2(url, body, token) {
332
+ const headers = { "Content-Type": "application/json" };
333
+ if (token) {
334
+ headers.Authorization = `Bearer ${token}`;
335
+ }
336
+ try {
337
+ var response = await fetch_implementation(url, {
338
+ method: "POST",
339
+ body: JSON.stringify(body),
340
+ headers
341
+ });
342
+ } catch (e) {
343
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
344
+ }
345
+ let output;
346
+ let status;
347
+ try {
348
+ output = await response.json();
349
+ status = response.status;
350
+ } catch (e) {
351
+ output = { error: `Could not parse server response: ${e}` };
352
+ status = 500;
353
+ }
354
+ return [output, status];
355
+ }
356
+ async function upload_files2(root, files, token, upload_id) {
357
+ const headers = {};
358
+ if (token) {
359
+ headers.Authorization = `Bearer ${token}`;
360
+ }
361
+ const chunkSize = 1e3;
362
+ const uploadResponses = [];
363
+ for (let i = 0; i < files.length; i += chunkSize) {
364
+ const chunk = files.slice(i, i + chunkSize);
365
+ const formData = new FormData();
366
+ chunk.forEach((file) => {
367
+ formData.append("files", file);
368
+ });
369
+ try {
370
+ const upload_url = upload_id ? `${root}/upload?upload_id=${upload_id}` : `${root}/upload`;
371
+ var response = await fetch_implementation(upload_url, {
372
+ method: "POST",
373
+ body: formData,
374
+ headers
375
+ });
376
+ } catch (e) {
377
+ return { error: BROKEN_CONNECTION_MSG };
378
+ }
379
+ const output = await response.json();
380
+ uploadResponses.push(...output);
381
+ }
382
+ return { files: uploadResponses };
383
+ }
384
+ async function client2(app_reference, options = { normalise_files: true }) {
385
+ return new Promise(async (res) => {
386
+ const { status_callback, hf_token, normalise_files } = options;
387
+ const return_obj = {
388
+ predict,
389
+ submit,
390
+ view_api,
391
+ component_server
392
+ };
393
+ const transform_files = normalise_files ?? true;
394
+ if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.Websocket) {
395
+ const ws = await import("./wrapper-6f348d45.js");
396
+ NodeBlob = (await import("node:buffer")).Blob;
397
+ global.WebSocket = ws.WebSocket;
398
+ }
399
+ const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token);
400
+ const session_hash = Math.random().toString(36).substring(2);
401
+ const last_status = {};
402
+ let stream_open = false;
403
+ let pending_stream_messages = {};
404
+ let event_stream = null;
405
+ const event_callbacks = {};
406
+ const unclosed_events = /* @__PURE__ */ new Set();
407
+ let config;
408
+ let api_map = {};
409
+ let jwt = false;
410
+ if (hf_token && space_id) {
411
+ jwt = await get_jwt(space_id, hf_token);
412
+ }
413
+ async function config_success(_config) {
414
+ config = _config;
415
+ api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []);
416
+ if (config.auth_required) {
417
+ return {
418
+ config,
419
+ ...return_obj
420
+ };
421
+ }
422
+ try {
423
+ api = await view_api(config);
424
+ } catch (e) {
425
+ console.error(`Could not get api details: ${e.message}`);
426
+ }
427
+ return {
428
+ config,
429
+ ...return_obj
430
+ };
431
+ }
432
+ let api;
433
+ async function handle_space_sucess(status) {
434
+ if (status_callback)
435
+ status_callback(status);
436
+ if (status.status === "running")
437
+ try {
438
+ config = await resolve_config(
439
+ fetch_implementation,
440
+ `${http_protocol}//${host}`,
441
+ hf_token
442
+ );
443
+ const _config = await config_success(config);
444
+ res(_config);
445
+ } catch (e) {
446
+ console.error(e);
447
+ if (status_callback) {
448
+ status_callback({
449
+ status: "error",
450
+ message: "Could not load this space.",
451
+ load_status: "error",
452
+ detail: "NOT_FOUND"
453
+ });
454
+ }
455
+ }
456
+ }
457
+ try {
458
+ config = await resolve_config(
459
+ fetch_implementation,
460
+ `${http_protocol}//${host}`,
461
+ hf_token
462
+ );
463
+ const _config = await config_success(config);
464
+ res(_config);
465
+ } catch (e) {
466
+ console.error(e);
467
+ if (space_id) {
468
+ check_space_status(
469
+ space_id,
470
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
471
+ handle_space_sucess
472
+ );
473
+ } else {
474
+ if (status_callback)
475
+ status_callback({
476
+ status: "error",
477
+ message: "Could not load this space.",
478
+ load_status: "error",
479
+ detail: "NOT_FOUND"
480
+ });
481
+ }
482
+ }
483
+ function predict(endpoint, data, event_data) {
484
+ let data_returned = false;
485
+ let status_complete = false;
486
+ let dependency;
487
+ if (typeof endpoint === "number") {
488
+ dependency = config.dependencies[endpoint];
489
+ } else {
490
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
491
+ dependency = config.dependencies[api_map[trimmed_endpoint]];
492
+ }
493
+ if (dependency.types.continuous) {
494
+ throw new Error(
495
+ "Cannot call predict on this function as it may run forever. Use submit instead"
496
+ );
497
+ }
498
+ return new Promise((res2, rej) => {
499
+ const app = submit(endpoint, data, event_data);
500
+ let result;
501
+ app.on("data", (d) => {
502
+ if (status_complete) {
503
+ app.destroy();
504
+ res2(d);
505
+ }
506
+ data_returned = true;
507
+ result = d;
508
+ }).on("status", (status) => {
509
+ if (status.stage === "error")
510
+ rej(status);
511
+ if (status.stage === "complete") {
512
+ status_complete = true;
513
+ if (data_returned) {
514
+ app.destroy();
515
+ res2(result);
516
+ }
517
+ }
518
+ });
519
+ });
520
+ }
521
+ function submit(endpoint, data, event_data, trigger_id = null) {
522
+ let fn_index;
523
+ let api_info;
524
+ if (typeof endpoint === "number") {
525
+ fn_index = endpoint;
526
+ api_info = api.unnamed_endpoints[fn_index];
527
+ } else {
528
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
529
+ fn_index = api_map[trimmed_endpoint];
530
+ api_info = api.named_endpoints[endpoint.trim()];
531
+ }
532
+ if (typeof fn_index !== "number") {
533
+ throw new Error(
534
+ "There is no endpoint matching that name of fn_index matching that number."
535
+ );
536
+ }
537
+ let websocket;
538
+ let eventSource;
539
+ let protocol = config.protocol ?? "ws";
540
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
541
+ let payload;
542
+ let event_id = null;
543
+ let complete = false;
544
+ const listener_map = {};
545
+ let url_params = "";
546
+ if (typeof window !== "undefined") {
547
+ url_params = new URLSearchParams(window.location.search).toString();
548
+ }
549
+ handle_blob2(`${config.root}`, data, api_info, hf_token).then(
550
+ (_payload) => {
551
+ payload = {
552
+ data: _payload || [],
553
+ event_data,
554
+ fn_index,
555
+ trigger_id
556
+ };
557
+ if (skip_queue(fn_index, config)) {
558
+ fire_event({
559
+ type: "status",
560
+ endpoint: _endpoint,
561
+ stage: "pending",
562
+ queue: false,
563
+ fn_index,
564
+ time: /* @__PURE__ */ new Date()
565
+ });
566
+ post_data2(
567
+ `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
568
+ {
569
+ ...payload,
570
+ session_hash
571
+ },
572
+ hf_token
573
+ ).then(([output, status_code]) => {
574
+ const data2 = transform_files ? transform_output(
575
+ output.data,
576
+ api_info,
577
+ config.root,
578
+ config.root_url
579
+ ) : output.data;
580
+ if (status_code == 200) {
581
+ fire_event({
582
+ type: "data",
583
+ endpoint: _endpoint,
584
+ fn_index,
585
+ data: data2,
586
+ time: /* @__PURE__ */ new Date()
587
+ });
588
+ fire_event({
589
+ type: "status",
590
+ endpoint: _endpoint,
591
+ fn_index,
592
+ stage: "complete",
593
+ eta: output.average_duration,
594
+ queue: false,
595
+ time: /* @__PURE__ */ new Date()
596
+ });
597
+ } else {
598
+ fire_event({
599
+ type: "status",
600
+ stage: "error",
601
+ endpoint: _endpoint,
602
+ fn_index,
603
+ message: output.error,
604
+ queue: false,
605
+ time: /* @__PURE__ */ new Date()
606
+ });
607
+ }
608
+ }).catch((e) => {
609
+ fire_event({
610
+ type: "status",
611
+ stage: "error",
612
+ message: e.message,
613
+ endpoint: _endpoint,
614
+ fn_index,
615
+ queue: false,
616
+ time: /* @__PURE__ */ new Date()
617
+ });
618
+ });
619
+ } else if (protocol == "ws") {
620
+ fire_event({
621
+ type: "status",
622
+ stage: "pending",
623
+ queue: true,
624
+ endpoint: _endpoint,
625
+ fn_index,
626
+ time: /* @__PURE__ */ new Date()
627
+ });
628
+ let url = new URL(`${ws_protocol}://${resolve_root(
629
+ host,
630
+ config.path,
631
+ true
632
+ )}
633
+ /queue/join${url_params ? "?" + url_params : ""}`);
634
+ if (jwt) {
635
+ url.searchParams.set("__sign", jwt);
636
+ }
637
+ websocket = new WebSocket(url);
638
+ websocket.onclose = (evt) => {
639
+ if (!evt.wasClean) {
640
+ fire_event({
641
+ type: "status",
642
+ stage: "error",
643
+ broken: true,
644
+ message: BROKEN_CONNECTION_MSG,
645
+ queue: true,
646
+ endpoint: _endpoint,
647
+ fn_index,
648
+ time: /* @__PURE__ */ new Date()
649
+ });
650
+ }
651
+ };
652
+ websocket.onmessage = function(event) {
653
+ const _data = JSON.parse(event.data);
654
+ const { type, status, data: data2 } = handle_message(
655
+ _data,
656
+ last_status[fn_index]
657
+ );
658
+ if (type === "update" && status && !complete) {
659
+ fire_event({
660
+ type: "status",
661
+ endpoint: _endpoint,
662
+ fn_index,
663
+ time: /* @__PURE__ */ new Date(),
664
+ ...status
665
+ });
666
+ if (status.stage === "error") {
667
+ websocket.close();
668
+ }
669
+ } else if (type === "hash") {
670
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
671
+ return;
672
+ } else if (type === "data") {
673
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
674
+ } else if (type === "complete") {
675
+ complete = status;
676
+ } else if (type === "log") {
677
+ fire_event({
678
+ type: "log",
679
+ log: data2.log,
680
+ level: data2.level,
681
+ endpoint: _endpoint,
682
+ fn_index
683
+ });
684
+ } else if (type === "generating") {
685
+ fire_event({
686
+ type: "status",
687
+ time: /* @__PURE__ */ new Date(),
688
+ ...status,
689
+ stage: status == null ? void 0 : status.stage,
690
+ queue: true,
691
+ endpoint: _endpoint,
692
+ fn_index
693
+ });
694
+ }
695
+ if (data2) {
696
+ fire_event({
697
+ type: "data",
698
+ time: /* @__PURE__ */ new Date(),
699
+ data: transform_files ? transform_output(
700
+ data2.data,
701
+ api_info,
702
+ config.root,
703
+ config.root_url
704
+ ) : data2.data,
705
+ endpoint: _endpoint,
706
+ fn_index
707
+ });
708
+ if (complete) {
709
+ fire_event({
710
+ type: "status",
711
+ time: /* @__PURE__ */ new Date(),
712
+ ...complete,
713
+ stage: status == null ? void 0 : status.stage,
714
+ queue: true,
715
+ endpoint: _endpoint,
716
+ fn_index
717
+ });
718
+ websocket.close();
719
+ }
720
+ }
721
+ };
722
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
723
+ addEventListener(
724
+ "open",
725
+ () => websocket.send(JSON.stringify({ hash: session_hash }))
726
+ );
727
+ }
728
+ } else if (protocol == "sse") {
729
+ fire_event({
730
+ type: "status",
731
+ stage: "pending",
732
+ queue: true,
733
+ endpoint: _endpoint,
734
+ fn_index,
735
+ time: /* @__PURE__ */ new Date()
736
+ });
737
+ var params = new URLSearchParams({
738
+ fn_index: fn_index.toString(),
739
+ session_hash
740
+ }).toString();
741
+ let url = new URL(
742
+ `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}`
743
+ );
744
+ eventSource = EventSource_factory(url);
745
+ eventSource.onmessage = async function(event) {
746
+ const _data = JSON.parse(event.data);
747
+ const { type, status, data: data2 } = handle_message(
748
+ _data,
749
+ last_status[fn_index]
750
+ );
751
+ if (type === "update" && status && !complete) {
752
+ fire_event({
753
+ type: "status",
754
+ endpoint: _endpoint,
755
+ fn_index,
756
+ time: /* @__PURE__ */ new Date(),
757
+ ...status
758
+ });
759
+ if (status.stage === "error") {
760
+ eventSource.close();
761
+ }
762
+ } else if (type === "data") {
763
+ event_id = _data.event_id;
764
+ let [_, status2] = await post_data2(
765
+ `${config.root}/queue/data`,
766
+ {
767
+ ...payload,
768
+ session_hash,
769
+ event_id
770
+ },
771
+ hf_token
772
+ );
773
+ if (status2 !== 200) {
774
+ fire_event({
775
+ type: "status",
776
+ stage: "error",
777
+ message: BROKEN_CONNECTION_MSG,
778
+ queue: true,
779
+ endpoint: _endpoint,
780
+ fn_index,
781
+ time: /* @__PURE__ */ new Date()
782
+ });
783
+ eventSource.close();
784
+ }
785
+ } else if (type === "complete") {
786
+ complete = status;
787
+ } else if (type === "log") {
788
+ fire_event({
789
+ type: "log",
790
+ log: data2.log,
791
+ level: data2.level,
792
+ endpoint: _endpoint,
793
+ fn_index
794
+ });
795
+ } else if (type === "generating") {
796
+ fire_event({
797
+ type: "status",
798
+ time: /* @__PURE__ */ new Date(),
799
+ ...status,
800
+ stage: status == null ? void 0 : status.stage,
801
+ queue: true,
802
+ endpoint: _endpoint,
803
+ fn_index
804
+ });
805
+ }
806
+ if (data2) {
807
+ fire_event({
808
+ type: "data",
809
+ time: /* @__PURE__ */ new Date(),
810
+ data: transform_files ? transform_output(
811
+ data2.data,
812
+ api_info,
813
+ config.root,
814
+ config.root_url
815
+ ) : data2.data,
816
+ endpoint: _endpoint,
817
+ fn_index
818
+ });
819
+ if (complete) {
820
+ fire_event({
821
+ type: "status",
822
+ time: /* @__PURE__ */ new Date(),
823
+ ...complete,
824
+ stage: status == null ? void 0 : status.stage,
825
+ queue: true,
826
+ endpoint: _endpoint,
827
+ fn_index
828
+ });
829
+ eventSource.close();
830
+ }
831
+ }
832
+ };
833
+ } else if (protocol == "sse_v1") {
834
+ fire_event({
835
+ type: "status",
836
+ stage: "pending",
837
+ queue: true,
838
+ endpoint: _endpoint,
839
+ fn_index,
840
+ time: /* @__PURE__ */ new Date()
841
+ });
842
+ post_data2(
843
+ `${config.root}/queue/join?${url_params}`,
844
+ {
845
+ ...payload,
846
+ session_hash
847
+ },
848
+ hf_token
849
+ ).then(([response, status]) => {
850
+ if (status === 503) {
851
+ fire_event({
852
+ type: "status",
853
+ stage: "error",
854
+ message: QUEUE_FULL_MSG,
855
+ queue: true,
856
+ endpoint: _endpoint,
857
+ fn_index,
858
+ time: /* @__PURE__ */ new Date()
859
+ });
860
+ } else if (status !== 200) {
861
+ fire_event({
862
+ type: "status",
863
+ stage: "error",
864
+ message: BROKEN_CONNECTION_MSG,
865
+ queue: true,
866
+ endpoint: _endpoint,
867
+ fn_index,
868
+ time: /* @__PURE__ */ new Date()
869
+ });
870
+ } else {
871
+ event_id = response.event_id;
872
+ let callback = async function(_data) {
873
+ try {
874
+ const { type, status: status2, data: data2 } = handle_message(
875
+ _data,
876
+ last_status[fn_index]
877
+ );
878
+ if (type == "heartbeat") {
879
+ return;
880
+ }
881
+ if (type === "update" && status2 && !complete) {
882
+ fire_event({
883
+ type: "status",
884
+ endpoint: _endpoint,
885
+ fn_index,
886
+ time: /* @__PURE__ */ new Date(),
887
+ ...status2
888
+ });
889
+ } else if (type === "complete") {
890
+ complete = status2;
891
+ } else if (type == "unexpected_error") {
892
+ console.error("Unexpected error", status2 == null ? void 0 : status2.message);
893
+ fire_event({
894
+ type: "status",
895
+ stage: "error",
896
+ message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!",
897
+ queue: true,
898
+ endpoint: _endpoint,
899
+ fn_index,
900
+ time: /* @__PURE__ */ new Date()
901
+ });
902
+ } else if (type === "log") {
903
+ fire_event({
904
+ type: "log",
905
+ log: data2.log,
906
+ level: data2.level,
907
+ endpoint: _endpoint,
908
+ fn_index
909
+ });
910
+ return;
911
+ } else if (type === "generating") {
912
+ fire_event({
913
+ type: "status",
914
+ time: /* @__PURE__ */ new Date(),
915
+ ...status2,
916
+ stage: status2 == null ? void 0 : status2.stage,
917
+ queue: true,
918
+ endpoint: _endpoint,
919
+ fn_index
920
+ });
921
+ }
922
+ if (data2) {
923
+ fire_event({
924
+ type: "data",
925
+ time: /* @__PURE__ */ new Date(),
926
+ data: transform_files ? transform_output(
927
+ data2.data,
928
+ api_info,
929
+ config.root,
930
+ config.root_url
931
+ ) : data2.data,
932
+ endpoint: _endpoint,
933
+ fn_index
934
+ });
935
+ if (complete) {
936
+ fire_event({
937
+ type: "status",
938
+ time: /* @__PURE__ */ new Date(),
939
+ ...complete,
940
+ stage: status2 == null ? void 0 : status2.stage,
941
+ queue: true,
942
+ endpoint: _endpoint,
943
+ fn_index
944
+ });
945
+ }
946
+ }
947
+ if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") {
948
+ if (event_callbacks[event_id]) {
949
+ delete event_callbacks[event_id];
950
+ }
951
+ }
952
+ } catch (e) {
953
+ console.error("Unexpected client exception", e);
954
+ fire_event({
955
+ type: "status",
956
+ stage: "error",
957
+ message: "An Unexpected Error Occurred!",
958
+ queue: true,
959
+ endpoint: _endpoint,
960
+ fn_index,
961
+ time: /* @__PURE__ */ new Date()
962
+ });
963
+ close_stream();
964
+ }
965
+ };
966
+ if (event_id in pending_stream_messages) {
967
+ pending_stream_messages[event_id].forEach(
968
+ (msg) => callback(msg)
969
+ );
970
+ delete pending_stream_messages[event_id];
971
+ }
972
+ event_callbacks[event_id] = callback;
973
+ unclosed_events.add(event_id);
974
+ if (!stream_open) {
975
+ open_stream();
976
+ }
977
+ }
978
+ });
979
+ }
980
+ }
981
+ );
982
+ function fire_event(event) {
983
+ const narrowed_listener_map = listener_map;
984
+ const listeners = narrowed_listener_map[event.type] || [];
985
+ listeners == null ? void 0 : listeners.forEach((l) => l(event));
986
+ }
987
+ function on(eventType, listener) {
988
+ const narrowed_listener_map = listener_map;
989
+ const listeners = narrowed_listener_map[eventType] || [];
990
+ narrowed_listener_map[eventType] = listeners;
991
+ listeners == null ? void 0 : listeners.push(listener);
992
+ return { on, off, cancel, destroy };
993
+ }
994
+ function off(eventType, listener) {
995
+ const narrowed_listener_map = listener_map;
996
+ let listeners = narrowed_listener_map[eventType] || [];
997
+ listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
998
+ narrowed_listener_map[eventType] = listeners;
999
+ return { on, off, cancel, destroy };
1000
+ }
1001
+ async function cancel() {
1002
+ const _status = {
1003
+ stage: "complete",
1004
+ queue: false,
1005
+ time: /* @__PURE__ */ new Date()
1006
+ };
1007
+ complete = _status;
1008
+ fire_event({
1009
+ ..._status,
1010
+ type: "status",
1011
+ endpoint: _endpoint,
1012
+ fn_index
1013
+ });
1014
+ let cancel_request = {};
1015
+ if (protocol === "ws") {
1016
+ if (websocket && websocket.readyState === 0) {
1017
+ websocket.addEventListener("open", () => {
1018
+ websocket.close();
1019
+ });
1020
+ } else {
1021
+ websocket.close();
1022
+ }
1023
+ cancel_request = { fn_index, session_hash };
1024
+ } else {
1025
+ eventSource.close();
1026
+ cancel_request = { event_id };
1027
+ }
1028
+ try {
1029
+ await fetch_implementation(`${config.root}/reset`, {
1030
+ headers: { "Content-Type": "application/json" },
1031
+ method: "POST",
1032
+ body: JSON.stringify(cancel_request)
1033
+ });
1034
+ } catch (e) {
1035
+ console.warn(
1036
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1037
+ );
1038
+ }
1039
+ }
1040
+ function destroy() {
1041
+ for (const event_type in listener_map) {
1042
+ listener_map[event_type].forEach((fn2) => {
1043
+ off(event_type, fn2);
1044
+ });
1045
+ }
1046
+ }
1047
+ return {
1048
+ on,
1049
+ off,
1050
+ cancel,
1051
+ destroy
1052
+ };
1053
+ }
1054
+ function open_stream() {
1055
+ stream_open = true;
1056
+ let params = new URLSearchParams({
1057
+ session_hash
1058
+ }).toString();
1059
+ let url = new URL(`${config.root}/queue/data?${params}`);
1060
+ event_stream = EventSource_factory(url);
1061
+ event_stream.onmessage = async function(event) {
1062
+ let _data = JSON.parse(event.data);
1063
+ const event_id = _data.event_id;
1064
+ if (!event_id) {
1065
+ await Promise.all(
1066
+ Object.keys(event_callbacks).map(
1067
+ (event_id2) => event_callbacks[event_id2](_data)
1068
+ )
1069
+ );
1070
+ } else if (event_callbacks[event_id]) {
1071
+ if (_data.msg === "process_completed") {
1072
+ unclosed_events.delete(event_id);
1073
+ if (unclosed_events.size === 0) {
1074
+ close_stream();
1075
+ }
1076
+ }
1077
+ let fn2 = event_callbacks[event_id];
1078
+ window.setTimeout(fn2, 0, _data);
1079
+ } else {
1080
+ if (!pending_stream_messages[event_id]) {
1081
+ pending_stream_messages[event_id] = [];
1082
+ }
1083
+ pending_stream_messages[event_id].push(_data);
1084
+ }
1085
+ };
1086
+ event_stream.onerror = async function(event) {
1087
+ await Promise.all(
1088
+ Object.keys(event_callbacks).map(
1089
+ (event_id) => event_callbacks[event_id]({
1090
+ msg: "unexpected_error",
1091
+ message: BROKEN_CONNECTION_MSG
1092
+ })
1093
+ )
1094
+ );
1095
+ close_stream();
1096
+ };
1097
+ }
1098
+ function close_stream() {
1099
+ stream_open = false;
1100
+ event_stream == null ? void 0 : event_stream.close();
1101
+ }
1102
+ async function component_server(component_id, fn_name, data) {
1103
+ var _a;
1104
+ const headers = { "Content-Type": "application/json" };
1105
+ if (hf_token) {
1106
+ headers.Authorization = `Bearer ${hf_token}`;
1107
+ }
1108
+ let root_url;
1109
+ let component = config.components.find(
1110
+ (comp) => comp.id === component_id
1111
+ );
1112
+ if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
1113
+ root_url = component.props.root_url;
1114
+ } else {
1115
+ root_url = config.root;
1116
+ }
1117
+ const response = await fetch_implementation(
1118
+ `${root_url}/component_server/`,
1119
+ {
1120
+ method: "POST",
1121
+ body: JSON.stringify({
1122
+ data,
1123
+ component_id,
1124
+ fn_name,
1125
+ session_hash
1126
+ }),
1127
+ headers
1128
+ }
1129
+ );
1130
+ if (!response.ok) {
1131
+ throw new Error(
1132
+ "Could not connect to component server: " + response.statusText
1133
+ );
1134
+ }
1135
+ const output = await response.json();
1136
+ return output;
1137
+ }
1138
+ async function view_api(config2) {
1139
+ if (api)
1140
+ return api;
1141
+ const headers = { "Content-Type": "application/json" };
1142
+ if (hf_token) {
1143
+ headers.Authorization = `Bearer ${hf_token}`;
1144
+ }
1145
+ let response;
1146
+ if (semiver(config2.version || "2.0.0", "3.30") < 0) {
1147
+ response = await fetch_implementation(
1148
+ "https://gradio-space-api-fetcher-v2.hf.space/api",
1149
+ {
1150
+ method: "POST",
1151
+ body: JSON.stringify({
1152
+ serialize: false,
1153
+ config: JSON.stringify(config2)
1154
+ }),
1155
+ headers
1156
+ }
1157
+ );
1158
+ } else {
1159
+ response = await fetch_implementation(`${config2.root}/info`, {
1160
+ headers
1161
+ });
1162
+ }
1163
+ if (!response.ok) {
1164
+ throw new Error(BROKEN_CONNECTION_MSG);
1165
+ }
1166
+ let api_info = await response.json();
1167
+ if ("api" in api_info) {
1168
+ api_info = api_info.api;
1169
+ }
1170
+ if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
1171
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
1172
+ }
1173
+ const x = transform_api_info(api_info, config2, api_map);
1174
+ return x;
1175
+ }
1176
+ });
1177
+ }
1178
+ async function handle_blob2(endpoint, data, api_info, token) {
1179
+ const blob_refs = await walk_and_store_blobs(
1180
+ data,
1181
+ void 0,
1182
+ [],
1183
+ true,
1184
+ api_info
1185
+ );
1186
+ return Promise.all(
1187
+ blob_refs.map(async ({ path, blob, type }) => {
1188
+ if (blob) {
1189
+ const file_url = (await upload_files2(endpoint, [blob], token)).files[0];
1190
+ return { path, file_url, type, name: blob == null ? void 0 : blob.name };
1191
+ }
1192
+ return { path, type };
1193
+ })
1194
+ ).then((r) => {
1195
+ r.forEach(({ path, file_url, type, name }) => {
1196
+ if (type === "Gallery") {
1197
+ update_object(data, file_url, path);
1198
+ } else if (file_url) {
1199
+ const file = new FileData({ path: file_url, orig_name: name });
1200
+ update_object(data, file, path);
1201
+ }
1202
+ });
1203
+ return data;
1204
+ });
1205
+ }
1206
+ }
1207
+ const { post_data, upload_files, client, handle_blob } = api_factory(
1208
+ fetch,
1209
+ (...args) => new EventSource(...args)
1210
+ );
1211
+ function transform_output(data, api_info, root_url, remote_url) {
1212
+ return data.map((d, i) => {
1213
+ var _a, _b, _c, _d;
1214
+ if (((_b = (_a = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _a[i]) == null ? void 0 : _b.component) === "File") {
1215
+ return normalise_file(d, root_url, remote_url);
1216
+ } else if (((_d = (_c = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _c[i]) == null ? void 0 : _d.component) === "Gallery") {
1217
+ return d.map((img) => {
1218
+ return Array.isArray(img) ? [normalise_file(img[0], root_url, remote_url), img[1]] : [normalise_file(img, root_url, remote_url), null];
1219
+ });
1220
+ } else if (typeof d === "object" && d.path) {
1221
+ return normalise_file(d, root_url, remote_url);
1222
+ }
1223
+ return d;
1224
+ });
1225
+ }
1226
+ function get_type(type, component, serializer, signature_type) {
1227
+ switch (type.type) {
1228
+ case "string":
1229
+ return "string";
1230
+ case "boolean":
1231
+ return "boolean";
1232
+ case "number":
1233
+ return "number";
1234
+ }
1235
+ if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
1236
+ return "any";
1237
+ } else if (serializer === "ListStringSerializable") {
1238
+ return "string[]";
1239
+ } else if (component === "Image") {
1240
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
1241
+ } else if (serializer === "FileSerializable") {
1242
+ if ((type == null ? void 0 : type.type) === "array") {
1243
+ return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
1244
+ }
1245
+ return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
1246
+ } else if (serializer === "GallerySerializable") {
1247
+ return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
1248
+ }
1249
+ }
1250
+ function get_description(type, serializer) {
1251
+ if (serializer === "GallerySerializable") {
1252
+ return "array of [file, label] tuples";
1253
+ } else if (serializer === "ListStringSerializable") {
1254
+ return "array of strings";
1255
+ } else if (serializer === "FileSerializable") {
1256
+ return "array of files or single file";
1257
+ }
1258
+ return type.description;
1259
+ }
1260
+ function transform_api_info(api_info, config, api_map) {
1261
+ const new_data = {
1262
+ named_endpoints: {},
1263
+ unnamed_endpoints: {}
1264
+ };
1265
+ for (const key in api_info) {
1266
+ const cat = api_info[key];
1267
+ for (const endpoint in cat) {
1268
+ const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")];
1269
+ const info = cat[endpoint];
1270
+ new_data[key][endpoint] = {};
1271
+ new_data[key][endpoint].parameters = {};
1272
+ new_data[key][endpoint].returns = {};
1273
+ new_data[key][endpoint].type = config.dependencies[dep_index].types;
1274
+ new_data[key][endpoint].parameters = info.parameters.map(
1275
+ ({ label, component, type, serializer }) => ({
1276
+ label,
1277
+ component,
1278
+ type: get_type(type, component, serializer, "parameter"),
1279
+ description: get_description(type, serializer)
1280
+ })
1281
+ );
1282
+ new_data[key][endpoint].returns = info.returns.map(
1283
+ ({ label, component, type, serializer }) => ({
1284
+ label,
1285
+ component,
1286
+ type: get_type(type, component, serializer, "return"),
1287
+ description: get_description(type, serializer)
1288
+ })
1289
+ );
1290
+ }
1291
+ }
1292
+ return new_data;
1293
+ }
1294
+ async function get_jwt(space, token) {
1295
+ try {
1296
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
1297
+ headers: {
1298
+ Authorization: `Bearer ${token}`
1299
+ }
1300
+ });
1301
+ const jwt = (await r.json()).token;
1302
+ return jwt || false;
1303
+ } catch (e) {
1304
+ console.error(e);
1305
+ return false;
1306
+ }
1307
+ }
1308
+ function update_object(object, newValue, stack) {
1309
+ while (stack.length > 1) {
1310
+ object = object[stack.shift()];
1311
+ }
1312
+ object[stack.shift()] = newValue;
1313
+ }
1314
+ async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) {
1315
+ if (Array.isArray(param)) {
1316
+ let blob_refs = [];
1317
+ await Promise.all(
1318
+ param.map(async (v, i) => {
1319
+ var _a;
1320
+ let new_path = path.slice();
1321
+ new_path.push(i);
1322
+ const array_refs = await walk_and_store_blobs(
1323
+ param[i],
1324
+ root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type,
1325
+ new_path,
1326
+ false,
1327
+ api_info
1328
+ );
1329
+ blob_refs = blob_refs.concat(array_refs);
1330
+ })
1331
+ );
1332
+ return blob_refs;
1333
+ } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
1334
+ const is_image = type === "Image";
1335
+ return [
1336
+ {
1337
+ path,
1338
+ blob: is_image ? false : new NodeBlob([param]),
1339
+ type
1340
+ }
1341
+ ];
1342
+ } else if (typeof param === "object") {
1343
+ let blob_refs = [];
1344
+ for (let key in param) {
1345
+ if (param.hasOwnProperty(key)) {
1346
+ let new_path = path.slice();
1347
+ new_path.push(key);
1348
+ blob_refs = blob_refs.concat(
1349
+ await walk_and_store_blobs(
1350
+ param[key],
1351
+ void 0,
1352
+ new_path,
1353
+ false,
1354
+ api_info
1355
+ )
1356
+ );
1357
+ }
1358
+ }
1359
+ return blob_refs;
1360
+ }
1361
+ return [];
1362
+ }
1363
+ function skip_queue(id, config) {
1364
+ var _a, _b, _c, _d;
1365
+ 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;
1366
+ }
1367
+ async function resolve_config(fetch_implementation, endpoint, token) {
1368
+ const headers = {};
1369
+ if (token) {
1370
+ headers.Authorization = `Bearer ${token}`;
1371
+ }
1372
+ if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
1373
+ const path = window.gradio_config.root;
1374
+ const config = window.gradio_config;
1375
+ config.root = resolve_root(endpoint, config.root, false);
1376
+ return { ...config, path };
1377
+ } else if (endpoint) {
1378
+ let response = await fetch_implementation(`${endpoint}/config`, {
1379
+ headers
1380
+ });
1381
+ if (response.status === 200) {
1382
+ const config = await response.json();
1383
+ config.path = config.path ?? "";
1384
+ config.root = endpoint;
1385
+ return config;
1386
+ }
1387
+ throw new Error("Could not get config.");
1388
+ }
1389
+ throw new Error("No config or app endpoint found");
1390
+ }
1391
+ async function check_space_status(id, type, status_callback) {
1392
+ let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
1393
+ let response;
1394
+ let _status;
1395
+ try {
1396
+ response = await fetch(endpoint);
1397
+ _status = response.status;
1398
+ if (_status !== 200) {
1399
+ throw new Error();
1400
+ }
1401
+ response = await response.json();
1402
+ } catch (e) {
1403
+ status_callback({
1404
+ status: "error",
1405
+ load_status: "error",
1406
+ message: "Could not get space status",
1407
+ detail: "NOT_FOUND"
1408
+ });
1409
+ return;
1410
+ }
1411
+ if (!response || _status !== 200)
1412
+ return;
1413
+ const {
1414
+ runtime: { stage },
1415
+ id: space_name
1416
+ } = response;
1417
+ switch (stage) {
1418
+ case "STOPPED":
1419
+ case "SLEEPING":
1420
+ status_callback({
1421
+ status: "sleeping",
1422
+ load_status: "pending",
1423
+ message: "Space is asleep. Waking it up...",
1424
+ detail: stage
1425
+ });
1426
+ setTimeout(() => {
1427
+ check_space_status(id, type, status_callback);
1428
+ }, 1e3);
1429
+ break;
1430
+ case "PAUSED":
1431
+ status_callback({
1432
+ status: "paused",
1433
+ load_status: "error",
1434
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
1435
+ detail: stage,
1436
+ discussions_enabled: await discussions_enabled(space_name)
1437
+ });
1438
+ break;
1439
+ case "RUNNING":
1440
+ case "RUNNING_BUILDING":
1441
+ status_callback({
1442
+ status: "running",
1443
+ load_status: "complete",
1444
+ message: "",
1445
+ detail: stage
1446
+ });
1447
+ break;
1448
+ case "BUILDING":
1449
+ status_callback({
1450
+ status: "building",
1451
+ load_status: "pending",
1452
+ message: "Space is building...",
1453
+ detail: stage
1454
+ });
1455
+ setTimeout(() => {
1456
+ check_space_status(id, type, status_callback);
1457
+ }, 1e3);
1458
+ break;
1459
+ default:
1460
+ status_callback({
1461
+ status: "space_error",
1462
+ load_status: "error",
1463
+ message: "This space is experiencing an issue.",
1464
+ detail: stage,
1465
+ discussions_enabled: await discussions_enabled(space_name)
1466
+ });
1467
+ break;
1468
+ }
1469
+ }
1470
+ function handle_message(data, last_status) {
1471
+ const queue = true;
1472
+ switch (data.msg) {
1473
+ case "send_data":
1474
+ return { type: "data" };
1475
+ case "send_hash":
1476
+ return { type: "hash" };
1477
+ case "queue_full":
1478
+ return {
1479
+ type: "update",
1480
+ status: {
1481
+ queue,
1482
+ message: QUEUE_FULL_MSG,
1483
+ stage: "error",
1484
+ code: data.code,
1485
+ success: data.success
1486
+ }
1487
+ };
1488
+ case "heartbeat":
1489
+ return {
1490
+ type: "heartbeat"
1491
+ };
1492
+ case "unexpected_error":
1493
+ return {
1494
+ type: "unexpected_error",
1495
+ status: {
1496
+ queue,
1497
+ message: data.message,
1498
+ stage: "error",
1499
+ success: false
1500
+ }
1501
+ };
1502
+ case "estimation":
1503
+ return {
1504
+ type: "update",
1505
+ status: {
1506
+ queue,
1507
+ stage: last_status || "pending",
1508
+ code: data.code,
1509
+ size: data.queue_size,
1510
+ position: data.rank,
1511
+ eta: data.rank_eta,
1512
+ success: data.success
1513
+ }
1514
+ };
1515
+ case "progress":
1516
+ return {
1517
+ type: "update",
1518
+ status: {
1519
+ queue,
1520
+ stage: "pending",
1521
+ code: data.code,
1522
+ progress_data: data.progress_data,
1523
+ success: data.success
1524
+ }
1525
+ };
1526
+ case "log":
1527
+ return { type: "log", data };
1528
+ case "process_generating":
1529
+ return {
1530
+ type: "generating",
1531
+ status: {
1532
+ queue,
1533
+ message: !data.success ? data.output.error : null,
1534
+ stage: data.success ? "generating" : "error",
1535
+ code: data.code,
1536
+ progress_data: data.progress_data,
1537
+ eta: data.average_duration
1538
+ },
1539
+ data: data.success ? data.output : null
1540
+ };
1541
+ case "process_completed":
1542
+ if ("error" in data.output) {
1543
+ return {
1544
+ type: "update",
1545
+ status: {
1546
+ queue,
1547
+ message: data.output.error,
1548
+ stage: "error",
1549
+ code: data.code,
1550
+ success: data.success
1551
+ }
1552
+ };
1553
+ }
1554
+ return {
1555
+ type: "complete",
1556
+ status: {
1557
+ queue,
1558
+ message: !data.success ? data.output.error : void 0,
1559
+ stage: data.success ? "complete" : "error",
1560
+ code: data.code,
1561
+ progress_data: data.progress_data
1562
+ },
1563
+ data: data.success ? data.output : null
1564
+ };
1565
+ case "process_starts":
1566
+ return {
1567
+ type: "update",
1568
+ status: {
1569
+ queue,
1570
+ stage: "pending",
1571
+ code: data.code,
1572
+ size: data.rank,
1573
+ position: 0,
1574
+ success: data.success,
1575
+ eta: data.eta
1576
+ }
1577
+ };
1578
+ }
1579
+ return { type: "none", status: { stage: "error", queue } };
1580
+ }
1581
+ export {
1582
+ FileData,
1583
+ api_factory,
1584
+ client,
1585
+ duplicate,
1586
+ get_fetchable_url_or_file,
1587
+ normalise_file,
1588
+ post_data,
1589
+ prepare_files,
1590
+ upload,
1591
+ upload_files
1592
+ };
node_modules/@gradio/client/dist/types.d.ts ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface Config {
2
+ auth_required: boolean | undefined;
3
+ auth_message: string;
4
+ components: any[];
5
+ css: string | null;
6
+ js: string | null;
7
+ head: string | null;
8
+ dependencies: any[];
9
+ dev_mode: boolean;
10
+ enable_queue: boolean;
11
+ layout: any;
12
+ mode: "blocks" | "interface";
13
+ root: string;
14
+ root_url?: string;
15
+ theme: string;
16
+ title: string;
17
+ version: string;
18
+ space_id: string | null;
19
+ is_colab: boolean;
20
+ show_api: boolean;
21
+ stylesheets: string[];
22
+ path: string;
23
+ protocol?: "sse_v1" | "sse" | "ws";
24
+ }
25
+ export interface Payload {
26
+ data: unknown[];
27
+ fn_index?: number;
28
+ event_data?: unknown;
29
+ time?: Date;
30
+ }
31
+ export interface PostResponse {
32
+ error?: string;
33
+ [x: string]: any;
34
+ }
35
+ export interface UploadResponse {
36
+ error?: string;
37
+ files?: string[];
38
+ }
39
+ export interface Status {
40
+ queue: boolean;
41
+ code?: string;
42
+ success?: boolean;
43
+ stage: "pending" | "error" | "complete" | "generating";
44
+ broken?: boolean;
45
+ size?: number;
46
+ position?: number;
47
+ eta?: number;
48
+ message?: string;
49
+ progress_data?: {
50
+ progress: number | null;
51
+ index: number | null;
52
+ length: number | null;
53
+ unit: string | null;
54
+ desc: string | null;
55
+ }[];
56
+ time?: Date;
57
+ }
58
+ export interface LogMessage {
59
+ log: string;
60
+ level: "warning" | "info";
61
+ }
62
+ export interface SpaceStatusNormal {
63
+ status: "sleeping" | "running" | "building" | "error" | "stopped";
64
+ detail: "SLEEPING" | "RUNNING" | "RUNNING_BUILDING" | "BUILDING" | "NOT_FOUND";
65
+ load_status: "pending" | "error" | "complete" | "generating";
66
+ message: string;
67
+ }
68
+ export interface SpaceStatusError {
69
+ status: "space_error" | "paused";
70
+ detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR" | "PAUSED";
71
+ load_status: "error";
72
+ message: string;
73
+ discussions_enabled: boolean;
74
+ }
75
+ export type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
76
+ export type status_callback_function = (a: Status) => void;
77
+ export type SpaceStatusCallback = (a: SpaceStatus) => void;
78
+ export type EventType = "data" | "status" | "log";
79
+ export interface EventMap {
80
+ data: Payload;
81
+ status: Status;
82
+ log: LogMessage;
83
+ }
84
+ export type Event<K extends EventType> = {
85
+ [P in K]: EventMap[P] & {
86
+ type: P;
87
+ endpoint: string;
88
+ fn_index: number;
89
+ };
90
+ }[K];
91
+ export type EventListener<K extends EventType> = (event: Event<K>) => void;
92
+ export type ListenerMap<K extends EventType> = {
93
+ [P in K]?: EventListener<K>[];
94
+ };
95
+ export interface FileData {
96
+ name: string;
97
+ orig_name?: string;
98
+ size?: number;
99
+ data: string;
100
+ blob?: File;
101
+ is_file?: boolean;
102
+ mime_type?: string;
103
+ alt_text?: string;
104
+ }
105
+ //# sourceMappingURL=types.d.ts.map
node_modules/@gradio/client/dist/types.d.ts.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACtB,aAAa,EAAE,OAAO,GAAG,SAAS,CAAC;IACnC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,GAAG,EAAE,CAAC;IAClB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,YAAY,EAAE,GAAG,EAAE,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC;IACZ,IAAI,EAAE,QAAQ,GAAG,WAAW,CAAC;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,QAAQ,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;IAClB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,OAAO;IACvB,IAAI,EAAE,OAAO,EA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AAC,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE;CAC7B,CAAC;AACF,MAAM,WAAW,QAAQ;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB"}
node_modules/@gradio/client/dist/upload.d.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { upload_files } from "./client";
2
+ export declare function normalise_file(file: FileData | null, server_url: string, proxy_url: string | null): FileData | null;
3
+ export declare function normalise_file(file: FileData[] | null, server_url: string, proxy_url: string | null): FileData[] | null;
4
+ export declare function normalise_file(file: FileData[] | FileData | null, server_url: string, // root: string,
5
+ proxy_url: string | null): FileData[] | FileData | null;
6
+ export declare function get_fetchable_url_or_file(path: string | null, server_url: string, proxy_url: string | null): string;
7
+ export declare function upload(file_data: FileData[], root: string, upload_id?: string, upload_fn?: typeof upload_files): Promise<(FileData | null)[] | null>;
8
+ export declare function prepare_files(files: File[], is_stream?: boolean): Promise<FileData[]>;
9
+ export declare class FileData {
10
+ path: string;
11
+ url?: string;
12
+ orig_name?: string;
13
+ size?: number;
14
+ blob?: File;
15
+ is_stream?: boolean;
16
+ mime_type?: string;
17
+ alt_text?: string;
18
+ constructor({ path, url, orig_name, size, blob, is_stream, mime_type, alt_text }: {
19
+ path: string;
20
+ url?: string;
21
+ orig_name?: string;
22
+ size?: number;
23
+ blob?: File;
24
+ is_stream?: boolean;
25
+ mime_type?: string;
26
+ alt_text?: string;
27
+ });
28
+ }
29
+ //# sourceMappingURL=upload.d.ts.map
node_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AC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;gBAEN,EACX,IAAI,EACJ,GAAG,EACH,SAAS,EACT,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,QAAQ,EACR,EAAE;QACF,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,IAAI,CAAC;QACZ,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;KAClB;CAUD"}
node_modules/@gradio/client/dist/utils.d.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Config } from "./types.js";
2
+ /**
3
+ * This function is used to resolve the URL for making requests when the app has a root path.
4
+ * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or
5
+ * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting
6
+ * Gradio apps on Hugging Face Spaces.
7
+ * @param {string} base_url The base URL at which the Gradio server is hosted
8
+ * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces)
9
+ * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized.
10
+ * @returns {string} the resolved URL
11
+ */
12
+ export declare function resolve_root(base_url: string, root_path: string, prioritize_base: boolean): string;
13
+ export declare function determine_protocol(endpoint: string): {
14
+ ws_protocol: "ws" | "wss";
15
+ http_protocol: "http:" | "https:";
16
+ host: string;
17
+ };
18
+ export declare const RE_SPACE_NAME: RegExp;
19
+ export declare const RE_SPACE_DOMAIN: RegExp;
20
+ export declare function process_endpoint(app_reference: string, token?: `hf_${string}`): Promise<{
21
+ space_id: string | false;
22
+ host: string;
23
+ ws_protocol: "ws" | "wss";
24
+ http_protocol: "http:" | "https:";
25
+ }>;
26
+ export declare function map_names_to_ids(fns: Config["dependencies"]): Record<string, number>;
27
+ export declare function discussions_enabled(space_id: string): Promise<boolean>;
28
+ export declare function get_space_hardware(space_id: string, token: `hf_${string}`): Promise<(typeof hardware_types)[number]>;
29
+ export declare function set_space_hardware(space_id: string, new_hardware: (typeof hardware_types)[number], token: `hf_${string}`): Promise<(typeof hardware_types)[number]>;
30
+ export declare function set_space_timeout(space_id: string, timeout: number, token: `hf_${string}`): Promise<number>;
31
+ export declare const hardware_types: readonly ["cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large"];
32
+ //# sourceMappingURL=utils.d.ts.map
node_modules/@gradio/client/dist/utils.d.ts.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACtB,MAAM,CAKR;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACrD,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;CACb,CAgCA;AAED,eAAO,MAAM,aAAa,QAAqB,CAAC;AAChD,eAAO,MAAM,eAAe,QAAwB,CAAC;AACrD,wBAAsB,gBAAgB,CACrC,aAAa,EAAE,MAAM,EACrB,KAAK,CAAC,EAAE,MAAM,MAAM,EAAE,GACpB,OAAO,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;CAClC,CAAC,CA4CD;AAED,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,MAAM,CAAC,cAAc,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB;AAID,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAe5E;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAqB1C;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,EAC7C,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAuB1C;AAED,wBAAsB,iBAAiB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,MAAM,CAAC,CAuBjB;AAED,eAAO,MAAM,cAAc,0GAQjB,CAAC"}
node_modules/@gradio/client/dist/wrapper-6f348d45.js ADDED
The diff for this file is too large to render. See raw diff
 
node_modules/@gradio/client/package.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/client",
3
+ "version": "0.10.1",
4
+ "description": "Gradio API client",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "author": "",
8
+ "license": "ISC",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "dependencies": {
16
+ "bufferutil": "^4.0.7",
17
+ "semiver": "^1.1.0",
18
+ "ws": "^8.13.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/ws": "^8.5.4",
22
+ "esbuild": "^0.19.0"
23
+ },
24
+ "engines": {
25
+ "node": ">=18.0.0"
26
+ },
27
+ "main_changeset": true,
28
+ "scripts": {
29
+ "bundle": "vite build --ssr",
30
+ "generate_types": "tsc",
31
+ "build": "pnpm bundle && pnpm generate_types"
32
+ }
33
+ }
node_modules/@gradio/client/src/client.node-test.ts ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, describe, assert } from "vitest";
2
+ import { readFileSync } from "fs";
3
+ import { join, dirname } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { Blob } from "node:buffer";
6
+
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ const image_path = join(
9
+ __dirname,
10
+ "..",
11
+ "..",
12
+ "..",
13
+ "demo",
14
+ "kitchen_sink",
15
+ "files",
16
+ "lion.jpg"
17
+ );
18
+
19
+ import { walk_and_store_blobs, client, handle_blob } from "./client";
20
+
21
+ describe.skip("extract blob parts", () => {
22
+ test("convert Buffer to Blob", async () => {
23
+ const image = readFileSync(image_path);
24
+ await client("gradio/hello_world_main");
25
+ const parts = walk_and_store_blobs({
26
+ data: {
27
+ image
28
+ }
29
+ });
30
+
31
+ assert.isTrue(parts[0].blob instanceof Blob);
32
+ });
33
+
34
+ test("leave node Blob as Blob", async () => {
35
+ const image = new Blob([readFileSync(image_path)]);
36
+
37
+ await client("gradio/hello_world_main");
38
+ const parts = walk_and_store_blobs({
39
+ data: {
40
+ image
41
+ }
42
+ });
43
+
44
+ assert.isTrue(parts[0].blob instanceof Blob);
45
+ });
46
+
47
+ test("handle deep structures", async () => {
48
+ const image = new Blob([readFileSync(image_path)]);
49
+
50
+ await client("gradio/hello_world_main");
51
+ const parts = walk_and_store_blobs({
52
+ a: {
53
+ b: {
54
+ data: {
55
+ image
56
+ }
57
+ }
58
+ }
59
+ });
60
+
61
+ assert.isTrue(parts[0].blob instanceof Blob);
62
+ });
63
+
64
+ test("handle deep structures with arrays", async () => {
65
+ const image = new Blob([readFileSync(image_path)]);
66
+
67
+ await client("gradio/hello_world_main");
68
+ const parts = walk_and_store_blobs({
69
+ a: [
70
+ {
71
+ b: [
72
+ {
73
+ data: [
74
+ {
75
+ image
76
+ }
77
+ ]
78
+ }
79
+ ]
80
+ }
81
+ ]
82
+ });
83
+
84
+ assert.isTrue(parts[0].blob instanceof Blob);
85
+ });
86
+
87
+ test("handle deep structures with arrays 2", async () => {
88
+ const image = new Blob([readFileSync(image_path)]);
89
+
90
+ await client("gradio/hello_world_main");
91
+ const obj = {
92
+ a: [
93
+ {
94
+ b: [
95
+ {
96
+ data: [[image], image, [image, [image]]]
97
+ }
98
+ ]
99
+ }
100
+ ]
101
+ };
102
+ const parts = walk_and_store_blobs(obj);
103
+
104
+ function map_path(
105
+ obj: Record<string, any>,
106
+ parts: { path: string[]; blob: any }[]
107
+ ) {
108
+ const { path, blob } = parts[parts.length - 1];
109
+ let ref = obj;
110
+ path.forEach((p) => (ref = ref[p]));
111
+
112
+ return ref === blob;
113
+ }
114
+
115
+ assert.isTrue(parts[0].blob instanceof Blob);
116
+ // assert.isTrue(map_path(obj, parts));
117
+ });
118
+ });
119
+
120
+ describe("handle_blob", () => {
121
+ test("handle blobs", async () => {
122
+ const image = new Blob([readFileSync(image_path)]);
123
+
124
+ const app = await client("gradio/hello_world_main");
125
+ const obj = [
126
+ {
127
+ a: [
128
+ {
129
+ b: [
130
+ {
131
+ data: [[image], image, [image, [image]]]
132
+ }
133
+ ]
134
+ }
135
+ ]
136
+ }
137
+ ];
138
+
139
+ const parts = await handle_blob(app.config.root, obj, undefined);
140
+ //@ts-ignore
141
+ // assert.isString(parts.data[0].a[0].b[0].data[0][0]);
142
+ });
143
+ });
144
+
145
+ describe.skip("private space", () => {
146
+ test("can access a private space", async () => {
147
+ const image = new Blob([readFileSync(image_path)]);
148
+
149
+ const app = await client("pngwn/hello_world", {
150
+ hf_token: "hf_"
151
+ });
152
+
153
+ console.log(app);
154
+ const obj = [
155
+ {
156
+ a: [
157
+ {
158
+ b: [
159
+ {
160
+ data: [[image], image, [image, [image]]]
161
+ }
162
+ ]
163
+ }
164
+ ]
165
+ }
166
+ ];
167
+
168
+ const parts = await handle_blob(app.config.root, obj, "hf_");
169
+ //@ts-ignore
170
+ assert.isString(parts.data[0].a[0].b[0].data[0][0]);
171
+ });
172
+ });
node_modules/@gradio/client/src/client.ts ADDED
@@ -0,0 +1,1727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //@ts-nocheck
2
+
3
+ import semiver from "semiver";
4
+
5
+ import {
6
+ process_endpoint,
7
+ RE_SPACE_NAME,
8
+ map_names_to_ids,
9
+ discussions_enabled,
10
+ get_space_hardware,
11
+ set_space_hardware,
12
+ set_space_timeout,
13
+ hardware_types,
14
+ resolve_root
15
+ } from "./utils.js";
16
+
17
+ import type {
18
+ EventType,
19
+ EventListener,
20
+ ListenerMap,
21
+ Event,
22
+ Payload,
23
+ PostResponse,
24
+ UploadResponse,
25
+ Status,
26
+ SpaceStatus,
27
+ SpaceStatusCallback
28
+ } from "./types.js";
29
+
30
+ import { FileData, normalise_file } from "./upload";
31
+
32
+ import type { Config } from "./types.js";
33
+
34
+ type event = <K extends EventType>(
35
+ eventType: K,
36
+ listener: EventListener<K>
37
+ ) => SubmitReturn;
38
+ type predict = (
39
+ endpoint: string | number,
40
+ data?: unknown[],
41
+ event_data?: unknown
42
+ ) => Promise<unknown>;
43
+
44
+ type client_return = {
45
+ predict: predict;
46
+ config: Config;
47
+ submit: (
48
+ endpoint: string | number,
49
+ data?: unknown[],
50
+ event_data?: unknown,
51
+ trigger_id?: number | null
52
+ ) => SubmitReturn;
53
+ component_server: (
54
+ component_id: number,
55
+ fn_name: string,
56
+ data: unknown[]
57
+ ) => any;
58
+ view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
59
+ };
60
+
61
+ type SubmitReturn = {
62
+ on: event;
63
+ off: event;
64
+ cancel: () => Promise<void>;
65
+ destroy: () => void;
66
+ };
67
+
68
+ const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
69
+ const BROKEN_CONNECTION_MSG = "Connection errored out.";
70
+
71
+ export let NodeBlob;
72
+
73
+ export async function duplicate(
74
+ app_reference: string,
75
+ options: {
76
+ hf_token: `hf_${string}`;
77
+ private?: boolean;
78
+ status_callback: SpaceStatusCallback;
79
+ hardware?: (typeof hardware_types)[number];
80
+ timeout?: number;
81
+ }
82
+ ): Promise<client_return> {
83
+ const { hf_token, private: _private, hardware, timeout } = options;
84
+
85
+ if (hardware && !hardware_types.includes(hardware)) {
86
+ throw new Error(
87
+ `Invalid hardware type provided. Valid types are: ${hardware_types
88
+ .map((v) => `"${v}"`)
89
+ .join(",")}.`
90
+ );
91
+ }
92
+ const headers = {
93
+ Authorization: `Bearer ${hf_token}`
94
+ };
95
+
96
+ const user = (
97
+ await (
98
+ await fetch(`https://huggingface.co/api/whoami-v2`, {
99
+ headers
100
+ })
101
+ ).json()
102
+ ).name;
103
+
104
+ const space_name = app_reference.split("/")[1];
105
+ const body: {
106
+ repository: string;
107
+ private?: boolean;
108
+ } = {
109
+ repository: `${user}/${space_name}`
110
+ };
111
+
112
+ if (_private) {
113
+ body.private = true;
114
+ }
115
+
116
+ try {
117
+ const response = await fetch(
118
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
119
+ {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/json", ...headers },
122
+ body: JSON.stringify(body)
123
+ }
124
+ );
125
+
126
+ if (response.status === 409) {
127
+ return client(`${user}/${space_name}`, options);
128
+ }
129
+ const duplicated_space = await response.json();
130
+
131
+ let original_hardware;
132
+
133
+ if (!hardware) {
134
+ original_hardware = await get_space_hardware(app_reference, hf_token);
135
+ }
136
+
137
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
138
+ await set_space_hardware(
139
+ `${user}/${space_name}`,
140
+ requested_hardware,
141
+ hf_token
142
+ );
143
+
144
+ await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
145
+ return client(duplicated_space.url, options);
146
+ } catch (e: any) {
147
+ throw new Error(e);
148
+ }
149
+ }
150
+
151
+ interface Client {
152
+ post_data: (
153
+ url: string,
154
+ body: unknown,
155
+ token?: `hf_${string}`
156
+ ) => Promise<[PostResponse, number]>;
157
+ upload_files: (
158
+ root: string,
159
+ files: File[],
160
+ token?: `hf_${string}`,
161
+ upload_id?: string
162
+ ) => Promise<UploadResponse>;
163
+ client: (
164
+ app_reference: string,
165
+ options: {
166
+ hf_token?: `hf_${string}`;
167
+ status_callback?: SpaceStatusCallback;
168
+ normalise_files?: boolean;
169
+ }
170
+ ) => Promise<client_return>;
171
+ handle_blob: (
172
+ endpoint: string,
173
+ data: unknown[],
174
+ api_info: ApiInfo<JsApiData>,
175
+ token?: `hf_${string}`
176
+ ) => Promise<unknown[]>;
177
+ }
178
+
179
+ export function api_factory(
180
+ fetch_implementation: typeof fetch,
181
+ EventSource_factory: (url: URL) => EventSource
182
+ ): Client {
183
+ return { post_data, upload_files, client, handle_blob };
184
+
185
+ async function post_data(
186
+ url: string,
187
+ body: unknown,
188
+ token?: `hf_${string}`
189
+ ): Promise<[PostResponse, number]> {
190
+ const headers: {
191
+ Authorization?: string;
192
+ "Content-Type": "application/json";
193
+ } = { "Content-Type": "application/json" };
194
+ if (token) {
195
+ headers.Authorization = `Bearer ${token}`;
196
+ }
197
+ try {
198
+ var response = await fetch_implementation(url, {
199
+ method: "POST",
200
+ body: JSON.stringify(body),
201
+ headers
202
+ });
203
+ } catch (e) {
204
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
205
+ }
206
+ let output: PostResponse;
207
+ let status: int;
208
+ try {
209
+ output = await response.json();
210
+ status = response.status;
211
+ } catch (e) {
212
+ output = { error: `Could not parse server response: ${e}` };
213
+ status = 500;
214
+ }
215
+ return [output, status];
216
+ }
217
+
218
+ async function upload_files(
219
+ root: string,
220
+ files: (Blob | File)[],
221
+ token?: `hf_${string}`,
222
+ upload_id?: string
223
+ ): Promise<UploadResponse> {
224
+ const headers: {
225
+ Authorization?: string;
226
+ } = {};
227
+ if (token) {
228
+ headers.Authorization = `Bearer ${token}`;
229
+ }
230
+ const chunkSize = 1000;
231
+ const uploadResponses = [];
232
+ for (let i = 0; i < files.length; i += chunkSize) {
233
+ const chunk = files.slice(i, i + chunkSize);
234
+ const formData = new FormData();
235
+ chunk.forEach((file) => {
236
+ formData.append("files", file);
237
+ });
238
+ try {
239
+ const upload_url = upload_id
240
+ ? `${root}/upload?upload_id=${upload_id}`
241
+ : `${root}/upload`;
242
+ var response = await fetch_implementation(upload_url, {
243
+ method: "POST",
244
+ body: formData,
245
+ headers
246
+ });
247
+ } catch (e) {
248
+ return { error: BROKEN_CONNECTION_MSG };
249
+ }
250
+ const output: UploadResponse["files"] = await response.json();
251
+ uploadResponses.push(...output);
252
+ }
253
+ return { files: uploadResponses };
254
+ }
255
+
256
+ async function client(
257
+ app_reference: string,
258
+ options: {
259
+ hf_token?: `hf_${string}`;
260
+ status_callback?: SpaceStatusCallback;
261
+ normalise_files?: boolean;
262
+ } = { normalise_files: true }
263
+ ): Promise<client_return> {
264
+ return new Promise(async (res) => {
265
+ const { status_callback, hf_token, normalise_files } = options;
266
+ const return_obj = {
267
+ predict,
268
+ submit,
269
+ view_api,
270
+ component_server
271
+ };
272
+
273
+ const transform_files = normalise_files ?? true;
274
+ if (
275
+ (typeof window === "undefined" || !("WebSocket" in window)) &&
276
+ !global.Websocket
277
+ ) {
278
+ const ws = await import("ws");
279
+ NodeBlob = (await import("node:buffer")).Blob;
280
+ //@ts-ignore
281
+ global.WebSocket = ws.WebSocket;
282
+ }
283
+
284
+ const { ws_protocol, http_protocol, host, space_id } =
285
+ await process_endpoint(app_reference, hf_token);
286
+
287
+ const session_hash = Math.random().toString(36).substring(2);
288
+ const last_status: Record<string, Status["stage"]> = {};
289
+ let stream_open = false;
290
+ let pending_stream_messages: Record<string, any[]> = {}; // Event messages may be received by the SSE stream before the initial data POST request is complete. To resolve this race condition, we store the messages in a dictionary and process them when the POST request is complete.
291
+ let event_stream: EventSource | null = null;
292
+ const event_callbacks: Record<string, () => Promise<void>> = {};
293
+ const unclosed_events: Set<string> = new Set();
294
+ let config: Config;
295
+ let api_map: Record<string, number> = {};
296
+
297
+ let jwt: false | string = false;
298
+
299
+ if (hf_token && space_id) {
300
+ jwt = await get_jwt(space_id, hf_token);
301
+ }
302
+
303
+ async function config_success(_config: Config): Promise<client_return> {
304
+ config = _config;
305
+ api_map = map_names_to_ids(_config?.dependencies || []);
306
+ if (config.auth_required) {
307
+ return {
308
+ config,
309
+ ...return_obj
310
+ };
311
+ }
312
+ try {
313
+ api = await view_api(config);
314
+ } catch (e) {
315
+ console.error(`Could not get api details: ${e.message}`);
316
+ }
317
+
318
+ return {
319
+ config,
320
+ ...return_obj
321
+ };
322
+ }
323
+ let api: ApiInfo<JsApiData>;
324
+ async function handle_space_sucess(status: SpaceStatus): Promise<void> {
325
+ if (status_callback) status_callback(status);
326
+ if (status.status === "running")
327
+ try {
328
+ config = await resolve_config(
329
+ fetch_implementation,
330
+ `${http_protocol}//${host}`,
331
+ hf_token
332
+ );
333
+
334
+ const _config = await config_success(config);
335
+ res(_config);
336
+ } catch (e) {
337
+ console.error(e);
338
+ if (status_callback) {
339
+ status_callback({
340
+ status: "error",
341
+ message: "Could not load this space.",
342
+ load_status: "error",
343
+ detail: "NOT_FOUND"
344
+ });
345
+ }
346
+ }
347
+ }
348
+
349
+ try {
350
+ config = await resolve_config(
351
+ fetch_implementation,
352
+ `${http_protocol}//${host}`,
353
+ hf_token
354
+ );
355
+
356
+ const _config = await config_success(config);
357
+ res(_config);
358
+ } catch (e) {
359
+ console.error(e);
360
+ if (space_id) {
361
+ check_space_status(
362
+ space_id,
363
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
364
+ handle_space_sucess
365
+ );
366
+ } else {
367
+ if (status_callback)
368
+ status_callback({
369
+ status: "error",
370
+ message: "Could not load this space.",
371
+ load_status: "error",
372
+ detail: "NOT_FOUND"
373
+ });
374
+ }
375
+ }
376
+
377
+ function predict(
378
+ endpoint: string,
379
+ data: unknown[],
380
+ event_data?: unknown
381
+ ): Promise<unknown> {
382
+ let data_returned = false;
383
+ let status_complete = false;
384
+ let dependency;
385
+ if (typeof endpoint === "number") {
386
+ dependency = config.dependencies[endpoint];
387
+ } else {
388
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
389
+ dependency = config.dependencies[api_map[trimmed_endpoint]];
390
+ }
391
+
392
+ if (dependency.types.continuous) {
393
+ throw new Error(
394
+ "Cannot call predict on this function as it may run forever. Use submit instead"
395
+ );
396
+ }
397
+
398
+ return new Promise((res, rej) => {
399
+ const app = submit(endpoint, data, event_data);
400
+ let result;
401
+
402
+ app
403
+ .on("data", (d) => {
404
+ // if complete message comes before data, resolve here
405
+ if (status_complete) {
406
+ app.destroy();
407
+ res(d);
408
+ }
409
+ data_returned = true;
410
+ result = d;
411
+ })
412
+ .on("status", (status) => {
413
+ if (status.stage === "error") rej(status);
414
+ if (status.stage === "complete") {
415
+ status_complete = true;
416
+ // if complete message comes after data, resolve here
417
+ if (data_returned) {
418
+ app.destroy();
419
+ res(result);
420
+ }
421
+ }
422
+ });
423
+ });
424
+ }
425
+
426
+ function submit(
427
+ endpoint: string | number,
428
+ data: unknown[],
429
+ event_data?: unknown,
430
+ trigger_id: number | null = null
431
+ ): SubmitReturn {
432
+ let fn_index: number;
433
+ let api_info;
434
+
435
+ if (typeof endpoint === "number") {
436
+ fn_index = endpoint;
437
+ api_info = api.unnamed_endpoints[fn_index];
438
+ } else {
439
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
440
+
441
+ fn_index = api_map[trimmed_endpoint];
442
+ api_info = api.named_endpoints[endpoint.trim()];
443
+ }
444
+
445
+ if (typeof fn_index !== "number") {
446
+ throw new Error(
447
+ "There is no endpoint matching that name of fn_index matching that number."
448
+ );
449
+ }
450
+
451
+ let websocket: WebSocket;
452
+ let eventSource: EventSource;
453
+ let protocol = config.protocol ?? "ws";
454
+
455
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
456
+ let payload: Payload;
457
+ let event_id: string | null = null;
458
+ let complete: false | Record<string, any> = false;
459
+ const listener_map: ListenerMap<EventType> = {};
460
+ let url_params = "";
461
+ if (typeof window !== "undefined") {
462
+ url_params = new URLSearchParams(window.location.search).toString();
463
+ }
464
+
465
+ handle_blob(`${config.root}`, data, api_info, hf_token).then(
466
+ (_payload) => {
467
+ payload = {
468
+ data: _payload || [],
469
+ event_data,
470
+ fn_index,
471
+ trigger_id
472
+ };
473
+ if (skip_queue(fn_index, config)) {
474
+ fire_event({
475
+ type: "status",
476
+ endpoint: _endpoint,
477
+ stage: "pending",
478
+ queue: false,
479
+ fn_index,
480
+ time: new Date()
481
+ });
482
+
483
+ post_data(
484
+ `${config.root}/run${
485
+ _endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`
486
+ }${url_params ? "?" + url_params : ""}`,
487
+ {
488
+ ...payload,
489
+ session_hash
490
+ },
491
+ hf_token
492
+ )
493
+ .then(([output, status_code]) => {
494
+ const data = transform_files
495
+ ? transform_output(
496
+ output.data,
497
+ api_info,
498
+ config.root,
499
+ config.root_url
500
+ )
501
+ : output.data;
502
+ if (status_code == 200) {
503
+ fire_event({
504
+ type: "data",
505
+ endpoint: _endpoint,
506
+ fn_index,
507
+ data: data,
508
+ time: new Date()
509
+ });
510
+
511
+ fire_event({
512
+ type: "status",
513
+ endpoint: _endpoint,
514
+ fn_index,
515
+ stage: "complete",
516
+ eta: output.average_duration,
517
+ queue: false,
518
+ time: new Date()
519
+ });
520
+ } else {
521
+ fire_event({
522
+ type: "status",
523
+ stage: "error",
524
+ endpoint: _endpoint,
525
+ fn_index,
526
+ message: output.error,
527
+ queue: false,
528
+ time: new Date()
529
+ });
530
+ }
531
+ })
532
+ .catch((e) => {
533
+ fire_event({
534
+ type: "status",
535
+ stage: "error",
536
+ message: e.message,
537
+ endpoint: _endpoint,
538
+ fn_index,
539
+ queue: false,
540
+ time: new Date()
541
+ });
542
+ });
543
+ } else if (protocol == "ws") {
544
+ fire_event({
545
+ type: "status",
546
+ stage: "pending",
547
+ queue: true,
548
+ endpoint: _endpoint,
549
+ fn_index,
550
+ time: new Date()
551
+ });
552
+ let url = new URL(`${ws_protocol}://${resolve_root(
553
+ host,
554
+ config.path,
555
+ true
556
+ )}
557
+ /queue/join${url_params ? "?" + url_params : ""}`);
558
+
559
+ if (jwt) {
560
+ url.searchParams.set("__sign", jwt);
561
+ }
562
+
563
+ websocket = new WebSocket(url);
564
+
565
+ websocket.onclose = (evt) => {
566
+ if (!evt.wasClean) {
567
+ fire_event({
568
+ type: "status",
569
+ stage: "error",
570
+ broken: true,
571
+ message: BROKEN_CONNECTION_MSG,
572
+ queue: true,
573
+ endpoint: _endpoint,
574
+ fn_index,
575
+ time: new Date()
576
+ });
577
+ }
578
+ };
579
+
580
+ websocket.onmessage = function (event) {
581
+ const _data = JSON.parse(event.data);
582
+ const { type, status, data } = handle_message(
583
+ _data,
584
+ last_status[fn_index]
585
+ );
586
+
587
+ if (type === "update" && status && !complete) {
588
+ // call 'status' listeners
589
+ fire_event({
590
+ type: "status",
591
+ endpoint: _endpoint,
592
+ fn_index,
593
+ time: new Date(),
594
+ ...status
595
+ });
596
+ if (status.stage === "error") {
597
+ websocket.close();
598
+ }
599
+ } else if (type === "hash") {
600
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
601
+ return;
602
+ } else if (type === "data") {
603
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
604
+ } else if (type === "complete") {
605
+ complete = status;
606
+ } else if (type === "log") {
607
+ fire_event({
608
+ type: "log",
609
+ log: data.log,
610
+ level: data.level,
611
+ endpoint: _endpoint,
612
+ fn_index
613
+ });
614
+ } else if (type === "generating") {
615
+ fire_event({
616
+ type: "status",
617
+ time: new Date(),
618
+ ...status,
619
+ stage: status?.stage!,
620
+ queue: true,
621
+ endpoint: _endpoint,
622
+ fn_index
623
+ });
624
+ }
625
+ if (data) {
626
+ fire_event({
627
+ type: "data",
628
+ time: new Date(),
629
+ data: transform_files
630
+ ? transform_output(
631
+ data.data,
632
+ api_info,
633
+ config.root,
634
+ config.root_url
635
+ )
636
+ : data.data,
637
+ endpoint: _endpoint,
638
+ fn_index
639
+ });
640
+
641
+ if (complete) {
642
+ fire_event({
643
+ type: "status",
644
+ time: new Date(),
645
+ ...complete,
646
+ stage: status?.stage!,
647
+ queue: true,
648
+ endpoint: _endpoint,
649
+ fn_index
650
+ });
651
+ websocket.close();
652
+ }
653
+ }
654
+ };
655
+
656
+ // different ws contract for gradio versions older than 3.6.0
657
+ //@ts-ignore
658
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
659
+ addEventListener("open", () =>
660
+ websocket.send(JSON.stringify({ hash: session_hash }))
661
+ );
662
+ }
663
+ } else if (protocol == "sse") {
664
+ fire_event({
665
+ type: "status",
666
+ stage: "pending",
667
+ queue: true,
668
+ endpoint: _endpoint,
669
+ fn_index,
670
+ time: new Date()
671
+ });
672
+ var params = new URLSearchParams({
673
+ fn_index: fn_index.toString(),
674
+ session_hash: session_hash
675
+ }).toString();
676
+ let url = new URL(
677
+ `${config.root}/queue/join?${
678
+ url_params ? url_params + "&" : ""
679
+ }${params}`
680
+ );
681
+
682
+ eventSource = EventSource_factory(url);
683
+
684
+ eventSource.onmessage = async function (event) {
685
+ const _data = JSON.parse(event.data);
686
+ const { type, status, data } = handle_message(
687
+ _data,
688
+ last_status[fn_index]
689
+ );
690
+
691
+ if (type === "update" && status && !complete) {
692
+ // call 'status' listeners
693
+ fire_event({
694
+ type: "status",
695
+ endpoint: _endpoint,
696
+ fn_index,
697
+ time: new Date(),
698
+ ...status
699
+ });
700
+ if (status.stage === "error") {
701
+ eventSource.close();
702
+ }
703
+ } else if (type === "data") {
704
+ event_id = _data.event_id as string;
705
+ let [_, status] = await post_data(
706
+ `${config.root}/queue/data`,
707
+ {
708
+ ...payload,
709
+ session_hash,
710
+ event_id
711
+ },
712
+ hf_token
713
+ );
714
+ if (status !== 200) {
715
+ fire_event({
716
+ type: "status",
717
+ stage: "error",
718
+ message: BROKEN_CONNECTION_MSG,
719
+ queue: true,
720
+ endpoint: _endpoint,
721
+ fn_index,
722
+ time: new Date()
723
+ });
724
+ eventSource.close();
725
+ }
726
+ } else if (type === "complete") {
727
+ complete = status;
728
+ } else if (type === "log") {
729
+ fire_event({
730
+ type: "log",
731
+ log: data.log,
732
+ level: data.level,
733
+ endpoint: _endpoint,
734
+ fn_index
735
+ });
736
+ } else if (type === "generating") {
737
+ fire_event({
738
+ type: "status",
739
+ time: new Date(),
740
+ ...status,
741
+ stage: status?.stage!,
742
+ queue: true,
743
+ endpoint: _endpoint,
744
+ fn_index
745
+ });
746
+ }
747
+ if (data) {
748
+ fire_event({
749
+ type: "data",
750
+ time: new Date(),
751
+ data: transform_files
752
+ ? transform_output(
753
+ data.data,
754
+ api_info,
755
+ config.root,
756
+ config.root_url
757
+ )
758
+ : data.data,
759
+ endpoint: _endpoint,
760
+ fn_index
761
+ });
762
+
763
+ if (complete) {
764
+ fire_event({
765
+ type: "status",
766
+ time: new Date(),
767
+ ...complete,
768
+ stage: status?.stage!,
769
+ queue: true,
770
+ endpoint: _endpoint,
771
+ fn_index
772
+ });
773
+ eventSource.close();
774
+ }
775
+ }
776
+ };
777
+ } else if (protocol == "sse_v1") {
778
+ fire_event({
779
+ type: "status",
780
+ stage: "pending",
781
+ queue: true,
782
+ endpoint: _endpoint,
783
+ fn_index,
784
+ time: new Date()
785
+ });
786
+
787
+ post_data(
788
+ `${config.root}/queue/join?${url_params}`,
789
+ {
790
+ ...payload,
791
+ session_hash
792
+ },
793
+ hf_token
794
+ ).then(([response, status]) => {
795
+ if (status === 503) {
796
+ fire_event({
797
+ type: "status",
798
+ stage: "error",
799
+ message: QUEUE_FULL_MSG,
800
+ queue: true,
801
+ endpoint: _endpoint,
802
+ fn_index,
803
+ time: new Date()
804
+ });
805
+ } else if (status !== 200) {
806
+ fire_event({
807
+ type: "status",
808
+ stage: "error",
809
+ message: BROKEN_CONNECTION_MSG,
810
+ queue: true,
811
+ endpoint: _endpoint,
812
+ fn_index,
813
+ time: new Date()
814
+ });
815
+ } else {
816
+ event_id = response.event_id as string;
817
+ let callback = async function (_data: object): void {
818
+ try {
819
+ const { type, status, data } = handle_message(
820
+ _data,
821
+ last_status[fn_index]
822
+ );
823
+
824
+ if (type == "heartbeat") {
825
+ return;
826
+ }
827
+
828
+ if (type === "update" && status && !complete) {
829
+ // call 'status' listeners
830
+ fire_event({
831
+ type: "status",
832
+ endpoint: _endpoint,
833
+ fn_index,
834
+ time: new Date(),
835
+ ...status
836
+ });
837
+ } else if (type === "complete") {
838
+ complete = status;
839
+ } else if (type == "unexpected_error") {
840
+ console.error("Unexpected error", status?.message);
841
+ fire_event({
842
+ type: "status",
843
+ stage: "error",
844
+ message:
845
+ status?.message || "An Unexpected Error Occurred!",
846
+ queue: true,
847
+ endpoint: _endpoint,
848
+ fn_index,
849
+ time: new Date()
850
+ });
851
+ } else if (type === "log") {
852
+ fire_event({
853
+ type: "log",
854
+ log: data.log,
855
+ level: data.level,
856
+ endpoint: _endpoint,
857
+ fn_index
858
+ });
859
+ return;
860
+ } else if (type === "generating") {
861
+ fire_event({
862
+ type: "status",
863
+ time: new Date(),
864
+ ...status,
865
+ stage: status?.stage!,
866
+ queue: true,
867
+ endpoint: _endpoint,
868
+ fn_index
869
+ });
870
+ }
871
+ if (data) {
872
+ fire_event({
873
+ type: "data",
874
+ time: new Date(),
875
+ data: transform_files
876
+ ? transform_output(
877
+ data.data,
878
+ api_info,
879
+ config.root,
880
+ config.root_url
881
+ )
882
+ : data.data,
883
+ endpoint: _endpoint,
884
+ fn_index
885
+ });
886
+
887
+ if (complete) {
888
+ fire_event({
889
+ type: "status",
890
+ time: new Date(),
891
+ ...complete,
892
+ stage: status?.stage!,
893
+ queue: true,
894
+ endpoint: _endpoint,
895
+ fn_index
896
+ });
897
+ }
898
+ }
899
+
900
+ if (
901
+ status?.stage === "complete" ||
902
+ status?.stage === "error"
903
+ ) {
904
+ if (event_callbacks[event_id]) {
905
+ delete event_callbacks[event_id];
906
+ }
907
+ }
908
+ } catch (e) {
909
+ console.error("Unexpected client exception", e);
910
+ fire_event({
911
+ type: "status",
912
+ stage: "error",
913
+ message: "An Unexpected Error Occurred!",
914
+ queue: true,
915
+ endpoint: _endpoint,
916
+ fn_index,
917
+ time: new Date()
918
+ });
919
+ close_stream();
920
+ }
921
+ };
922
+ if (event_id in pending_stream_messages) {
923
+ pending_stream_messages[event_id].forEach((msg) =>
924
+ callback(msg)
925
+ );
926
+ delete pending_stream_messages[event_id];
927
+ }
928
+ event_callbacks[event_id] = callback;
929
+ unclosed_events.add(event_id);
930
+ if (!stream_open) {
931
+ open_stream();
932
+ }
933
+ }
934
+ });
935
+ }
936
+ }
937
+ );
938
+
939
+ function fire_event<K extends EventType>(event: Event<K>): void {
940
+ const narrowed_listener_map: ListenerMap<K> = listener_map;
941
+ const listeners = narrowed_listener_map[event.type] || [];
942
+ listeners?.forEach((l) => l(event));
943
+ }
944
+
945
+ function on<K extends EventType>(
946
+ eventType: K,
947
+ listener: EventListener<K>
948
+ ): SubmitReturn {
949
+ const narrowed_listener_map: ListenerMap<K> = listener_map;
950
+ const listeners = narrowed_listener_map[eventType] || [];
951
+ narrowed_listener_map[eventType] = listeners;
952
+ listeners?.push(listener);
953
+
954
+ return { on, off, cancel, destroy };
955
+ }
956
+
957
+ function off<K extends EventType>(
958
+ eventType: K,
959
+ listener: EventListener<K>
960
+ ): SubmitReturn {
961
+ const narrowed_listener_map: ListenerMap<K> = listener_map;
962
+ let listeners = narrowed_listener_map[eventType] || [];
963
+ listeners = listeners?.filter((l) => l !== listener);
964
+ narrowed_listener_map[eventType] = listeners;
965
+
966
+ return { on, off, cancel, destroy };
967
+ }
968
+
969
+ async function cancel(): Promise<void> {
970
+ const _status: Status = {
971
+ stage: "complete",
972
+ queue: false,
973
+ time: new Date()
974
+ };
975
+ complete = _status;
976
+ fire_event({
977
+ ..._status,
978
+ type: "status",
979
+ endpoint: _endpoint,
980
+ fn_index: fn_index
981
+ });
982
+
983
+ let cancel_request = {};
984
+ if (protocol === "ws") {
985
+ if (websocket && websocket.readyState === 0) {
986
+ websocket.addEventListener("open", () => {
987
+ websocket.close();
988
+ });
989
+ } else {
990
+ websocket.close();
991
+ }
992
+ cancel_request = { fn_index, session_hash };
993
+ } else {
994
+ eventSource.close();
995
+ cancel_request = { event_id };
996
+ }
997
+
998
+ try {
999
+ await fetch_implementation(`${config.root}/reset`, {
1000
+ headers: { "Content-Type": "application/json" },
1001
+ method: "POST",
1002
+ body: JSON.stringify(cancel_request)
1003
+ });
1004
+ } catch (e) {
1005
+ console.warn(
1006
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1007
+ );
1008
+ }
1009
+ }
1010
+
1011
+ function destroy(): void {
1012
+ for (const event_type in listener_map) {
1013
+ listener_map[event_type as "data" | "status"].forEach((fn) => {
1014
+ off(event_type as "data" | "status", fn);
1015
+ });
1016
+ }
1017
+ }
1018
+
1019
+ return {
1020
+ on,
1021
+ off,
1022
+ cancel,
1023
+ destroy
1024
+ };
1025
+ }
1026
+
1027
+ function open_stream(): void {
1028
+ stream_open = true;
1029
+ let params = new URLSearchParams({
1030
+ session_hash: session_hash
1031
+ }).toString();
1032
+ let url = new URL(`${config.root}/queue/data?${params}`);
1033
+ event_stream = EventSource_factory(url);
1034
+ event_stream.onmessage = async function (event) {
1035
+ let _data = JSON.parse(event.data);
1036
+ const event_id = _data.event_id;
1037
+ if (!event_id) {
1038
+ await Promise.all(
1039
+ Object.keys(event_callbacks).map((event_id) =>
1040
+ event_callbacks[event_id](_data)
1041
+ )
1042
+ );
1043
+ } else if (event_callbacks[event_id]) {
1044
+ if (_data.msg === "process_completed") {
1045
+ unclosed_events.delete(event_id);
1046
+ if (unclosed_events.size === 0) {
1047
+ close_stream();
1048
+ }
1049
+ }
1050
+ let fn = event_callbacks[event_id];
1051
+ window.setTimeout(fn, 0, _data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See https://github.com/gradio-app/gradio/pull/7055
1052
+ } else {
1053
+ if (!pending_stream_messages[event_id]) {
1054
+ pending_stream_messages[event_id] = [];
1055
+ }
1056
+ pending_stream_messages[event_id].push(_data);
1057
+ }
1058
+ };
1059
+ event_stream.onerror = async function (event) {
1060
+ await Promise.all(
1061
+ Object.keys(event_callbacks).map((event_id) =>
1062
+ event_callbacks[event_id]({
1063
+ msg: "unexpected_error",
1064
+ message: BROKEN_CONNECTION_MSG
1065
+ })
1066
+ )
1067
+ );
1068
+ close_stream();
1069
+ };
1070
+ }
1071
+
1072
+ function close_stream(): void {
1073
+ stream_open = false;
1074
+ event_stream?.close();
1075
+ }
1076
+
1077
+ async function component_server(
1078
+ component_id: number,
1079
+ fn_name: string,
1080
+ data: unknown[]
1081
+ ): Promise<any> {
1082
+ const headers: {
1083
+ Authorization?: string;
1084
+ "Content-Type": "application/json";
1085
+ } = { "Content-Type": "application/json" };
1086
+ if (hf_token) {
1087
+ headers.Authorization = `Bearer ${hf_token}`;
1088
+ }
1089
+ let root_url: string;
1090
+ let component = config.components.find(
1091
+ (comp) => comp.id === component_id
1092
+ );
1093
+ if (component?.props?.root_url) {
1094
+ root_url = component.props.root_url;
1095
+ } else {
1096
+ root_url = config.root;
1097
+ }
1098
+ const response = await fetch_implementation(
1099
+ `${root_url}/component_server/`,
1100
+ {
1101
+ method: "POST",
1102
+ body: JSON.stringify({
1103
+ data: data,
1104
+ component_id: component_id,
1105
+ fn_name: fn_name,
1106
+ session_hash: session_hash
1107
+ }),
1108
+ headers
1109
+ }
1110
+ );
1111
+
1112
+ if (!response.ok) {
1113
+ throw new Error(
1114
+ "Could not connect to component server: " + response.statusText
1115
+ );
1116
+ }
1117
+
1118
+ const output = await response.json();
1119
+ return output;
1120
+ }
1121
+
1122
+ async function view_api(config?: Config): Promise<ApiInfo<JsApiData>> {
1123
+ if (api) return api;
1124
+
1125
+ const headers: {
1126
+ Authorization?: string;
1127
+ "Content-Type": "application/json";
1128
+ } = { "Content-Type": "application/json" };
1129
+ if (hf_token) {
1130
+ headers.Authorization = `Bearer ${hf_token}`;
1131
+ }
1132
+ let response: Response;
1133
+ // @ts-ignore
1134
+ if (semiver(config.version || "2.0.0", "3.30") < 0) {
1135
+ response = await fetch_implementation(
1136
+ "https://gradio-space-api-fetcher-v2.hf.space/api",
1137
+ {
1138
+ method: "POST",
1139
+ body: JSON.stringify({
1140
+ serialize: false,
1141
+ config: JSON.stringify(config)
1142
+ }),
1143
+ headers
1144
+ }
1145
+ );
1146
+ } else {
1147
+ response = await fetch_implementation(`${config.root}/info`, {
1148
+ headers
1149
+ });
1150
+ }
1151
+
1152
+ if (!response.ok) {
1153
+ throw new Error(BROKEN_CONNECTION_MSG);
1154
+ }
1155
+
1156
+ let api_info = (await response.json()) as
1157
+ | ApiInfo<ApiData>
1158
+ | { api: ApiInfo<ApiData> };
1159
+ if ("api" in api_info) {
1160
+ api_info = api_info.api;
1161
+ }
1162
+
1163
+ if (
1164
+ api_info.named_endpoints["/predict"] &&
1165
+ !api_info.unnamed_endpoints["0"]
1166
+ ) {
1167
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
1168
+ }
1169
+
1170
+ const x = transform_api_info(api_info, config, api_map);
1171
+ return x;
1172
+ }
1173
+ });
1174
+ }
1175
+
1176
+ async function handle_blob(
1177
+ endpoint: string,
1178
+ data: unknown[],
1179
+ api_info: ApiInfo<JsApiData>,
1180
+ token?: `hf_${string}`
1181
+ ): Promise<unknown[]> {
1182
+ const blob_refs = await walk_and_store_blobs(
1183
+ data,
1184
+ undefined,
1185
+ [],
1186
+ true,
1187
+ api_info
1188
+ );
1189
+
1190
+ return Promise.all(
1191
+ blob_refs.map(async ({ path, blob, type }) => {
1192
+ if (blob) {
1193
+ const file_url = (await upload_files(endpoint, [blob], token))
1194
+ .files[0];
1195
+ return { path, file_url, type, name: blob?.name };
1196
+ }
1197
+ return { path, type };
1198
+ })
1199
+ ).then((r) => {
1200
+ r.forEach(({ path, file_url, type, name }) => {
1201
+ if (type === "Gallery") {
1202
+ update_object(data, file_url, path);
1203
+ } else if (file_url) {
1204
+ const file = new FileData({ path: file_url, orig_name: name });
1205
+ update_object(data, file, path);
1206
+ }
1207
+ });
1208
+
1209
+ return data;
1210
+ });
1211
+ }
1212
+ }
1213
+
1214
+ export const { post_data, upload_files, client, handle_blob } = api_factory(
1215
+ fetch,
1216
+ (...args) => new EventSource(...args)
1217
+ );
1218
+
1219
+ function transform_output(
1220
+ data: any[],
1221
+ api_info: any,
1222
+ root_url: string,
1223
+ remote_url?: string
1224
+ ): unknown[] {
1225
+ return data.map((d, i) => {
1226
+ if (api_info?.returns?.[i]?.component === "File") {
1227
+ return normalise_file(d, root_url, remote_url);
1228
+ } else if (api_info?.returns?.[i]?.component === "Gallery") {
1229
+ return d.map((img) => {
1230
+ return Array.isArray(img)
1231
+ ? [normalise_file(img[0], root_url, remote_url), img[1]]
1232
+ : [normalise_file(img, root_url, remote_url), null];
1233
+ });
1234
+ } else if (typeof d === "object" && d.path) {
1235
+ return normalise_file(d, root_url, remote_url);
1236
+ }
1237
+ return d;
1238
+ });
1239
+ }
1240
+
1241
+ interface ApiData {
1242
+ label: string;
1243
+ type: {
1244
+ type: any;
1245
+ description: string;
1246
+ };
1247
+ component: string;
1248
+ example_input?: any;
1249
+ }
1250
+
1251
+ interface JsApiData {
1252
+ label: string;
1253
+ type: string;
1254
+ component: string;
1255
+ example_input: any;
1256
+ }
1257
+
1258
+ interface EndpointInfo<T extends ApiData | JsApiData> {
1259
+ parameters: T[];
1260
+ returns: T[];
1261
+ }
1262
+ interface ApiInfo<T extends ApiData | JsApiData> {
1263
+ named_endpoints: {
1264
+ [key: string]: EndpointInfo<T>;
1265
+ };
1266
+ unnamed_endpoints: {
1267
+ [key: string]: EndpointInfo<T>;
1268
+ };
1269
+ }
1270
+
1271
+ function get_type(
1272
+ type: { [key: string]: any },
1273
+ component: string,
1274
+ serializer: string,
1275
+ signature_type: "return" | "parameter"
1276
+ ): string {
1277
+ switch (type.type) {
1278
+ case "string":
1279
+ return "string";
1280
+ case "boolean":
1281
+ return "boolean";
1282
+ case "number":
1283
+ return "number";
1284
+ }
1285
+
1286
+ if (
1287
+ serializer === "JSONSerializable" ||
1288
+ serializer === "StringSerializable"
1289
+ ) {
1290
+ return "any";
1291
+ } else if (serializer === "ListStringSerializable") {
1292
+ return "string[]";
1293
+ } else if (component === "Image") {
1294
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
1295
+ } else if (serializer === "FileSerializable") {
1296
+ if (type?.type === "array") {
1297
+ return signature_type === "parameter"
1298
+ ? "(Blob | File | Buffer)[]"
1299
+ : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
1300
+ }
1301
+ return signature_type === "parameter"
1302
+ ? "Blob | File | Buffer"
1303
+ : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
1304
+ } else if (serializer === "GallerySerializable") {
1305
+ return signature_type === "parameter"
1306
+ ? "[(Blob | File | Buffer), (string | null)][]"
1307
+ : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
1308
+ }
1309
+ }
1310
+
1311
+ function get_description(
1312
+ type: { type: any; description: string },
1313
+ serializer: string
1314
+ ): string {
1315
+ if (serializer === "GallerySerializable") {
1316
+ return "array of [file, label] tuples";
1317
+ } else if (serializer === "ListStringSerializable") {
1318
+ return "array of strings";
1319
+ } else if (serializer === "FileSerializable") {
1320
+ return "array of files or single file";
1321
+ }
1322
+ return type.description;
1323
+ }
1324
+
1325
+ function transform_api_info(
1326
+ api_info: ApiInfo<ApiData>,
1327
+ config: Config,
1328
+ api_map: Record<string, number>
1329
+ ): ApiInfo<JsApiData> {
1330
+ const new_data = {
1331
+ named_endpoints: {},
1332
+ unnamed_endpoints: {}
1333
+ };
1334
+ for (const key in api_info) {
1335
+ const cat = api_info[key];
1336
+
1337
+ for (const endpoint in cat) {
1338
+ const dep_index = config.dependencies[endpoint]
1339
+ ? endpoint
1340
+ : api_map[endpoint.replace("/", "")];
1341
+
1342
+ const info = cat[endpoint];
1343
+ new_data[key][endpoint] = {};
1344
+ new_data[key][endpoint].parameters = {};
1345
+ new_data[key][endpoint].returns = {};
1346
+ new_data[key][endpoint].type = config.dependencies[dep_index].types;
1347
+ new_data[key][endpoint].parameters = info.parameters.map(
1348
+ ({ label, component, type, serializer }) => ({
1349
+ label,
1350
+ component,
1351
+ type: get_type(type, component, serializer, "parameter"),
1352
+ description: get_description(type, serializer)
1353
+ })
1354
+ );
1355
+
1356
+ new_data[key][endpoint].returns = info.returns.map(
1357
+ ({ label, component, type, serializer }) => ({
1358
+ label,
1359
+ component,
1360
+ type: get_type(type, component, serializer, "return"),
1361
+ description: get_description(type, serializer)
1362
+ })
1363
+ );
1364
+ }
1365
+ }
1366
+
1367
+ return new_data;
1368
+ }
1369
+
1370
+ async function get_jwt(
1371
+ space: string,
1372
+ token: `hf_${string}`
1373
+ ): Promise<string | false> {
1374
+ try {
1375
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
1376
+ headers: {
1377
+ Authorization: `Bearer ${token}`
1378
+ }
1379
+ });
1380
+
1381
+ const jwt = (await r.json()).token;
1382
+
1383
+ return jwt || false;
1384
+ } catch (e) {
1385
+ console.error(e);
1386
+ return false;
1387
+ }
1388
+ }
1389
+
1390
+ function update_object(object, newValue, stack): void {
1391
+ while (stack.length > 1) {
1392
+ object = object[stack.shift()];
1393
+ }
1394
+
1395
+ object[stack.shift()] = newValue;
1396
+ }
1397
+
1398
+ export async function walk_and_store_blobs(
1399
+ param,
1400
+ type = undefined,
1401
+ path = [],
1402
+ root = false,
1403
+ api_info = undefined
1404
+ ): Promise<
1405
+ {
1406
+ path: string[];
1407
+ type: string;
1408
+ blob: Blob | false;
1409
+ }[]
1410
+ > {
1411
+ if (Array.isArray(param)) {
1412
+ let blob_refs = [];
1413
+
1414
+ await Promise.all(
1415
+ param.map(async (v, i) => {
1416
+ let new_path = path.slice();
1417
+ new_path.push(i);
1418
+
1419
+ const array_refs = await walk_and_store_blobs(
1420
+ param[i],
1421
+ root ? api_info?.parameters[i]?.component || undefined : type,
1422
+ new_path,
1423
+ false,
1424
+ api_info
1425
+ );
1426
+
1427
+ blob_refs = blob_refs.concat(array_refs);
1428
+ })
1429
+ );
1430
+
1431
+ return blob_refs;
1432
+ } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
1433
+ const is_image = type === "Image";
1434
+ return [
1435
+ {
1436
+ path: path,
1437
+ blob: is_image ? false : new NodeBlob([param]),
1438
+ type
1439
+ }
1440
+ ];
1441
+ } else if (typeof param === "object") {
1442
+ let blob_refs = [];
1443
+ for (let key in param) {
1444
+ if (param.hasOwnProperty(key)) {
1445
+ let new_path = path.slice();
1446
+ new_path.push(key);
1447
+ blob_refs = blob_refs.concat(
1448
+ await walk_and_store_blobs(
1449
+ param[key],
1450
+ undefined,
1451
+ new_path,
1452
+ false,
1453
+ api_info
1454
+ )
1455
+ );
1456
+ }
1457
+ }
1458
+ return blob_refs;
1459
+ }
1460
+ return [];
1461
+ }
1462
+
1463
+ function image_to_data_uri(blob: Blob): Promise<string | ArrayBuffer> {
1464
+ return new Promise((resolve, _) => {
1465
+ const reader = new FileReader();
1466
+ reader.onloadend = () => resolve(reader.result);
1467
+ reader.readAsDataURL(blob);
1468
+ });
1469
+ }
1470
+
1471
+ function skip_queue(id: number, config: Config): boolean {
1472
+ return (
1473
+ !(config?.dependencies?.[id]?.queue === null
1474
+ ? config.enable_queue
1475
+ : config?.dependencies?.[id]?.queue) || false
1476
+ );
1477
+ }
1478
+
1479
+ async function resolve_config(
1480
+ fetch_implementation: typeof fetch,
1481
+ endpoint?: string,
1482
+ token?: `hf_${string}`
1483
+ ): Promise<Config> {
1484
+ const headers: { Authorization?: string } = {};
1485
+ if (token) {
1486
+ headers.Authorization = `Bearer ${token}`;
1487
+ }
1488
+ if (
1489
+ typeof window !== "undefined" &&
1490
+ window.gradio_config &&
1491
+ location.origin !== "http://localhost:9876" &&
1492
+ !window.gradio_config.dev_mode
1493
+ ) {
1494
+ const path = window.gradio_config.root;
1495
+ const config = window.gradio_config;
1496
+ config.root = resolve_root(endpoint, config.root, false);
1497
+ return { ...config, path: path };
1498
+ } else if (endpoint) {
1499
+ let response = await fetch_implementation(`${endpoint}/config`, {
1500
+ headers
1501
+ });
1502
+
1503
+ if (response.status === 200) {
1504
+ const config = await response.json();
1505
+ config.path = config.path ?? "";
1506
+ config.root = endpoint;
1507
+ return config;
1508
+ }
1509
+ throw new Error("Could not get config.");
1510
+ }
1511
+
1512
+ throw new Error("No config or app endpoint found");
1513
+ }
1514
+
1515
+ async function check_space_status(
1516
+ id: string,
1517
+ type: "subdomain" | "space_name",
1518
+ status_callback: SpaceStatusCallback
1519
+ ): Promise<void> {
1520
+ let endpoint =
1521
+ type === "subdomain"
1522
+ ? `https://huggingface.co/api/spaces/by-subdomain/${id}`
1523
+ : `https://huggingface.co/api/spaces/${id}`;
1524
+ let response;
1525
+ let _status;
1526
+ try {
1527
+ response = await fetch(endpoint);
1528
+ _status = response.status;
1529
+ if (_status !== 200) {
1530
+ throw new Error();
1531
+ }
1532
+ response = await response.json();
1533
+ } catch (e) {
1534
+ status_callback({
1535
+ status: "error",
1536
+ load_status: "error",
1537
+ message: "Could not get space status",
1538
+ detail: "NOT_FOUND"
1539
+ });
1540
+ return;
1541
+ }
1542
+
1543
+ if (!response || _status !== 200) return;
1544
+ const {
1545
+ runtime: { stage },
1546
+ id: space_name
1547
+ } = response;
1548
+
1549
+ switch (stage) {
1550
+ case "STOPPED":
1551
+ case "SLEEPING":
1552
+ status_callback({
1553
+ status: "sleeping",
1554
+ load_status: "pending",
1555
+ message: "Space is asleep. Waking it up...",
1556
+ detail: stage
1557
+ });
1558
+
1559
+ setTimeout(() => {
1560
+ check_space_status(id, type, status_callback);
1561
+ }, 1000); // poll for status
1562
+ break;
1563
+ case "PAUSED":
1564
+ status_callback({
1565
+ status: "paused",
1566
+ load_status: "error",
1567
+ message:
1568
+ "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
1569
+ detail: stage,
1570
+ discussions_enabled: await discussions_enabled(space_name)
1571
+ });
1572
+ break;
1573
+ case "RUNNING":
1574
+ case "RUNNING_BUILDING":
1575
+ status_callback({
1576
+ status: "running",
1577
+ load_status: "complete",
1578
+ message: "",
1579
+ detail: stage
1580
+ });
1581
+ // load_config(source);
1582
+ // launch
1583
+ break;
1584
+ case "BUILDING":
1585
+ status_callback({
1586
+ status: "building",
1587
+ load_status: "pending",
1588
+ message: "Space is building...",
1589
+ detail: stage
1590
+ });
1591
+
1592
+ setTimeout(() => {
1593
+ check_space_status(id, type, status_callback);
1594
+ }, 1000);
1595
+ break;
1596
+ default:
1597
+ status_callback({
1598
+ status: "space_error",
1599
+ load_status: "error",
1600
+ message: "This space is experiencing an issue.",
1601
+ detail: stage,
1602
+ discussions_enabled: await discussions_enabled(space_name)
1603
+ });
1604
+ break;
1605
+ }
1606
+ }
1607
+
1608
+ function handle_message(
1609
+ data: any,
1610
+ last_status: Status["stage"]
1611
+ ): {
1612
+ type: "hash" | "data" | "update" | "complete" | "generating" | "log" | "none";
1613
+ data?: any;
1614
+ status?: Status;
1615
+ } {
1616
+ const queue = true;
1617
+ switch (data.msg) {
1618
+ case "send_data":
1619
+ return { type: "data" };
1620
+ case "send_hash":
1621
+ return { type: "hash" };
1622
+ case "queue_full":
1623
+ return {
1624
+ type: "update",
1625
+ status: {
1626
+ queue,
1627
+ message: QUEUE_FULL_MSG,
1628
+ stage: "error",
1629
+ code: data.code,
1630
+ success: data.success
1631
+ }
1632
+ };
1633
+ case "heartbeat":
1634
+ return {
1635
+ type: "heartbeat"
1636
+ };
1637
+ case "unexpected_error":
1638
+ return {
1639
+ type: "unexpected_error",
1640
+ status: {
1641
+ queue,
1642
+ message: data.message,
1643
+ stage: "error",
1644
+ success: false
1645
+ }
1646
+ };
1647
+ case "estimation":
1648
+ return {
1649
+ type: "update",
1650
+ status: {
1651
+ queue,
1652
+ stage: last_status || "pending",
1653
+ code: data.code,
1654
+ size: data.queue_size,
1655
+ position: data.rank,
1656
+ eta: data.rank_eta,
1657
+ success: data.success
1658
+ }
1659
+ };
1660
+ case "progress":
1661
+ return {
1662
+ type: "update",
1663
+ status: {
1664
+ queue,
1665
+ stage: "pending",
1666
+ code: data.code,
1667
+ progress_data: data.progress_data,
1668
+ success: data.success
1669
+ }
1670
+ };
1671
+ case "log":
1672
+ return { type: "log", data: data };
1673
+ case "process_generating":
1674
+ return {
1675
+ type: "generating",
1676
+ status: {
1677
+ queue,
1678
+ message: !data.success ? data.output.error : null,
1679
+ stage: data.success ? "generating" : "error",
1680
+ code: data.code,
1681
+ progress_data: data.progress_data,
1682
+ eta: data.average_duration
1683
+ },
1684
+ data: data.success ? data.output : null
1685
+ };
1686
+ case "process_completed":
1687
+ if ("error" in data.output) {
1688
+ return {
1689
+ type: "update",
1690
+ status: {
1691
+ queue,
1692
+ message: data.output.error as string,
1693
+ stage: "error",
1694
+ code: data.code,
1695
+ success: data.success
1696
+ }
1697
+ };
1698
+ }
1699
+ return {
1700
+ type: "complete",
1701
+ status: {
1702
+ queue,
1703
+ message: !data.success ? data.output.error : undefined,
1704
+ stage: data.success ? "complete" : "error",
1705
+ code: data.code,
1706
+ progress_data: data.progress_data
1707
+ },
1708
+ data: data.success ? data.output : null
1709
+ };
1710
+
1711
+ case "process_starts":
1712
+ return {
1713
+ type: "update",
1714
+ status: {
1715
+ queue,
1716
+ stage: "pending",
1717
+ code: data.code,
1718
+ size: data.rank,
1719
+ position: 0,
1720
+ success: data.success,
1721
+ eta: data.eta
1722
+ }
1723
+ };
1724
+ }
1725
+
1726
+ return { type: "none", status: { stage: "error", queue } };
1727
+ }
node_modules/@gradio/client/src/globals.d.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ declare global {
2
+ interface Window {
3
+ __gradio_mode__: "app" | "website";
4
+ gradio_config: Config;
5
+ __is_colab__: boolean;
6
+ __gradio_space__: string | null;
7
+ }
8
+ }
9
+
10
+ export interface Config {
11
+ auth_required: boolean | undefined;
12
+ auth_message: string;
13
+ components: any[];
14
+ css: string | null;
15
+ dependencies: any[];
16
+ dev_mode: boolean;
17
+ enable_queue: boolean;
18
+ layout: any;
19
+ mode: "blocks" | "interface";
20
+ root: string;
21
+ theme: string;
22
+ title: string;
23
+ version: string;
24
+ space_id: string | null;
25
+ is_colab: boolean;
26
+ show_api: boolean;
27
+ stylesheets: string[];
28
+ path: string;
29
+ }
node_modules/@gradio/client/src/index.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export {
2
+ client,
3
+ post_data,
4
+ upload_files,
5
+ duplicate,
6
+ api_factory
7
+ } from "./client.js";
8
+ export type { SpaceStatus } from "./types.js";
9
+ export {
10
+ normalise_file,
11
+ FileData,
12
+ upload,
13
+ get_fetchable_url_or_file,
14
+ prepare_files
15
+ } from "./upload.js";
node_modules/@gradio/client/src/types.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface Config {
2
+ auth_required: boolean | undefined;
3
+ auth_message: string;
4
+ components: any[];
5
+ css: string | null;
6
+ js: string | null;
7
+ head: string | null;
8
+ dependencies: any[];
9
+ dev_mode: boolean;
10
+ enable_queue: boolean;
11
+ layout: any;
12
+ mode: "blocks" | "interface";
13
+ root: string;
14
+ root_url?: string;
15
+ theme: string;
16
+ title: string;
17
+ version: string;
18
+ space_id: string | null;
19
+ is_colab: boolean;
20
+ show_api: boolean;
21
+ stylesheets: string[];
22
+ path: string;
23
+ protocol?: "sse_v1" | "sse" | "ws";
24
+ }
25
+
26
+ export interface Payload {
27
+ data: unknown[];
28
+ fn_index?: number;
29
+ event_data?: unknown;
30
+ time?: Date;
31
+ }
32
+
33
+ export interface PostResponse {
34
+ error?: string;
35
+ [x: string]: any;
36
+ }
37
+ export interface UploadResponse {
38
+ error?: string;
39
+ files?: string[];
40
+ }
41
+
42
+ export interface Status {
43
+ queue: boolean;
44
+ code?: string;
45
+ success?: boolean;
46
+ stage: "pending" | "error" | "complete" | "generating";
47
+ broken?: boolean;
48
+ size?: number;
49
+ position?: number;
50
+ eta?: number;
51
+ message?: string;
52
+ progress_data?: {
53
+ progress: number | null;
54
+ index: number | null;
55
+ length: number | null;
56
+ unit: string | null;
57
+ desc: string | null;
58
+ }[];
59
+ time?: Date;
60
+ }
61
+
62
+ export interface LogMessage {
63
+ log: string;
64
+ level: "warning" | "info";
65
+ }
66
+
67
+ export interface SpaceStatusNormal {
68
+ status: "sleeping" | "running" | "building" | "error" | "stopped";
69
+ detail:
70
+ | "SLEEPING"
71
+ | "RUNNING"
72
+ | "RUNNING_BUILDING"
73
+ | "BUILDING"
74
+ | "NOT_FOUND";
75
+ load_status: "pending" | "error" | "complete" | "generating";
76
+ message: string;
77
+ }
78
+ export interface SpaceStatusError {
79
+ status: "space_error" | "paused";
80
+ detail:
81
+ | "NO_APP_FILE"
82
+ | "CONFIG_ERROR"
83
+ | "BUILD_ERROR"
84
+ | "RUNTIME_ERROR"
85
+ | "PAUSED";
86
+ load_status: "error";
87
+ message: string;
88
+ discussions_enabled: boolean;
89
+ }
90
+ export type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
91
+
92
+ export type status_callback_function = (a: Status) => void;
93
+ export type SpaceStatusCallback = (a: SpaceStatus) => void;
94
+
95
+ export type EventType = "data" | "status" | "log";
96
+
97
+ export interface EventMap {
98
+ data: Payload;
99
+ status: Status;
100
+ log: LogMessage;
101
+ }
102
+
103
+ export type Event<K extends EventType> = {
104
+ [P in K]: EventMap[P] & { type: P; endpoint: string; fn_index: number };
105
+ }[K];
106
+ export type EventListener<K extends EventType> = (event: Event<K>) => void;
107
+ export type ListenerMap<K extends EventType> = {
108
+ [P in K]?: EventListener<K>[];
109
+ };
110
+ export interface FileData {
111
+ name: string;
112
+ orig_name?: string;
113
+ size?: number;
114
+ data: string;
115
+ blob?: File;
116
+ is_file?: boolean;
117
+ mime_type?: string;
118
+ alt_text?: string;
119
+ }
node_modules/@gradio/client/src/upload.ts ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { upload_files } from "./client";
2
+
3
+ export function normalise_file(
4
+ file: FileData | null,
5
+ server_url: string,
6
+ proxy_url: string | null
7
+ ): FileData | null;
8
+
9
+ export function normalise_file(
10
+ file: FileData[] | null,
11
+ server_url: string,
12
+ proxy_url: string | null
13
+ ): FileData[] | null;
14
+
15
+ export function normalise_file(
16
+ file: FileData[] | FileData | null,
17
+ server_url: string, // root: string,
18
+ proxy_url: string | null // root_url: string | null
19
+ ): FileData[] | FileData | null;
20
+
21
+ export function normalise_file(
22
+ file: FileData[] | FileData | null,
23
+ server_url: string, // root: string,
24
+ proxy_url: string | null // root_url: string | null
25
+ ): FileData[] | FileData | null {
26
+ if (file == null) {
27
+ return null;
28
+ }
29
+
30
+ if (Array.isArray(file)) {
31
+ const normalized_file: (FileData | null)[] = [];
32
+
33
+ for (const x of file) {
34
+ if (x == null) {
35
+ normalized_file.push(null);
36
+ } else {
37
+ normalized_file.push(normalise_file(x, server_url, proxy_url));
38
+ }
39
+ }
40
+
41
+ return normalized_file as FileData[];
42
+ }
43
+
44
+ if (file.is_stream) {
45
+ if (proxy_url == null) {
46
+ return new FileData({
47
+ ...file,
48
+ url: server_url + "/stream/" + file.path
49
+ });
50
+ }
51
+ return new FileData({
52
+ ...file,
53
+ url: "/proxy=" + proxy_url + "stream/" + file.path
54
+ });
55
+ }
56
+
57
+ return new FileData({
58
+ ...file,
59
+ url: get_fetchable_url_or_file(file.path, server_url, proxy_url)
60
+ });
61
+ }
62
+
63
+ function is_url(str: string): boolean {
64
+ try {
65
+ const url = new URL(str);
66
+ return url.protocol === "http:" || url.protocol === "https:";
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ export function get_fetchable_url_or_file(
73
+ path: string | null,
74
+ server_url: string,
75
+ proxy_url: string | null
76
+ ): string {
77
+ if (path == null) {
78
+ return proxy_url ? `/proxy=${proxy_url}file=` : `${server_url}/file=`;
79
+ }
80
+ if (is_url(path)) {
81
+ return path;
82
+ }
83
+ return proxy_url
84
+ ? `/proxy=${proxy_url}file=${path}`
85
+ : `${server_url}/file=${path}`;
86
+ }
87
+
88
+ export async function upload(
89
+ file_data: FileData[],
90
+ root: string,
91
+ upload_id?: string,
92
+ upload_fn: typeof upload_files = upload_files
93
+ ): Promise<(FileData | null)[] | null> {
94
+ let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
95
+ (file_data) => file_data.blob!
96
+ );
97
+
98
+ return await Promise.all(
99
+ await upload_fn(root, files, undefined, upload_id).then(
100
+ async (response: { files?: string[]; error?: string }) => {
101
+ if (response.error) {
102
+ throw new Error(response.error);
103
+ } else {
104
+ if (response.files) {
105
+ return response.files.map((f, i) => {
106
+ const file = new FileData({ ...file_data[i], path: f });
107
+
108
+ return normalise_file(file, root, null);
109
+ });
110
+ }
111
+
112
+ return [];
113
+ }
114
+ }
115
+ )
116
+ );
117
+ }
118
+
119
+ export async function prepare_files(
120
+ files: File[],
121
+ is_stream?: boolean
122
+ ): Promise<FileData[]> {
123
+ return files.map(
124
+ (f, i) =>
125
+ new FileData({
126
+ path: f.name,
127
+ orig_name: f.name,
128
+ blob: f,
129
+ size: f.size,
130
+ mime_type: f.type,
131
+ is_stream
132
+ })
133
+ );
134
+ }
135
+
136
+ export class FileData {
137
+ path: string;
138
+ url?: string;
139
+ orig_name?: string;
140
+ size?: number;
141
+ blob?: File;
142
+ is_stream?: boolean;
143
+ mime_type?: string;
144
+ alt_text?: string;
145
+
146
+ constructor({
147
+ path,
148
+ url,
149
+ orig_name,
150
+ size,
151
+ blob,
152
+ is_stream,
153
+ mime_type,
154
+ alt_text
155
+ }: {
156
+ path: string;
157
+ url?: string;
158
+ orig_name?: string;
159
+ size?: number;
160
+ blob?: File;
161
+ is_stream?: boolean;
162
+ mime_type?: string;
163
+ alt_text?: string;
164
+ }) {
165
+ this.path = path;
166
+ this.url = url;
167
+ this.orig_name = orig_name;
168
+ this.size = size;
169
+ this.blob = url ? undefined : blob;
170
+ this.is_stream = is_stream;
171
+ this.mime_type = mime_type;
172
+ this.alt_text = alt_text;
173
+ }
174
+ }
node_modules/@gradio/client/src/utils.ts ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Config } from "./types.js";
2
+
3
+ /**
4
+ * This function is used to resolve the URL for making requests when the app has a root path.
5
+ * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or
6
+ * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting
7
+ * Gradio apps on Hugging Face Spaces.
8
+ * @param {string} base_url The base URL at which the Gradio server is hosted
9
+ * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces)
10
+ * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized.
11
+ * @returns {string} the resolved URL
12
+ */
13
+ export function resolve_root(
14
+ base_url: string,
15
+ root_path: string,
16
+ prioritize_base: boolean
17
+ ): string {
18
+ if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
19
+ return prioritize_base ? base_url : root_path;
20
+ }
21
+ return base_url + root_path;
22
+ }
23
+
24
+ export function determine_protocol(endpoint: string): {
25
+ ws_protocol: "ws" | "wss";
26
+ http_protocol: "http:" | "https:";
27
+ host: string;
28
+ } {
29
+ if (endpoint.startsWith("http")) {
30
+ const { protocol, host } = new URL(endpoint);
31
+
32
+ if (host.endsWith("hf.space")) {
33
+ return {
34
+ ws_protocol: "wss",
35
+ host: host,
36
+ http_protocol: protocol as "http:" | "https:"
37
+ };
38
+ }
39
+ return {
40
+ ws_protocol: protocol === "https:" ? "wss" : "ws",
41
+ http_protocol: protocol as "http:" | "https:",
42
+ host
43
+ };
44
+ } else if (endpoint.startsWith("file:")) {
45
+ // This case is only expected to be used for the Wasm mode (Gradio-lite),
46
+ // where users can create a local HTML file using it and open the page in a browser directly via the `file:` protocol.
47
+ return {
48
+ ws_protocol: "ws",
49
+ http_protocol: "http:",
50
+ host: "lite.local" // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`.
51
+ };
52
+ }
53
+
54
+ // default to secure if no protocol is provided
55
+ return {
56
+ ws_protocol: "wss",
57
+ http_protocol: "https:",
58
+ host: endpoint
59
+ };
60
+ }
61
+
62
+ export const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
63
+ export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
64
+ export async function process_endpoint(
65
+ app_reference: string,
66
+ token?: `hf_${string}`
67
+ ): Promise<{
68
+ space_id: string | false;
69
+ host: string;
70
+ ws_protocol: "ws" | "wss";
71
+ http_protocol: "http:" | "https:";
72
+ }> {
73
+ const headers: { Authorization?: string } = {};
74
+ if (token) {
75
+ headers.Authorization = `Bearer ${token}`;
76
+ }
77
+
78
+ const _app_reference = app_reference.trim();
79
+
80
+ if (RE_SPACE_NAME.test(_app_reference)) {
81
+ try {
82
+ const res = await fetch(
83
+ `https://huggingface.co/api/spaces/${_app_reference}/host`,
84
+ { headers }
85
+ );
86
+
87
+ if (res.status !== 200)
88
+ throw new Error("Space metadata could not be loaded.");
89
+ const _host = (await res.json()).host;
90
+
91
+ return {
92
+ space_id: app_reference,
93
+ ...determine_protocol(_host)
94
+ };
95
+ } catch (e: any) {
96
+ throw new Error("Space metadata could not be loaded." + e.message);
97
+ }
98
+ }
99
+
100
+ if (RE_SPACE_DOMAIN.test(_app_reference)) {
101
+ const { ws_protocol, http_protocol, host } =
102
+ determine_protocol(_app_reference);
103
+
104
+ return {
105
+ space_id: host.replace(".hf.space", ""),
106
+ ws_protocol,
107
+ http_protocol,
108
+ host
109
+ };
110
+ }
111
+
112
+ return {
113
+ space_id: false,
114
+ ...determine_protocol(_app_reference)
115
+ };
116
+ }
117
+
118
+ export function map_names_to_ids(
119
+ fns: Config["dependencies"]
120
+ ): Record<string, number> {
121
+ let apis: Record<string, number> = {};
122
+
123
+ fns.forEach(({ api_name }, i) => {
124
+ if (api_name) apis[api_name] = i;
125
+ });
126
+
127
+ return apis;
128
+ }
129
+
130
+ const RE_DISABLED_DISCUSSION =
131
+ /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
132
+ export async function discussions_enabled(space_id: string): Promise<boolean> {
133
+ try {
134
+ const r = await fetch(
135
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
136
+ {
137
+ method: "HEAD"
138
+ }
139
+ );
140
+ const error = r.headers.get("x-error-message");
141
+
142
+ if (error && RE_DISABLED_DISCUSSION.test(error)) return false;
143
+ return true;
144
+ } catch (e) {
145
+ return false;
146
+ }
147
+ }
148
+
149
+ export async function get_space_hardware(
150
+ space_id: string,
151
+ token: `hf_${string}`
152
+ ): Promise<(typeof hardware_types)[number]> {
153
+ const headers: { Authorization?: string } = {};
154
+ if (token) {
155
+ headers.Authorization = `Bearer ${token}`;
156
+ }
157
+
158
+ try {
159
+ const res = await fetch(
160
+ `https://huggingface.co/api/spaces/${space_id}/runtime`,
161
+ { headers }
162
+ );
163
+
164
+ if (res.status !== 200)
165
+ throw new Error("Space hardware could not be obtained.");
166
+
167
+ const { hardware } = await res.json();
168
+
169
+ return hardware;
170
+ } catch (e: any) {
171
+ throw new Error(e.message);
172
+ }
173
+ }
174
+
175
+ export async function set_space_hardware(
176
+ space_id: string,
177
+ new_hardware: (typeof hardware_types)[number],
178
+ token: `hf_${string}`
179
+ ): Promise<(typeof hardware_types)[number]> {
180
+ const headers: { Authorization?: string } = {};
181
+ if (token) {
182
+ headers.Authorization = `Bearer ${token}`;
183
+ }
184
+
185
+ try {
186
+ const res = await fetch(
187
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
188
+ { headers, body: JSON.stringify(new_hardware) }
189
+ );
190
+
191
+ if (res.status !== 200)
192
+ throw new Error(
193
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
194
+ );
195
+
196
+ const { hardware } = await res.json();
197
+
198
+ return hardware;
199
+ } catch (e: any) {
200
+ throw new Error(e.message);
201
+ }
202
+ }
203
+
204
+ export async function set_space_timeout(
205
+ space_id: string,
206
+ timeout: number,
207
+ token: `hf_${string}`
208
+ ): Promise<number> {
209
+ const headers: { Authorization?: string } = {};
210
+ if (token) {
211
+ headers.Authorization = `Bearer ${token}`;
212
+ }
213
+
214
+ try {
215
+ const res = await fetch(
216
+ `https://huggingface.co/api/spaces/${space_id}/hardware`,
217
+ { headers, body: JSON.stringify({ seconds: timeout }) }
218
+ );
219
+
220
+ if (res.status !== 200)
221
+ throw new Error(
222
+ "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
223
+ );
224
+
225
+ const { hardware } = await res.json();
226
+
227
+ return hardware;
228
+ } catch (e: any) {
229
+ throw new Error(e.message);
230
+ }
231
+ }
232
+
233
+ export const hardware_types = [
234
+ "cpu-basic",
235
+ "cpu-upgrade",
236
+ "t4-small",
237
+ "t4-medium",
238
+ "a10g-small",
239
+ "a10g-large",
240
+ "a100-large"
241
+ ] as const;
node_modules/@gradio/client/tsconfig.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "include": ["src/**/*"],
3
+ "exclude": ["src/**/*.test.ts", "src/**/*.node-test.ts"],
4
+ "compilerOptions": {
5
+ "allowJs": true,
6
+ "declaration": true,
7
+ "emitDeclarationOnly": true,
8
+ "outDir": "dist",
9
+ "declarationMap": true,
10
+ "module": "es2020",
11
+ "moduleResolution": "bundler",
12
+ "skipDefaultLibCheck": true
13
+ }
14
+ }
node_modules/@gradio/client/vite.config.js ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from "vite";
2
+ import { svelte } from "@sveltejs/vite-plugin-svelte";
3
+ import { fileURLToPath } from "url";
4
+ import path from "path";
5
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
6
+
7
+ export default defineConfig({
8
+ build: {
9
+ lib: {
10
+ entry: "src/index.ts",
11
+ formats: ["es"]
12
+ },
13
+ rollupOptions: {
14
+ input: "src/index.ts",
15
+ output: {
16
+ dir: "dist"
17
+ }
18
+ }
19
+ },
20
+ plugins: [
21
+ svelte()
22
+ // {
23
+ // name: "resolve-gradio-client",
24
+ // enforce: "pre",
25
+ // resolveId(id) {
26
+ // if (id === "@gradio/client") {
27
+ // return path.join(__dirname, "src", "index.ts");
28
+ // }
29
+ // }
30
+ // }
31
+ ],
32
+
33
+ ssr: {
34
+ target: "node",
35
+ format: "esm",
36
+ noExternal: ["ws", "semiver", "@gradio/upload"]
37
+ }
38
+ });