lsmpp commited on
Commit
60b32b8
·
verified ·
1 Parent(s): 12f3208

Serve the Gradio browser client locally so example runs do not depend on a CDN

Browse files
Files changed (3) hide show
  1. static/app.js +1 -1
  2. static/gradio-client.js +2319 -0
  3. static/index.html +1 -0
static/app.js CHANGED
@@ -179,7 +179,7 @@ document.addEventListener('keydown',event=>{if(/INPUT|TEXTAREA|SELECT/.test(even
179
  let gradioClient = null;
180
  async function submitGradio(sid, body) {
181
  if(!gradioClient){
182
- const {Client}=await import('https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js');
183
  gradioClient=await Client.connect(window.location.origin);
184
  }
185
  let result=null;
 
179
  let gradioClient = null;
180
  async function submitGradio(sid, body) {
181
  if(!gradioClient){
182
+ const {Client}=await import('/static/gradio-client.js');
183
  gradioClient=await Client.connect(window.location.origin);
184
  }
185
  let result=null;
static/gradio-client.js ADDED
@@ -0,0 +1,2319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*! @gradio/client 2.7.1
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ */
205
+ //#region \0rolldown/runtime.js
206
+ var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => {
207
+ if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
208
+ get: ((e) => i[e]).bind(null, d),
209
+ enumerable: !(s = n(i, d)) || s.enumerable
210
+ });
211
+ return e;
212
+ }, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", {
213
+ value: n,
214
+ enumerable: !0
215
+ }) : a, n)), l = "host", u = "queue/data", d = "queue/join", f = "upload", p = "login", m = "config", ee = "info", h = "runtime", g = "sleeptime", _ = "heartbeat", te = "component_server", ne = "reset", re = "cancel", ie = "app_id", ae = "This application is currently busy. Please try again. ", v = "Connection errored out. ", y = "Could not resolve app config. ", b = "Could not get space status. ", oe = "Could not get API info. ", x = "Space metadata could not be loaded. ", se = "Invalid URL. A full URL path is required.", S = "Not authorized to access this space. ", C = "Invalid credentials. Could not login. ", w = "Login credentials are required to access this space.", ce = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", T = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, le = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", ue = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", de = "File system access is only available in Node.js environments", fe = "Root URL not found in client config", pe = "Error uploading file";
216
+ //#endregion
217
+ //#region src/helpers/init_helpers.ts
218
+ async function me(e, t, n) {
219
+ try {
220
+ return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: {
221
+ Authorization: `Bearer ${t}`,
222
+ ...n ? { Cookie: n } : {}
223
+ } })).json()).token || !1;
224
+ } catch {
225
+ return !1;
226
+ }
227
+ }
228
+ function he(e) {
229
+ e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."));
230
+ }
231
+ function E(e) {
232
+ let t = {};
233
+ return e.forEach(({ api_name: e, id: n }) => {
234
+ e && (t[e] = n);
235
+ }), t;
236
+ }
237
+ function ge(e, t, n = !1) {
238
+ let r = new URL(t), i = new URL(e, r), a = i.hostname.endsWith(".colab-user-runtimes.internal") || i.hostname.endsWith(".codatalab-user-runtimes.internal");
239
+ return n || a ? new URL(new URL(e, r).pathname, r).toString().replace(/\/$/, "") : i.hostname === r.hostname ? (i.protocol = r.protocol, i.host = r.host, i.toString().replace(/\/$/, "")) : e;
240
+ }
241
+ async function D(e, t = !0) {
242
+ let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {};
243
+ if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") {
244
+ if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") {
245
+ let t = new URL(I(e, m));
246
+ this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page);
247
+ let r = await O(await this.fetch(t, {
248
+ headers: n,
249
+ credentials: this.options.credentials ?? "same-origin"
250
+ }), !!this.options.auth);
251
+ r.root = e || r.root, window.gradio_config = {
252
+ ...r,
253
+ current_page: window.gradio_config.current_page
254
+ };
255
+ }
256
+ let r = { ...window.gradio_config };
257
+ return r.root = ge(r.root, location.href, r.is_colab), r;
258
+ } else if (e) {
259
+ let t = new URL(I(e, m));
260
+ this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page);
261
+ let r = await O(await this.fetch(t, {
262
+ headers: n,
263
+ credentials: this.options.credentials ?? "same-origin"
264
+ }), !!this.options.auth);
265
+ return r.root ||= e, r;
266
+ }
267
+ throw Error(y);
268
+ }
269
+ async function O(e, t) {
270
+ if (e?.status === 401 && !t) {
271
+ let t = null;
272
+ try {
273
+ t = await e.json();
274
+ } catch {
275
+ throw Error(ce);
276
+ }
277
+ let n = t?.detail?.auth_message;
278
+ throw Error(n || "Login credentials are required to access this space.");
279
+ } else if (e?.status === 401 && t) throw Error(C);
280
+ if (e?.status === 200) {
281
+ let t = await e.json();
282
+ return t.dependencies?.forEach((e, t) => {
283
+ e.id === void 0 && (e.id = t);
284
+ }), t;
285
+ } else if (e?.status === 401) throw Error(S);
286
+ throw Error(`${y}(received status ${e?.status} when fetching the app config)`);
287
+ }
288
+ async function k() {
289
+ let { http_protocol: e, host: t } = await F(this.app_reference, this.options.token);
290
+ try {
291
+ if (this.options.auth) {
292
+ let n = await A(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials);
293
+ n && this.set_cookies(n);
294
+ }
295
+ } catch (e) {
296
+ throw Error(e.message);
297
+ }
298
+ }
299
+ async function A(e, t, n, r, i, a) {
300
+ let o = new FormData();
301
+ o.append("username", n?.[0]), o.append("password", n?.[1]);
302
+ let s = {};
303
+ i && (s.Authorization = `Bearer ${i}`);
304
+ let c = await r(`${e}//${t}/${p}`, {
305
+ headers: s,
306
+ method: "POST",
307
+ body: o,
308
+ credentials: a ?? "same-origin"
309
+ });
310
+ if (c.status === 200) return c.headers.get("set-cookie");
311
+ throw c.status === 401 ? Error(C) : Error(x);
312
+ }
313
+ function j(e) {
314
+ if (e.startsWith("http")) {
315
+ let { protocol: t, host: n, pathname: r } = new URL(e);
316
+ return {
317
+ ws_protocol: t === "https:" ? "wss" : "ws",
318
+ http_protocol: t,
319
+ host: n + (r === "/" ? "" : r)
320
+ };
321
+ }
322
+ return {
323
+ ws_protocol: "wss",
324
+ http_protocol: "https:",
325
+ host: new URL(e).host
326
+ };
327
+ }
328
+ var M = (e) => {
329
+ let t = [];
330
+ return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => {
331
+ let [n, r] = e.split(";")[0].split("=");
332
+ n && r && t.push(`${n.trim()}=${r.trim()}`);
333
+ }), t;
334
+ }, N = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, P = /.*hf\.space\/{0,1}.*$/;
335
+ async function F(e, t) {
336
+ let n = {};
337
+ t && (n.Authorization = `Bearer ${t}`);
338
+ let r = e.trim().replace(/\/$/, "");
339
+ if (N.test(r)) {
340
+ let e;
341
+ try {
342
+ e = await fetch(`https://huggingface.co/api/spaces/${r}/${l}`, { headers: n });
343
+ } catch {
344
+ throw Error(x);
345
+ }
346
+ if (e.status === 401 || e.status === 404) throw Error(T(r, e.status));
347
+ let t;
348
+ try {
349
+ t = (await e.json()).host;
350
+ } catch {
351
+ throw Error(x);
352
+ }
353
+ if (!t) throw Error(x);
354
+ return {
355
+ space_id: r,
356
+ ...j(t)
357
+ };
358
+ }
359
+ if (P.test(r)) {
360
+ let { ws_protocol: e, http_protocol: t, host: n } = j(r);
361
+ return {
362
+ space_id: n.split("/")[0].replace(".hf.space", ""),
363
+ ws_protocol: e,
364
+ http_protocol: t,
365
+ host: n
366
+ };
367
+ }
368
+ return {
369
+ space_id: !1,
370
+ ...j(r)
371
+ };
372
+ }
373
+ var I = (...e) => {
374
+ try {
375
+ return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString()));
376
+ } catch {
377
+ throw Error(se);
378
+ }
379
+ };
380
+ function _e(e, t, n) {
381
+ let r = {
382
+ named_endpoints: {},
383
+ unnamed_endpoints: {}
384
+ };
385
+ return Object.keys(e).forEach((i) => {
386
+ (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => {
387
+ let o = a?.parameters ?? [], s = a?.returns ?? [], c = t.dependencies.find((t) => t.api_name === e || t.api_name === e.replace("/", ""))?.id || n[e.replace("/", "")] || -1, l = c === -1 ? void 0 : t.dependencies.find((e) => e.id == c), u = c === -1 ? {
388
+ generator: !1,
389
+ cancel: !1
390
+ } : l?.types;
391
+ if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) {
392
+ let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type);
393
+ try {
394
+ e.forEach((e, t) => {
395
+ e === "state" && o.splice(t, 0, {
396
+ component: "state",
397
+ example: null,
398
+ parameter_default: null,
399
+ parameter_has_default: !0,
400
+ parameter_name: null,
401
+ hidden: !0
402
+ });
403
+ });
404
+ } catch (e) {
405
+ console.error(e);
406
+ }
407
+ }
408
+ let d = (e, t, n, r) => ({
409
+ ...e,
410
+ description: ve(e?.type, n),
411
+ type: L(e?.type, t, n, r) || ""
412
+ });
413
+ r[i][e] = {
414
+ parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")),
415
+ returns: s.map((e) => d(e, e?.component, e?.serializer, "return")),
416
+ type: u,
417
+ ...a?.oauth_token ? { oauth_token: a.oauth_token } : {}
418
+ };
419
+ }));
420
+ }), r;
421
+ }
422
+ function L(e, t, n, r) {
423
+ if (t === "Api") return e.type;
424
+ switch (e?.type) {
425
+ case "string": return "string";
426
+ case "boolean": return "boolean";
427
+ case "number": return "number";
428
+ }
429
+ if (n === "JSONSerializable" || n === "StringSerializable") return "any";
430
+ if (n === "ListStringSerializable") return "string[]";
431
+ if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string";
432
+ if (n === "FileSerializable") return e?.type === "array" ? r === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : r === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";
433
+ if (n === "GallerySerializable") return r === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]";
434
+ }
435
+ function ve(e, t) {
436
+ return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description;
437
+ }
438
+ function ye(e, t) {
439
+ switch (e.msg) {
440
+ case "send_data": return { type: "data" };
441
+ case "send_hash": return { type: "hash" };
442
+ case "queue_full": return {
443
+ type: "update",
444
+ status: {
445
+ queue: !0,
446
+ message: ae,
447
+ stage: "error",
448
+ code: e.code,
449
+ success: e.success
450
+ }
451
+ };
452
+ case "heartbeat": return { type: "heartbeat" };
453
+ case "unexpected_error": return {
454
+ type: "unexpected_error",
455
+ status: {
456
+ queue: !0,
457
+ message: e.message,
458
+ session_not_found: e.session_not_found,
459
+ stage: "error",
460
+ success: !1
461
+ }
462
+ };
463
+ case "broken_connection": return {
464
+ type: "broken_connection",
465
+ status: {
466
+ queue: !0,
467
+ message: e.message,
468
+ stage: "error",
469
+ success: !1
470
+ }
471
+ };
472
+ case "estimation": return {
473
+ type: "update",
474
+ status: {
475
+ queue: !0,
476
+ stage: t || "pending",
477
+ code: e.code,
478
+ size: e.queue_size,
479
+ position: e.rank,
480
+ eta: e.rank_eta,
481
+ success: e.success
482
+ }
483
+ };
484
+ case "progress": return {
485
+ type: "update",
486
+ status: {
487
+ queue: !0,
488
+ stage: "pending",
489
+ code: e.code,
490
+ progress_data: e.progress_data,
491
+ success: e.success
492
+ }
493
+ };
494
+ case "log": return {
495
+ type: "log",
496
+ data: e
497
+ };
498
+ case "process_generating": return {
499
+ type: "generating",
500
+ status: {
501
+ queue: !0,
502
+ message: e.success ? null : e.output.error,
503
+ stage: e.success ? "generating" : "error",
504
+ code: e.code,
505
+ progress_data: e.progress_data,
506
+ eta: e.average_duration,
507
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0
508
+ },
509
+ data: e.success ? e.output : null
510
+ };
511
+ case "process_streaming": return {
512
+ type: "streaming",
513
+ status: {
514
+ queue: !0,
515
+ message: e.output.error,
516
+ stage: "streaming",
517
+ time_limit: e.time_limit,
518
+ code: e.code,
519
+ progress_data: e.progress_data,
520
+ changed_state_ids: e.output.changed_state_ids,
521
+ eta: e.eta
522
+ },
523
+ data: e.output
524
+ };
525
+ case "process_completed": return "error" in e.output ? {
526
+ type: "update",
527
+ status: {
528
+ queue: !0,
529
+ title: e.output.title ?? "Error",
530
+ message: e.output.error ?? "An error occurred",
531
+ visible: e.output.visible,
532
+ duration: e.output.duration,
533
+ stage: "error",
534
+ code: e.code,
535
+ success: e.success
536
+ }
537
+ } : {
538
+ type: "complete",
539
+ status: {
540
+ queue: !0,
541
+ message: e.success ? void 0 : e.output.error,
542
+ stage: e.success ? "complete" : "error",
543
+ code: e.code,
544
+ progress_data: e.progress_data,
545
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0,
546
+ used_cache: e.used_cache,
547
+ cache_duration: e.cache_duration,
548
+ avg_time: e.avg_time
549
+ },
550
+ data: e.success ? e.output : null
551
+ };
552
+ case "process_starts": return {
553
+ type: "update",
554
+ status: {
555
+ queue: !0,
556
+ stage: "pending",
557
+ code: e.code,
558
+ size: e.rank,
559
+ position: 0,
560
+ success: e.success,
561
+ eta: e.eta
562
+ },
563
+ original_msg: "process_starts"
564
+ };
565
+ }
566
+ return {
567
+ type: "none",
568
+ status: {
569
+ stage: "error",
570
+ queue: !0
571
+ }
572
+ };
573
+ }
574
+ var be = (e = [], t) => {
575
+ let n = t ? t.parameters : [];
576
+ if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e;
577
+ let r = [], i = Object.keys(e);
578
+ return n.forEach((t, n) => {
579
+ if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name];
580
+ else if (t.parameter_has_default) r[n] = t.parameter_default;
581
+ else throw Error(`No value provided for required parameter: ${t.parameter_name}`);
582
+ }), i.forEach((e) => {
583
+ if (!n.some((t) => t.parameter_name === e)) throw Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`);
584
+ }), r.forEach((e, t) => {
585
+ if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`);
586
+ }), r;
587
+ };
588
+ //#endregion
589
+ //#region src/utils/view_api.ts
590
+ async function xe() {
591
+ if (this.api_info) return this.api_info;
592
+ let { token: e } = this.options, { config: t } = this, n = {};
593
+ if (e && (n.Authorization = `Bearer ${e}`), t) try {
594
+ let e, r;
595
+ if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info;
596
+ else {
597
+ let i = new URL(I(t.root, this.api_prefix, ee));
598
+ if (this.page !== null && i.searchParams.set("page", this.page), e = await this.fetch(i, {
599
+ headers: n,
600
+ credentials: this.options.credentials ?? "same-origin"
601
+ }), !e.ok) throw Error(v);
602
+ r = await e.json();
603
+ }
604
+ return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), _e(r, t, this.api_map);
605
+ } catch (e) {
606
+ throw Error("Could not get API info. " + e.message);
607
+ }
608
+ }
609
+ //#endregion
610
+ //#region src/utils/upload_files.ts
611
+ async function Se(e, t, n) {
612
+ let r = {};
613
+ this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`);
614
+ let i = 1e3, a = [], o;
615
+ for (let s = 0; s < t.length; s += i) {
616
+ let c = t.slice(s, s + i), l = new FormData();
617
+ c.forEach((e) => {
618
+ l.append("files", e);
619
+ });
620
+ try {
621
+ let t = n ? `${e}${this.api_prefix}/${f}?upload_id=${n}` : `${e}${this.api_prefix}/${f}`;
622
+ o = await this.fetch(t, {
623
+ method: "POST",
624
+ body: l,
625
+ headers: r,
626
+ credentials: this.options.credentials ?? "same-origin"
627
+ });
628
+ } catch (e) {
629
+ throw Error(v + e.message);
630
+ }
631
+ if (!o.ok) {
632
+ let e = await o.text();
633
+ return { error: `HTTP ${o.status}: ${e}` };
634
+ }
635
+ let u = await o.json();
636
+ u && a.push(...u);
637
+ }
638
+ return { files: a };
639
+ }
640
+ var R = {
641
+ si: {
642
+ radix: 1e3,
643
+ unit: [
644
+ "b",
645
+ "kb",
646
+ "Mb",
647
+ "Gb",
648
+ "Tb",
649
+ "Pb",
650
+ "Eb",
651
+ "Zb",
652
+ "Yb"
653
+ ]
654
+ },
655
+ iec: {
656
+ radix: 1024,
657
+ unit: [
658
+ "b",
659
+ "Kib",
660
+ "Mib",
661
+ "Gib",
662
+ "Tib",
663
+ "Pib",
664
+ "Eib",
665
+ "Zib",
666
+ "Yib"
667
+ ]
668
+ },
669
+ jedec: {
670
+ radix: 1024,
671
+ unit: [
672
+ "b",
673
+ "Kb",
674
+ "Mb",
675
+ "Gb",
676
+ "Tb",
677
+ "Pb",
678
+ "Eb",
679
+ "Zb",
680
+ "Yb"
681
+ ]
682
+ }
683
+ };
684
+ function Ce(e, t = 1, n = "jedec") {
685
+ e = Math.abs(e);
686
+ let { radix: r, unit: i } = R[n] || R.jedec, a = 0;
687
+ for (; e >= r;) e /= r, ++a;
688
+ return `${e.toFixed(t)} ${i[a]}`;
689
+ }
690
+ //#endregion
691
+ //#region src/upload.ts
692
+ async function z(e, t, n, r) {
693
+ let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity));
694
+ if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${Ce(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`);
695
+ return await Promise.all(await this.upload_files(t, i, n).then(async (n) => {
696
+ if (n.error) throw Error(n.error);
697
+ return n.files ? n.files.map((n, r) => {
698
+ let i = n.split("/").map((e) => encodeURIComponent(e)).join("/");
699
+ return new V({
700
+ ...e[r],
701
+ path: n,
702
+ url: `${t}${this.api_prefix}/file=${i}`
703
+ });
704
+ }) : [];
705
+ }));
706
+ }
707
+ async function B(e, t) {
708
+ return e.map((e) => new V({
709
+ path: e.name,
710
+ orig_name: e.name,
711
+ blob: e,
712
+ size: e.size,
713
+ mime_type: e.type,
714
+ is_stream: t
715
+ }));
716
+ }
717
+ var V = class {
718
+ path;
719
+ url;
720
+ orig_name;
721
+ size;
722
+ blob;
723
+ is_stream;
724
+ mime_type;
725
+ alt_text;
726
+ b64;
727
+ meta = { _type: "gradio.FileData" };
728
+ constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) {
729
+ this.path = e, this.url = t, this.orig_name = n, this.size = r, this.blob = t ? void 0 : i, this.is_stream = a, this.mime_type = o, this.alt_text = s, this.b64 = c;
730
+ }
731
+ }, H = class {
732
+ type;
733
+ command;
734
+ meta;
735
+ fileData;
736
+ constructor(e, t) {
737
+ this.type = "command", this.command = e, this.meta = t;
738
+ }
739
+ }, we = typeof process < "u" && process.versions && process.versions.node;
740
+ function Te(e, t, n) {
741
+ for (; n.length > 1;) {
742
+ let t = n.shift();
743
+ if (typeof t == "string" || typeof t == "number") e = e[t];
744
+ else throw Error("Invalid key type");
745
+ }
746
+ let r = n.shift();
747
+ if (typeof r == "string" || typeof r == "number") e[r] = t;
748
+ else throw Error("Invalid key type");
749
+ }
750
+ async function U(e, t = void 0, n = [], r = !1, i = void 0) {
751
+ if (Array.isArray(e)) {
752
+ let a = [];
753
+ return await Promise.all(e.map(async (o, s) => {
754
+ let c = n.slice();
755
+ c.push(String(s));
756
+ let l = await U(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i);
757
+ a = a.concat(l);
758
+ })), a;
759
+ } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{
760
+ path: n,
761
+ blob: e instanceof Blob ? e : new Blob([e]),
762
+ type: t
763
+ }];
764
+ else if (typeof e == "object" && e) {
765
+ let t = [];
766
+ for (let r of Object.keys(e)) {
767
+ let a = [...n, r], o = e[r];
768
+ t = t.concat(await U(o, void 0, a, !1, i));
769
+ }
770
+ return t;
771
+ }
772
+ return [];
773
+ }
774
+ function Ee(e, t) {
775
+ let n = t?.dependencies?.find((t) => t.id == e)?.queue;
776
+ return n == null ? !t.enable_queue : !n;
777
+ }
778
+ function De(e, t) {
779
+ return new Promise((n, r) => {
780
+ let i = new MessageChannel();
781
+ i.port1.onmessage = (({ data: e }) => {
782
+ i.port1.close(), n(e);
783
+ }), window.parent.postMessage(e, t, [i.port2]);
784
+ });
785
+ }
786
+ function Oe(e) {
787
+ if (typeof e == "string") {
788
+ if (e.startsWith("http://") || e.startsWith("https://")) return {
789
+ path: e,
790
+ url: e,
791
+ orig_name: e.split("/").pop() ?? "unknown",
792
+ meta: { _type: "gradio.FileData" }
793
+ };
794
+ if (we) return new H("upload_file", {
795
+ path: e,
796
+ name: e,
797
+ orig_path: e
798
+ });
799
+ } else if (typeof File < "u" && e instanceof File) return e;
800
+ else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]);
801
+ else if (e instanceof Blob) return e;
802
+ throw Error("Invalid input: must be a URL, File, Blob, or Buffer object.");
803
+ }
804
+ function W(e, t, n, r, i = !1) {
805
+ if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input.");
806
+ if (r === "output" && i) return e;
807
+ let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs;
808
+ for (let t = 0; t < s.length; t++) {
809
+ let r = s[t];
810
+ if (n.find((e) => e.id === r)?.type === "state") {
811
+ if (i) if (e.length === s.length) {
812
+ let t = e[o];
813
+ a.push(t), o++;
814
+ } else a.push(null);
815
+ else {
816
+ o++;
817
+ continue;
818
+ }
819
+ continue;
820
+ } else {
821
+ let t = e[o];
822
+ a.push(t), o++;
823
+ }
824
+ }
825
+ return a;
826
+ }
827
+ var ke = [
828
+ "/file=",
829
+ "/file/",
830
+ "/stream/",
831
+ "/proxy="
832
+ ];
833
+ function Ae(e, t, n, r) {
834
+ if (!r || typeof e != "object" || !e) return;
835
+ let i = r, a = new URL(t), o = a.pathname.replace(/\/+$/, ""), s = n ? `/${n.replace(/^\/+|\/+$/g, "")}` : "", c = new Set([`${o}${s}`, s]);
836
+ s || (c.add(`${o}/gradio_api`), c.add("/gradio_api"));
837
+ function l(e) {
838
+ if (typeof e != "object" || !e) return;
839
+ let t = e;
840
+ if (t.meta?._type === "gradio.FileData" && typeof t.url == "string") {
841
+ let e = new URL(t.url, `${a.toString().replace(/\/$/, "")}/`), n = [...c].some((t) => ke.some((n) => e.pathname.startsWith(`${t}${n}`)));
842
+ (e.protocol === "http:" || e.protocol === "https:") && e.origin === a.origin && n && (e.searchParams.set("__sign", i), t.url = e.toString());
843
+ }
844
+ for (let e of Object.values(t)) l(e);
845
+ }
846
+ l(e);
847
+ }
848
+ function je(e, t) {
849
+ for (let n of e.components || []) Ae(n.props?.value, e.root, e.api_prefix || "", t);
850
+ }
851
+ //#endregion
852
+ //#region __vite-browser-external
853
+ var Me = /* @__PURE__ */ o(((e, t) => {
854
+ t.exports = {};
855
+ }));
856
+ //#endregion
857
+ //#region src/utils/handle_blob.ts
858
+ async function Ne(e, t, n) {
859
+ let r = this;
860
+ await Pe(r, t);
861
+ let i = await U(t, void 0, [], !0, n);
862
+ return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => {
863
+ if (!n) return {
864
+ path: t,
865
+ type: i
866
+ };
867
+ let a = await r.upload_files(e, [n]);
868
+ return {
869
+ path: t,
870
+ file_url: a.files && a.files[0],
871
+ type: i,
872
+ name: typeof File < "u" && n instanceof File ? n?.name : void 0
873
+ };
874
+ }))).forEach(({ path: e, file_url: n, type: r, name: i }) => {
875
+ r === "Gallery" ? Te(t, n, e) : n && Te(t, new V({
876
+ path: n,
877
+ orig_name: i
878
+ }), e);
879
+ }), t;
880
+ }
881
+ async function Pe(e, t) {
882
+ if (!(e.config?.root || e.config?.root_url)) throw Error(fe);
883
+ await Fe(e, t);
884
+ }
885
+ async function Fe(e, t, n = []) {
886
+ for (let r in t) t[r] instanceof H ? await Ie(e, t, r) : typeof t[r] == "object" && t[r] !== null && await Fe(e, t[r], [...n, r]);
887
+ }
888
+ async function Ie(e, t, n) {
889
+ let r = t[n], i = e.config?.root || e.config?.root_url;
890
+ if (!i) throw Error(fe);
891
+ try {
892
+ let a, o;
893
+ if (typeof process < "u" && process.versions && process.versions.node) {
894
+ let e = await Promise.resolve().then(() => /* @__PURE__ */ c(Me(), 1));
895
+ o = (await Promise.resolve().then(() => /* @__PURE__ */ c(Me(), 1))).resolve(process.cwd(), r.meta.path), a = await e.readFile(o);
896
+ } else throw Error(de);
897
+ let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0];
898
+ u && (t[n] = new V({
899
+ path: u,
900
+ orig_name: r.meta.name || ""
901
+ }));
902
+ } catch (e) {
903
+ console.error(pe, e);
904
+ }
905
+ }
906
+ //#endregion
907
+ //#region src/utils/post_data.ts
908
+ async function Le(e, t, n) {
909
+ let r = { "Content-Type": "application/json" };
910
+ this.options.token && (r.Authorization = `Bearer ${this.options.token}`);
911
+ try {
912
+ var i = await this.fetch(e, {
913
+ method: "POST",
914
+ body: JSON.stringify(t),
915
+ headers: {
916
+ ...r,
917
+ ...n
918
+ },
919
+ credentials: this.options.credentials ?? "same-origin"
920
+ });
921
+ } catch {
922
+ return [{ error: v }, 500];
923
+ }
924
+ let a, o;
925
+ try {
926
+ a = await i.json(), o = i.status;
927
+ } catch (e) {
928
+ a = { error: `Could not parse server response: ${e}` }, o = 500;
929
+ }
930
+ return [a, o];
931
+ }
932
+ //#endregion
933
+ //#region src/utils/predict.ts
934
+ async function Re(e, t = {}) {
935
+ let n = !1, r = !1;
936
+ if (!this.config) throw Error("Could not resolve app config");
937
+ if (typeof e == "number") this.config.dependencies.find((t) => t.id == e);
938
+ else {
939
+ let t = e.replace(/^\//, "");
940
+ this.config.dependencies.find((e) => e.id == this.api_map[t]);
941
+ }
942
+ let i = this.submit(e, t, null, null, !0), a;
943
+ for await (let e of i) {
944
+ if (e.type === "data" && (n = !0, a = e, r)) return a;
945
+ if (e.type === "status") {
946
+ if (e.stage === "error") {
947
+ let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction.");
948
+ throw Object.assign(r, n), r;
949
+ }
950
+ if (e.stage === "complete" && (r = !0, n)) return a;
951
+ }
952
+ }
953
+ return a;
954
+ }
955
+ //#endregion
956
+ //#region src/helpers/spaces.ts
957
+ async function G(e, t, n) {
958
+ let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a;
959
+ try {
960
+ if (i = await fetch(r), a = i.status, a !== 200) throw Error();
961
+ i = await i.json();
962
+ } catch {
963
+ n({
964
+ status: "error",
965
+ load_status: "error",
966
+ message: b,
967
+ detail: "NOT_FOUND"
968
+ });
969
+ return;
970
+ }
971
+ if (!i || a !== 200) return;
972
+ let { runtime: { stage: o }, id: s } = i;
973
+ switch (o) {
974
+ case "STOPPED":
975
+ case "SLEEPING":
976
+ n({
977
+ status: "sleeping",
978
+ load_status: "pending",
979
+ message: "Space is asleep. Waking it up...",
980
+ detail: o
981
+ }), setTimeout(() => {
982
+ G(e, t, n);
983
+ }, 1e3);
984
+ break;
985
+ case "PAUSED":
986
+ n({
987
+ status: "paused",
988
+ load_status: "error",
989
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
990
+ detail: o,
991
+ discussions_enabled: await Ve(s)
992
+ });
993
+ break;
994
+ case "RUNNING":
995
+ case "RUNNING_BUILDING":
996
+ n({
997
+ status: "running",
998
+ load_status: "complete",
999
+ message: "Space is running.",
1000
+ detail: o
1001
+ });
1002
+ break;
1003
+ case "BUILDING":
1004
+ n({
1005
+ status: "building",
1006
+ load_status: "pending",
1007
+ message: "Space is building...",
1008
+ detail: o
1009
+ }), setTimeout(() => {
1010
+ G(e, t, n);
1011
+ }, 1e3);
1012
+ break;
1013
+ case "APP_STARTING":
1014
+ n({
1015
+ status: "starting",
1016
+ load_status: "pending",
1017
+ message: "Space is starting...",
1018
+ detail: o
1019
+ }), setTimeout(() => {
1020
+ G(e, t, n);
1021
+ }, 1e3);
1022
+ break;
1023
+ default:
1024
+ n({
1025
+ status: "space_error",
1026
+ load_status: "error",
1027
+ message: "This space is experiencing an issue.",
1028
+ detail: o,
1029
+ discussions_enabled: await Ve(s)
1030
+ });
1031
+ break;
1032
+ }
1033
+ }
1034
+ var ze = async (e, t) => {
1035
+ let n = 0;
1036
+ return new Promise((r) => {
1037
+ G(e, N.test(e) ? "space_name" : "subdomain", (i) => {
1038
+ t(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (n < 12 ? (n++, setTimeout(() => {
1039
+ ze(e, t).then(r);
1040
+ }, 5e3)) : r());
1041
+ });
1042
+ });
1043
+ }, Be = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
1044
+ async function Ve(e) {
1045
+ try {
1046
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message");
1047
+ return !(!t.ok || n && Be.test(n));
1048
+ } catch {
1049
+ return !1;
1050
+ }
1051
+ }
1052
+ async function He(e, t) {
1053
+ let n = {};
1054
+ t && (n.Authorization = `Bearer ${t}`);
1055
+ try {
1056
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/${h}`, { headers: n });
1057
+ if (t.status !== 200) throw Error("Space hardware could not be obtained.");
1058
+ let { hardware: r } = await t.json();
1059
+ return r.current;
1060
+ } catch (e) {
1061
+ throw Error(e.message);
1062
+ }
1063
+ }
1064
+ async function Ue(e, t, n) {
1065
+ let r = {};
1066
+ n && (r.Authorization = `Bearer ${n}`);
1067
+ let i = { seconds: t };
1068
+ try {
1069
+ let t = await fetch(`https://huggingface.co/api/spaces/${e}/${g}`, {
1070
+ method: "POST",
1071
+ headers: {
1072
+ "Content-Type": "application/json",
1073
+ ...r
1074
+ },
1075
+ body: JSON.stringify(i)
1076
+ });
1077
+ if (t.status !== 200) throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges.");
1078
+ return await t.json();
1079
+ } catch (e) {
1080
+ throw Error(e.message);
1081
+ }
1082
+ }
1083
+ var We = [
1084
+ "cpu-basic",
1085
+ "cpu-upgrade",
1086
+ "cpu-xl",
1087
+ "t4-small",
1088
+ "t4-medium",
1089
+ "a10g-small",
1090
+ "a10g-large",
1091
+ "a10g-largex2",
1092
+ "a10g-largex4",
1093
+ "a100-large",
1094
+ "zero-a10g",
1095
+ "h100",
1096
+ "h100x8"
1097
+ ];
1098
+ //#endregion
1099
+ //#region src/utils/duplicate.ts
1100
+ async function Ge(e, t) {
1101
+ he(t);
1102
+ let { token: n, private: r, hardware: i, timeout: a, auth: o } = t;
1103
+ if (i && !We.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${We.map((e) => `"${e}"`).join(",")}.`);
1104
+ let { http_protocol: s, host: c } = await F(e, n), l = null;
1105
+ if (o) {
1106
+ let e = await A(s, c, o, fetch, void 0, t.credentials);
1107
+ e && (l = M(e));
1108
+ }
1109
+ let u = {
1110
+ Authorization: `Bearer ${n}`,
1111
+ "Content-Type": "application/json",
1112
+ ...l ? { Cookie: l.join("; ") } : {}
1113
+ }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` };
1114
+ r && (p.private = !0);
1115
+ let m;
1116
+ try {
1117
+ i || (m = await He(e, n));
1118
+ } catch (e) {
1119
+ throw Error(x + e.message);
1120
+ }
1121
+ p.hardware = i || m || "cpu-basic";
1122
+ try {
1123
+ let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, {
1124
+ method: "POST",
1125
+ headers: u,
1126
+ body: JSON.stringify(p)
1127
+ });
1128
+ if (r.status === 409) try {
1129
+ return await $.connect(`${d}/${f}`, t);
1130
+ } catch (e) {
1131
+ throw console.error("Failed to connect Client instance:", e), e;
1132
+ }
1133
+ else if (r.status !== 200) throw Error(r.statusText);
1134
+ let i = await r.json();
1135
+ return await Ue(`${d}/${f}`, a || 300, n), await $.connect(Ke(i.url), t);
1136
+ } catch (e) {
1137
+ throw Error(e);
1138
+ }
1139
+ }
1140
+ function Ke(e) {
1141
+ let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/);
1142
+ if (t) return t[1];
1143
+ }
1144
+ //#endregion
1145
+ //#region src/helpers/zerogpu.ts
1146
+ var qe = "supports-zerogpu-headers", Je = !1;
1147
+ function Ye() {
1148
+ return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function";
1149
+ }
1150
+ function Xe(e) {
1151
+ return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null;
1152
+ }
1153
+ function Ze() {
1154
+ if (!Ye() || Je) return;
1155
+ window.addEventListener("message", (e) => {
1156
+ e.data === qe && (window.supports_zerogpu_headers = !0);
1157
+ }), Je = !0;
1158
+ let e = Xe(window.location.hostname);
1159
+ e && window.parent !== window && window.parent.postMessage(qe, e);
1160
+ }
1161
+ //#endregion
1162
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/deps/jsr.io/@std/streams/0.221.0/text_line_stream.js
1163
+ var Qe = class extends TransformStream {
1164
+ #e = "";
1165
+ constructor(e = { allowCR: !1 }) {
1166
+ super({
1167
+ transform: (t, n) => {
1168
+ for (t = this.#e + t;;) {
1169
+ let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1;
1170
+ if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) {
1171
+ n.enqueue(t.slice(0, i)), t = t.slice(i + 1);
1172
+ continue;
1173
+ }
1174
+ if (r === -1) break;
1175
+ let a = t[r - 1] === "\r" ? r - 1 : r;
1176
+ n.enqueue(t.slice(0, a)), t = t.slice(r + 1);
1177
+ }
1178
+ this.#e = t;
1179
+ },
1180
+ flush: (t) => {
1181
+ if (this.#e === "") return;
1182
+ let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e;
1183
+ t.enqueue(n);
1184
+ }
1185
+ });
1186
+ }
1187
+ };
1188
+ //#endregion
1189
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.js
1190
+ function $e(e) {
1191
+ let t = new TextDecoderStream(), n = new Qe({ allowCR: !0 });
1192
+ return e.pipeThrough(t).pipeThrough(n);
1193
+ }
1194
+ function et(e) {
1195
+ let t = /[:]\s*/.exec(e), n = t && t.index;
1196
+ if (n) return [e.substring(0, n), e.substring(n + t[0].length)];
1197
+ }
1198
+ function tt(e, t, n) {
1199
+ e.get(t) || e.set(t, n);
1200
+ }
1201
+ //#endregion
1202
+ //#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.js
1203
+ async function* nt(e, t) {
1204
+ if (!e.body) return;
1205
+ let n = $e(e.body), r, i = n.getReader(), a;
1206
+ for (;;) {
1207
+ if (t && t.aborted) return i.cancel();
1208
+ if (r = await i.read(), r.done) return;
1209
+ if (!r.value) {
1210
+ a && (yield a), a = void 0;
1211
+ continue;
1212
+ }
1213
+ let [e, n] = et(r.value) || [];
1214
+ e === "data" ? (a ||= {}, a[e] = a[e] ? a[e] + "\n" + n : n) : e === "event" ? (a ||= {}, a[e] = n) : e === "id" ? (a ||= {}, a[e] = String(+n) === n ? +n : n) : e === "retry" && (a ||= {}, a[e] = +n || void 0);
1215
+ }
1216
+ }
1217
+ async function rt(e, t) {
1218
+ let n = new Request(e, t);
1219
+ tt(n.headers, "Accept", "text/event-stream"), tt(n.headers, "Content-Type", "application/json");
1220
+ let r = await fetch(n);
1221
+ if (!r.ok) throw r;
1222
+ return nt(r, n.signal);
1223
+ }
1224
+ //#endregion
1225
+ //#region src/utils/stream.ts
1226
+ async function it() {
1227
+ let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this;
1228
+ if (!i) throw Error("Could not resolve app config");
1229
+ r.open = !0;
1230
+ let s = null, c = new URLSearchParams({ session_hash: this.session_hash }).toString(), l = new URL(`${i.root}${this.api_prefix}/${u}?${c}`);
1231
+ if (a && l.searchParams.set("__sign", a), s = this.stream(l), !s) {
1232
+ console.warn("Cannot connect to SSE endpoint: " + l.toString());
1233
+ return;
1234
+ }
1235
+ s.onmessage = async function(a) {
1236
+ let s = JSON.parse(a.data);
1237
+ if (s.msg === "close_stream") {
1238
+ at(r, o.abort_controller);
1239
+ return;
1240
+ }
1241
+ let c = s.event_id;
1242
+ if (!c) await Promise.all(Object.keys(e).map((t) => e[t](s)));
1243
+ else if (e[c] && i) {
1244
+ s.msg === "process_completed" && [
1245
+ "sse",
1246
+ "sse_v1",
1247
+ "sse_v2",
1248
+ "sse_v2.1",
1249
+ "sse_v3"
1250
+ ].includes(i.protocol) && t.delete(c);
1251
+ let n = e[c];
1252
+ typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, s) : n(s);
1253
+ } else n[c] || (n[c] = []), n[c].push(s);
1254
+ }, s.onerror = async function(t) {
1255
+ console.error(t), await Promise.all(Object.keys(e).map((t) => e[t]({
1256
+ msg: "broken_connection",
1257
+ message: v
1258
+ })));
1259
+ };
1260
+ }
1261
+ function at(e, t) {
1262
+ e && (e.open = !1, t?.abort());
1263
+ }
1264
+ function ot(e, t, n) {
1265
+ e[t] ? n.data.forEach((r, i) => {
1266
+ let a = st(i < e[t].length ? e[t][i] : null, r);
1267
+ e[t][i] = a, n.data[i] = a;
1268
+ }) : (e[t] = [], n.data.forEach((n, r) => {
1269
+ e[t][r] = n;
1270
+ }));
1271
+ }
1272
+ function st(e, t) {
1273
+ return t.forEach(([t, n, r]) => {
1274
+ e = ct(e, n, t, r);
1275
+ }), e;
1276
+ }
1277
+ function ct(e, t, n, r) {
1278
+ if (t.length === 0) {
1279
+ if (n === "replace") return r;
1280
+ if (n === "append") return e + r;
1281
+ throw Error(`Unsupported action: ${n}`);
1282
+ }
1283
+ let i = e;
1284
+ for (let e = 0; e < t.length - 1; e++) i = i[t[e]];
1285
+ let a = t[t.length - 1];
1286
+ switch (n) {
1287
+ case "replace":
1288
+ i[a] = r;
1289
+ break;
1290
+ case "append":
1291
+ i[a] += r;
1292
+ break;
1293
+ case "add":
1294
+ Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r;
1295
+ break;
1296
+ case "delete":
1297
+ Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a];
1298
+ break;
1299
+ default: throw Error(`Unknown action: ${n}`);
1300
+ }
1301
+ return e;
1302
+ }
1303
+ function lt(e, t = {}) {
1304
+ let n = {
1305
+ close: () => {
1306
+ console.warn("Method not implemented.");
1307
+ },
1308
+ onerror: null,
1309
+ onmessage: null,
1310
+ onopen: null,
1311
+ readyState: 0,
1312
+ url: e.toString(),
1313
+ withCredentials: !1,
1314
+ CONNECTING: 0,
1315
+ OPEN: 1,
1316
+ CLOSED: 2,
1317
+ addEventListener: () => {
1318
+ throw Error("Method not implemented.");
1319
+ },
1320
+ dispatchEvent: () => {
1321
+ throw Error("Method not implemented.");
1322
+ },
1323
+ removeEventListener: () => {
1324
+ throw Error("Method not implemented.");
1325
+ }
1326
+ };
1327
+ return rt(e, t).then(async (e) => {
1328
+ n.readyState = n.OPEN;
1329
+ try {
1330
+ for await (let t of e) n.onmessage && n.onmessage(t);
1331
+ n.readyState = n.CLOSED;
1332
+ } catch (e) {
1333
+ n.onerror && n.onerror(e), n.readyState = n.CLOSED;
1334
+ }
1335
+ }).catch((e) => {
1336
+ console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED;
1337
+ }), n;
1338
+ }
1339
+ //#endregion
1340
+ //#region src/utils/run_history.ts
1341
+ var K = "gradio:run-history:", q = `${K}v2:`, ut = `${K}replay:v2:`, dt = `${K}destination:v1:`, ft = 100, pt = 8;
1342
+ function J(e, t) {
1343
+ try {
1344
+ return e();
1345
+ } catch (e) {
1346
+ return console.warn("Could not update the run history.", e), t;
1347
+ }
1348
+ }
1349
+ function mt(e, t = "/gradio_api") {
1350
+ return `${e.replace(/\/+$/, "")}${t}/runs`;
1351
+ }
1352
+ function Y(e) {
1353
+ if (typeof window > "u") return null;
1354
+ let t = e?.app_id;
1355
+ if (t == null || t === "") return null;
1356
+ try {
1357
+ return window.localStorage ? `${q}${t}${e?.username ? `:user:${encodeURIComponent(e.username)}` : ""}` : null;
1358
+ } catch {
1359
+ return null;
1360
+ }
1361
+ }
1362
+ function ht(e) {
1363
+ let t = Y(e);
1364
+ return t ? t.replace(q, ut) : null;
1365
+ }
1366
+ function gt(e) {
1367
+ let t = Y(e);
1368
+ return t ? t.replace(q, dt) : null;
1369
+ }
1370
+ function _t(e) {
1371
+ let t = gt(e);
1372
+ if (!t) return { type: "browser" };
1373
+ try {
1374
+ let e = JSON.parse(window.localStorage.getItem(t) || "null");
1375
+ return typeof e?.bucket_id == "string" ? e.type === "bucket" ? {
1376
+ type: "bucket",
1377
+ bucket_id: e.bucket_id
1378
+ } : {
1379
+ type: "browser",
1380
+ bucket_id: e.bucket_id
1381
+ } : { type: "browser" };
1382
+ } catch {
1383
+ return { type: "browser" };
1384
+ }
1385
+ }
1386
+ function vt(e, t) {
1387
+ let n = gt(e);
1388
+ n && (t.type === "browser" && !t.bucket_id ? window.localStorage.removeItem(n) : window.localStorage.setItem(n, JSON.stringify(t)), Et());
1389
+ }
1390
+ function yt(e) {
1391
+ try {
1392
+ let t = JSON.parse(window.localStorage.getItem(e) || "[]");
1393
+ return Array.isArray(t) && t.length && Date.parse(t[0]?.started_at) || 0;
1394
+ } catch {
1395
+ return 0;
1396
+ }
1397
+ }
1398
+ function bt(e) {
1399
+ let t = Object.keys(window.localStorage).filter((e) => e.startsWith(K)), n = [...t.filter((e) => !e.startsWith(q) && !e.startsWith(ut) && !e.startsWith(dt)), ...t.filter((t) => t.startsWith(q) && t !== e).sort((e, t) => yt(t) - yt(e)).slice(pt - 1)];
1400
+ for (let e of n) try {
1401
+ window.localStorage.removeItem(e), window.sessionStorage.removeItem(e.replace(q, ut));
1402
+ } catch {}
1403
+ }
1404
+ function xt() {
1405
+ return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
1406
+ }
1407
+ function X(e) {
1408
+ let t = /* @__PURE__ */ new WeakSet();
1409
+ try {
1410
+ return JSON.parse(JSON.stringify(e, (e, n) => {
1411
+ if (typeof n == "bigint") return n.toString();
1412
+ if (typeof n == "object" && n) {
1413
+ if (t.has(n)) return "[Circular]";
1414
+ t.add(n);
1415
+ }
1416
+ return n;
1417
+ }));
1418
+ } catch {
1419
+ return "[Unserializable value]";
1420
+ }
1421
+ }
1422
+ function Z(e) {
1423
+ let t = Y(e);
1424
+ if (!t) return [];
1425
+ try {
1426
+ let e = JSON.parse(window.localStorage.getItem(t) || "[]");
1427
+ return Array.isArray(e) ? e : [];
1428
+ } catch {
1429
+ return [];
1430
+ }
1431
+ }
1432
+ function St(e, t) {
1433
+ let n = Y(e);
1434
+ if (!n) return;
1435
+ let r = t.slice(0, ft), i = !1;
1436
+ for (; r.length > 0;) try {
1437
+ window.localStorage.setItem(n, JSON.stringify(r));
1438
+ return;
1439
+ } catch {
1440
+ if (!i) {
1441
+ i = !0, bt(n);
1442
+ continue;
1443
+ }
1444
+ r = r.slice(0, -1);
1445
+ }
1446
+ try {
1447
+ window.localStorage.removeItem(n);
1448
+ } catch {}
1449
+ }
1450
+ function Ct(e) {
1451
+ let t = Y(e);
1452
+ if (t) {
1453
+ try {
1454
+ window.localStorage.removeItem(t);
1455
+ } catch {}
1456
+ Et();
1457
+ }
1458
+ }
1459
+ function wt(e, t) {
1460
+ St(e, Z(e).filter((e) => e.id !== t)), Et();
1461
+ }
1462
+ var Tt = "gradio:run-history-change";
1463
+ function Et() {
1464
+ if (!(typeof window > "u")) try {
1465
+ window.dispatchEvent(new Event(Tt));
1466
+ } catch {}
1467
+ }
1468
+ function Dt(e) {
1469
+ return typeof window > "u" ? () => {} : (window.addEventListener(Tt, e), window.addEventListener("storage", e), () => {
1470
+ window.removeEventListener(Tt, e), window.removeEventListener("storage", e);
1471
+ });
1472
+ }
1473
+ function Ot(e, t) {
1474
+ let n = ht(e);
1475
+ if (n) try {
1476
+ window.sessionStorage.setItem(n, JSON.stringify(t));
1477
+ } catch {}
1478
+ }
1479
+ function kt(e) {
1480
+ let t = ht(e);
1481
+ if (!t) return null;
1482
+ try {
1483
+ let e = window.sessionStorage.getItem(t);
1484
+ return window.sessionStorage.removeItem(t), e ? JSON.parse(e) : null;
1485
+ } catch {
1486
+ return null;
1487
+ }
1488
+ }
1489
+ function At(e, t) {
1490
+ let n = e.dependencies.find((e) => e.id === t.fn_index || typeof e.api_name == "string" && `/${e.api_name.replace(/^\//, "")}` === t.api_name);
1491
+ if (!n) return !1;
1492
+ let r = Array.isArray(t.inputs) ? t.inputs : Object.values(t.inputs ?? {}), i = Array.isArray(t.outputs) ? t.outputs : t.outputs === null || t.outputs === void 0 ? [] : [t.outputs], a = (t, n) => {
1493
+ for (let [r, i] of t.entries()) {
1494
+ let t = e.components.find((e) => e.id === i);
1495
+ !t || r >= n.length || t.type !== "state" && (t.props.value = n[r]);
1496
+ }
1497
+ };
1498
+ return a(n.inputs, r), a(n.outputs, i), !0;
1499
+ }
1500
+ function jt(e) {
1501
+ let t = kt(e);
1502
+ return t ? At(e, t) : !1;
1503
+ }
1504
+ function Mt(e) {
1505
+ if (_t(e).type === "bucket") return null;
1506
+ let t = Y(e);
1507
+ if (!t) return null;
1508
+ bt(t);
1509
+ let n = {
1510
+ id: xt(),
1511
+ endpoint: e.endpoint,
1512
+ api_name: e.api_name,
1513
+ fn_index: e.fn_index,
1514
+ page: `${window.location.pathname}${window.location.search}`,
1515
+ inputs: X(e.inputs),
1516
+ outputs: null,
1517
+ ...e.input_components ? { input_components: X(e.input_components) } : {},
1518
+ ...e.output_components ? { output_components: X(e.output_components) } : {},
1519
+ status: "running",
1520
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
1521
+ };
1522
+ return St(e, [n, ...Z(e)]), Et(), n.id;
1523
+ }
1524
+ function Nt(e, t, n) {
1525
+ if (!t) return;
1526
+ let r = Z(e), i = r.find((e) => e.id === t);
1527
+ i && (i.inputs = X(n), St(e, r));
1528
+ }
1529
+ function Pt(e, t, n) {
1530
+ if (!t) return;
1531
+ let r = Z(e), i = r.find((e) => e.id === t);
1532
+ if (!i) return;
1533
+ let a = !1;
1534
+ if (n.type === "data") i.outputs = X(n.data), Q.set(t, i.outputs);
1535
+ else if (n.type === "status" && n.original_msg === "process_starts") Lt(i, n.time);
1536
+ else if (n.type === "status" && (n.stage === "generating" || n.stage === "streaming")) i.streamed = !0;
1537
+ else if (n.type === "status" && n.stage === "complete") i.status = "completed", Rt(i, n), a = !0;
1538
+ else if (n.type === "status" && n.stage === "error") i.status = "failed", i.error = typeof n.message == "string" ? n.message : JSON.stringify(n.message || "Unknown error"), Rt(i, n), a = !0;
1539
+ else return;
1540
+ if (a) Q.has(t) && (i.outputs = Q.get(t)), Q.delete(t), It.delete(t);
1541
+ else if (i.streamed) {
1542
+ if (Date.now() - (It.get(t) ?? 0) < Ft) return;
1543
+ It.set(t, Date.now()), Q.delete(t);
1544
+ }
1545
+ St(e, r);
1546
+ }
1547
+ var Ft = 500, It = /* @__PURE__ */ new Map(), Q = /* @__PURE__ */ new Map();
1548
+ function Lt(e, t) {
1549
+ if (e.process_started_at) return;
1550
+ let n = t || /* @__PURE__ */ new Date();
1551
+ e.process_started_at = n.toISOString(), e.queued_ms = Math.max(0, n.getTime() - Date.parse(e.started_at));
1552
+ }
1553
+ function Rt(e, t) {
1554
+ let n = t.time || /* @__PURE__ */ new Date();
1555
+ e.completed_at = n.toISOString(), e.duration_ms = (!e.streamed && typeof t.cache_duration == "number" && t.cache_duration >= 0 ? t.cache_duration * 1e3 : null) ?? Math.max(0, n.getTime() - Date.parse(e.process_started_at || e.started_at));
1556
+ }
1557
+ function zt(e) {
1558
+ return J(() => Z(e), []);
1559
+ }
1560
+ function Bt(e) {
1561
+ return J(() => _t(e), { type: "browser" });
1562
+ }
1563
+ function Vt(e, t) {
1564
+ J(() => vt(e, t), void 0);
1565
+ }
1566
+ function Ht(e) {
1567
+ J(() => Ct(e), void 0);
1568
+ }
1569
+ function Ut(e, t) {
1570
+ J(() => wt(e, t), void 0);
1571
+ }
1572
+ function Wt(e, t) {
1573
+ J(() => Ot(e, t), void 0);
1574
+ }
1575
+ function Gt(e) {
1576
+ return J(() => kt(e), null);
1577
+ }
1578
+ function Kt(e) {
1579
+ return J(() => jt(e), !1);
1580
+ }
1581
+ function qt(e) {
1582
+ return J(() => Mt(e), null);
1583
+ }
1584
+ function Jt(e, t, n) {
1585
+ J(() => Nt(e, t, n), void 0);
1586
+ }
1587
+ function Yt(e, t, n) {
1588
+ J(() => Pt(e, t, n), void 0);
1589
+ }
1590
+ function Xt(e) {
1591
+ return J(() => Dt(() => J(e, void 0)), () => {});
1592
+ }
1593
+ //#endregion
1594
+ //#region src/utils/submit.ts
1595
+ function Zt(e, t = {}, n, r, i, a) {
1596
+ try {
1597
+ let { token: o } = this.options, { fetch: s, app_reference: c, config: l, session_hash: f, api_info: p, api_map: m, stream_status: ee, pending_stream_messages: h, pending_diff_streams: g, event_callbacks: _, unclosed_events: te, post_data: ie, options: y, api_prefix: b } = this, oe = a || { "x-gradio-user": "api" }, x = this;
1598
+ if (!p) throw Error(le);
1599
+ if (!l) throw Error("Could not resolve app config");
1600
+ let se = l.root, { fn_index: S, endpoint_info: C, dependency: w } = $t(p, e, m, l), ce = be(t, C), T = l.protocol ?? "ws";
1601
+ if (T === "ws") throw Error(ue);
1602
+ let de = typeof w.api_name == "string" ? `/${w.api_name}` : e, fe = typeof w.api_name == "string" ? `/${w.api_name}` : `Function ${S}`, pe = (e) => {
1603
+ let t = l.components.find((t) => t.id === e);
1604
+ return t ? {
1605
+ type: t.type,
1606
+ component_class_id: t.component_class_id,
1607
+ props: t.props
1608
+ } : null;
1609
+ }, me = w.api_visibility === "public", he = l.run_history !== !1 && this.options.record_history !== !1, E = {
1610
+ app_id: l.app_id,
1611
+ username: l.username
1612
+ }, ge = Bt(E), D = {
1613
+ ...oe,
1614
+ ...he && ge.type === "bucket" ? { "x-gradio-history-bucket": ge.bucket_id } : {}
1615
+ }, O = !he || !me ? null : qt({
1616
+ ...E,
1617
+ endpoint: de,
1618
+ api_name: fe,
1619
+ fn_index: S,
1620
+ inputs: W(ce, w, l.components, "input", !0),
1621
+ input_components: w.inputs.map(pe),
1622
+ output_components: w.outputs.map(pe)
1623
+ }), k, A = "", j = typeof e == "number" ? "/predict" : e, M, N = null, P = !1, F = {}, I = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", _e = y?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {};
1624
+ function L(e) {
1625
+ Yt(E, O, e), (e.type === "data" || e.type === "render") && Ae(e.data, se, b, x.jwt), (i || _e[e.type]) && Te(e);
1626
+ }
1627
+ async function ve() {
1628
+ let e = {}, t = {};
1629
+ e = { event_id: N }, t = {
1630
+ event_id: N,
1631
+ session_hash: f,
1632
+ fn_index: S
1633
+ };
1634
+ try {
1635
+ if (!l) throw Error("Could not resolve app config");
1636
+ "event_id" in t && await s(`${l.root}${b}/${re}`, {
1637
+ headers: { "Content-Type": "application/json" },
1638
+ method: "POST",
1639
+ body: JSON.stringify(t)
1640
+ }), await s(`${l.root}${b}/${ne}`, {
1641
+ headers: { "Content-Type": "application/json" },
1642
+ method: "POST",
1643
+ body: JSON.stringify(e)
1644
+ });
1645
+ } catch {
1646
+ console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.");
1647
+ }
1648
+ }
1649
+ let xe = async (e) => {
1650
+ await this._resolve_heartbeat(e);
1651
+ };
1652
+ async function Se(e) {
1653
+ if (!l) return;
1654
+ let t = e.render_id;
1655
+ l.components = [...l.components.filter((e) => e.props.rendered_in !== t), ...e.components], l.dependencies = [...l.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies];
1656
+ let n = l.components.some((e) => e.type === "state"), r = l.dependencies.some((e) => e.targets.some((e) => e[1] === "unload"));
1657
+ l.connect_heartbeat = n || r, await xe(l), L({
1658
+ type: "render",
1659
+ data: e,
1660
+ endpoint: j,
1661
+ fn_index: S
1662
+ });
1663
+ }
1664
+ let R = this.handle_blob(l.root, ce, C).then(async (e) => {
1665
+ let t = W(e, w, l.components, "input", !0);
1666
+ if (Jt(E, O, t || []), M = {
1667
+ data: t || [],
1668
+ event_data: n,
1669
+ fn_index: S,
1670
+ trigger_id: r,
1671
+ ...y.oauth_token && C?.oauth_token ? { oauth_token: y.oauth_token } : {}
1672
+ }, Ee(S, l)) L({
1673
+ type: "status",
1674
+ endpoint: j,
1675
+ stage: "pending",
1676
+ queue: !1,
1677
+ fn_index: S,
1678
+ time: /* @__PURE__ */ new Date()
1679
+ }), ie(`${l.root}${b}/run${j.startsWith("/") ? j : `/${j}`}${I ? "?" + I : ""}`, {
1680
+ ...M,
1681
+ session_hash: f
1682
+ }, D).then(async ([e, t]) => {
1683
+ let i = e.data;
1684
+ if (t == 200) L({
1685
+ type: "data",
1686
+ endpoint: j,
1687
+ fn_index: S,
1688
+ data: W(i, w, l.components, "output", y.with_null_state),
1689
+ time: /* @__PURE__ */ new Date(),
1690
+ event_data: n,
1691
+ trigger_id: r
1692
+ }), e.render_config && await Se(e.render_config), L({
1693
+ type: "status",
1694
+ endpoint: j,
1695
+ fn_index: S,
1696
+ stage: "complete",
1697
+ eta: e.average_duration,
1698
+ queue: !1,
1699
+ time: /* @__PURE__ */ new Date()
1700
+ });
1701
+ else {
1702
+ let t = e?.error === v;
1703
+ L({
1704
+ type: "status",
1705
+ stage: "error",
1706
+ endpoint: j,
1707
+ fn_index: S,
1708
+ message: e.error,
1709
+ broken: t,
1710
+ queue: !1,
1711
+ time: /* @__PURE__ */ new Date()
1712
+ });
1713
+ }
1714
+ }).catch((e) => {
1715
+ L({
1716
+ type: "status",
1717
+ stage: "error",
1718
+ message: e.message,
1719
+ endpoint: j,
1720
+ fn_index: S,
1721
+ queue: !1,
1722
+ time: /* @__PURE__ */ new Date()
1723
+ });
1724
+ });
1725
+ else if (T == "sse") {
1726
+ L({
1727
+ type: "status",
1728
+ stage: "pending",
1729
+ queue: !0,
1730
+ endpoint: j,
1731
+ fn_index: S,
1732
+ time: /* @__PURE__ */ new Date()
1733
+ });
1734
+ var i = new URLSearchParams({
1735
+ fn_index: S.toString(),
1736
+ session_hash: f
1737
+ }).toString();
1738
+ let e = new URL(`${l.root}${b}/${u}?${I ? I + "&" : ""}${i}`);
1739
+ if (this.jwt && e.searchParams.set("__sign", this.jwt), k = this.stream(e), !k) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString()));
1740
+ k.onmessage = async function(e) {
1741
+ let { type: t, status: i, data: a } = ye(JSON.parse(e.data), F[S]);
1742
+ if (t === "update" && i && !P) L({
1743
+ type: "status",
1744
+ endpoint: j,
1745
+ fn_index: S,
1746
+ time: /* @__PURE__ */ new Date(),
1747
+ ...i
1748
+ }), i.stage === "error" && (k?.close(), V());
1749
+ else if (t === "data") {
1750
+ let [e, t] = await ie(`${l.root}${b}/queue/data`, {
1751
+ ...M,
1752
+ session_hash: f,
1753
+ event_id: N
1754
+ }, D);
1755
+ t !== 200 && (L({
1756
+ type: "status",
1757
+ stage: "error",
1758
+ message: v,
1759
+ queue: !0,
1760
+ endpoint: j,
1761
+ fn_index: S,
1762
+ time: /* @__PURE__ */ new Date()
1763
+ }), k?.close(), V());
1764
+ } else t === "complete" ? P = i : t === "log" ? L({
1765
+ type: "log",
1766
+ title: a.title,
1767
+ log: a.log,
1768
+ level: a.level,
1769
+ endpoint: j,
1770
+ duration: a.duration,
1771
+ visible: a.visible,
1772
+ fn_index: S
1773
+ }) : (t === "generating" || t === "streaming") && L({
1774
+ type: "status",
1775
+ time: /* @__PURE__ */ new Date(),
1776
+ ...i,
1777
+ stage: i?.stage,
1778
+ queue: !0,
1779
+ endpoint: j,
1780
+ fn_index: S
1781
+ });
1782
+ a && (L({
1783
+ type: "data",
1784
+ time: /* @__PURE__ */ new Date(),
1785
+ data: W(a.data, w, l.components, "output", y.with_null_state),
1786
+ endpoint: j,
1787
+ fn_index: S,
1788
+ event_data: n,
1789
+ trigger_id: r
1790
+ }), P && (L({
1791
+ type: "status",
1792
+ time: /* @__PURE__ */ new Date(),
1793
+ ...P,
1794
+ stage: i?.stage,
1795
+ queue: !0,
1796
+ endpoint: j,
1797
+ fn_index: S
1798
+ }), k?.close(), V()));
1799
+ };
1800
+ } else if (T == "sse_v1" || T == "sse_v2" || T == "sse_v2.1" || T == "sse_v3") {
1801
+ L({
1802
+ type: "status",
1803
+ stage: "pending",
1804
+ queue: !0,
1805
+ endpoint: j,
1806
+ fn_index: S,
1807
+ time: /* @__PURE__ */ new Date()
1808
+ });
1809
+ let e = "";
1810
+ typeof window < "u" && typeof document < "u" && (e = window?.location?.hostname);
1811
+ let t = Xe(e);
1812
+ return (typeof window < "u" && typeof document < "u" && window.parent != window && t && window.supports_zerogpu_headers ? De("zerogpu-headers", t) : Promise.resolve(null)).then((e) => {
1813
+ let t = {
1814
+ ...D,
1815
+ ...e || {}
1816
+ };
1817
+ return ie(`${l.root}${b}/${d}?${I}`, {
1818
+ ...M,
1819
+ session_hash: f
1820
+ }, t);
1821
+ }).then(async ([e, t]) => {
1822
+ if (e.event_id && (A = e.event_id), t === 503) L({
1823
+ type: "status",
1824
+ stage: "error",
1825
+ message: ae,
1826
+ queue: !0,
1827
+ endpoint: j,
1828
+ fn_index: S,
1829
+ time: /* @__PURE__ */ new Date(),
1830
+ visible: !0
1831
+ }), V();
1832
+ else if (t === 422) L({
1833
+ type: "status",
1834
+ stage: "error",
1835
+ message: e.detail,
1836
+ queue: !0,
1837
+ endpoint: j,
1838
+ fn_index: S,
1839
+ code: "validation_error",
1840
+ time: /* @__PURE__ */ new Date(),
1841
+ visible: !0
1842
+ }), V();
1843
+ else if (t !== 200) {
1844
+ let t = e?.error === v;
1845
+ L({
1846
+ type: "status",
1847
+ stage: "error",
1848
+ broken: t,
1849
+ message: t ? v : e.detail || e.error,
1850
+ queue: !0,
1851
+ endpoint: j,
1852
+ fn_index: S,
1853
+ time: /* @__PURE__ */ new Date(),
1854
+ visible: !0
1855
+ }), V();
1856
+ } else {
1857
+ N = e.event_id, A = N;
1858
+ let t = async function(e) {
1859
+ try {
1860
+ let { type: t, status: n, data: r, original_msg: i } = ye(e, F[S]);
1861
+ if (t == "heartbeat") return;
1862
+ if (t === "update" && n && !P) L({
1863
+ type: "status",
1864
+ endpoint: j,
1865
+ fn_index: S,
1866
+ time: /* @__PURE__ */ new Date(),
1867
+ original_msg: i,
1868
+ ...n
1869
+ });
1870
+ else if (t === "complete") P = n;
1871
+ else if (t == "unexpected_error" || t == "broken_connection") {
1872
+ console.error("Unexpected error", n?.message);
1873
+ let e = t === "broken_connection";
1874
+ L({
1875
+ type: "status",
1876
+ stage: "error",
1877
+ message: n?.message || "An Unexpected Error Occurred!",
1878
+ queue: !0,
1879
+ endpoint: j,
1880
+ broken: e,
1881
+ session_not_found: n?.session_not_found,
1882
+ fn_index: S,
1883
+ time: /* @__PURE__ */ new Date()
1884
+ });
1885
+ } else if (t === "log") {
1886
+ L({
1887
+ type: "log",
1888
+ title: r.title,
1889
+ log: r.log,
1890
+ level: r.level,
1891
+ endpoint: j,
1892
+ duration: r.duration,
1893
+ visible: r.visible,
1894
+ fn_index: S
1895
+ });
1896
+ return;
1897
+ } else (t === "generating" || t === "streaming") && (L({
1898
+ type: "status",
1899
+ time: /* @__PURE__ */ new Date(),
1900
+ ...n,
1901
+ stage: n?.stage,
1902
+ queue: !0,
1903
+ endpoint: j,
1904
+ fn_index: S
1905
+ }), r && w.connection !== "stream" && [
1906
+ "sse_v2",
1907
+ "sse_v2.1",
1908
+ "sse_v3"
1909
+ ].includes(T) && ot(g, N, r));
1910
+ r && (L({
1911
+ type: "data",
1912
+ time: /* @__PURE__ */ new Date(),
1913
+ data: W(r.data, w, l.components, "output", y.with_null_state),
1914
+ endpoint: j,
1915
+ fn_index: S
1916
+ }), r.render_config && await Se(r.render_config), P && (L({
1917
+ type: "status",
1918
+ time: /* @__PURE__ */ new Date(),
1919
+ ...P,
1920
+ stage: n?.stage,
1921
+ queue: !0,
1922
+ endpoint: j,
1923
+ fn_index: S
1924
+ }), V())), (n?.stage === "complete" || n?.stage === "error") && (_[N] && delete _[N], N in g && delete g[N], V());
1925
+ } catch (e) {
1926
+ console.error("Unexpected client exception", e), L({
1927
+ type: "status",
1928
+ stage: "error",
1929
+ message: "An Unexpected Error Occurred!",
1930
+ queue: !0,
1931
+ endpoint: j,
1932
+ fn_index: S,
1933
+ time: /* @__PURE__ */ new Date()
1934
+ }), [
1935
+ "sse_v2",
1936
+ "sse_v2.1",
1937
+ "sse_v3"
1938
+ ].includes(T) && (at(ee, x.abort_controller), ee.open = !1, V());
1939
+ }
1940
+ };
1941
+ N in h && (h[N].forEach((e) => t(e)), delete h[N]), _[N] = t, te.add(N), ee.open || await this.open_stream();
1942
+ }
1943
+ });
1944
+ }
1945
+ });
1946
+ R.catch((e) => {
1947
+ L({
1948
+ type: "status",
1949
+ stage: "error",
1950
+ message: e instanceof Error ? e.message : String(e),
1951
+ queue: !Ee(S, l),
1952
+ endpoint: j,
1953
+ fn_index: S,
1954
+ time: /* @__PURE__ */ new Date()
1955
+ }), V();
1956
+ });
1957
+ let Ce = !1, z = [], B = [];
1958
+ function V() {
1959
+ for (Ce = !0; B.length > 0;) B.shift()({
1960
+ value: void 0,
1961
+ done: !0
1962
+ });
1963
+ }
1964
+ function H(e) {
1965
+ B.length > 0 ? B.shift()(e) : z.push(e);
1966
+ }
1967
+ function we(e) {
1968
+ H(Qt(e)), V();
1969
+ }
1970
+ function Te(e) {
1971
+ H({
1972
+ value: e,
1973
+ done: !1
1974
+ });
1975
+ }
1976
+ function U() {
1977
+ return z.length > 0 ? Promise.resolve(z.shift()) : Ce ? Promise.resolve({
1978
+ value: void 0,
1979
+ done: !0
1980
+ }) : new Promise((e) => B.push(e));
1981
+ }
1982
+ let Oe = (e, t) => {
1983
+ R.then(() => {
1984
+ A && this.post_data(`${l.root}${b}/stream/${A}${e}`, t);
1985
+ }, () => {});
1986
+ }, ke = {
1987
+ [Symbol.asyncIterator]: () => ke,
1988
+ next: U,
1989
+ throw: async (e) => (we(e), U()),
1990
+ return: async () => (V(), {
1991
+ value: void 0,
1992
+ done: !0
1993
+ }),
1994
+ cancel: ve,
1995
+ send_chunk: (e) => {
1996
+ Oe("", {
1997
+ ...e,
1998
+ session_hash: this.session_hash
1999
+ });
2000
+ },
2001
+ close_stream: () => {
2002
+ V(), Oe("/close", {});
2003
+ },
2004
+ event_id: () => A,
2005
+ wait_for_id: async () => (await R, N)
2006
+ };
2007
+ return ke;
2008
+ } catch (e) {
2009
+ throw console.error("Submit function encountered an error:", e), e;
2010
+ }
2011
+ }
2012
+ function Qt(e) {
2013
+ return { then: (t, n) => n(e) };
2014
+ }
2015
+ function $t(e, t, n, r) {
2016
+ let i, a, o;
2017
+ if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t);
2018
+ else {
2019
+ let s = t.replace(/^\//, "");
2020
+ i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]);
2021
+ }
2022
+ if (typeof i != "number" || !o) {
2023
+ let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", ");
2024
+ throw Error(`No endpoint matching ${JSON.stringify(t)} was found. ` + (e ? `Valid named endpoints are: ${e}. ` : "This app exposes no named endpoints. ") + "An fn_index (number) of an existing dependency can also be used.");
2025
+ }
2026
+ return {
2027
+ fn_index: i,
2028
+ endpoint_info: a,
2029
+ dependency: o
2030
+ };
2031
+ }
2032
+ //#endregion
2033
+ //#region src/client.ts
2034
+ var $ = class {
2035
+ app_reference;
2036
+ options;
2037
+ deep_link = null;
2038
+ page = null;
2039
+ config;
2040
+ api_prefix = "";
2041
+ api_info;
2042
+ api_map = {};
2043
+ session_hash = Math.random().toString(36).substring(2);
2044
+ jwt = !1;
2045
+ last_status = {};
2046
+ cookies = null;
2047
+ stream_status = { open: !1 };
2048
+ closed = !1;
2049
+ pending_stream_messages = {};
2050
+ pending_diff_streams = {};
2051
+ event_callbacks = {};
2052
+ unclosed_events = /* @__PURE__ */ new Set();
2053
+ heartbeat_event = null;
2054
+ abort_controller = null;
2055
+ stream_instance = null;
2056
+ current_payload;
2057
+ get_url_config(e = null) {
2058
+ if (!this.config) throw Error(y);
2059
+ e === null && (e = window.location.href);
2060
+ let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i;
2061
+ return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i);
2062
+ }
2063
+ get_page_config(e) {
2064
+ if (!this.config) throw Error(y);
2065
+ let t = this.config;
2066
+ return e in t.page || (e = ""), {
2067
+ ...t,
2068
+ current_page: e,
2069
+ layout: t.page[e].layout,
2070
+ components: t.components.filter((n) => t.page[e].components.includes(n.id)),
2071
+ dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id))
2072
+ };
2073
+ }
2074
+ fetch(e, t) {
2075
+ let n = new Headers(t?.headers || {});
2076
+ return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => {
2077
+ n.append(t, e);
2078
+ }), fetch(e, {
2079
+ ...t,
2080
+ headers: n
2081
+ });
2082
+ }
2083
+ stream(e) {
2084
+ let t = new Headers();
2085
+ return this && this.cookies && t.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, n) => {
2086
+ t.append(n, e);
2087
+ }), this && this.options.token && t.append("Authorization", `Bearer ${this.options.token}`), this.abort_controller = new AbortController(), this.stream_instance = lt(e.toString(), {
2088
+ credentials: this.options.credentials ?? "same-origin",
2089
+ headers: t,
2090
+ signal: this.abort_controller.signal
2091
+ }), this.stream_instance;
2092
+ }
2093
+ view_api;
2094
+ upload_files;
2095
+ upload;
2096
+ handle_blob;
2097
+ post_data;
2098
+ submit;
2099
+ predict;
2100
+ open_stream;
2101
+ resolve_config;
2102
+ resolve_cookies;
2103
+ constructor(e, t = { events: ["data"] }) {
2104
+ this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, this.page = t.query_params?.page ?? null, t.events ||= ["data"], he(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = xe.bind(this), this.upload_files = Se.bind(this), this.handle_blob = Ne.bind(this), this.post_data = Le.bind(this), this.submit = Zt.bind(this), this.predict = Re.bind(this), this.open_stream = it.bind(this), this.resolve_config = D.bind(this), this.resolve_cookies = k.bind(this), this.upload = z.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this);
2105
+ }
2106
+ async init() {
2107
+ Ze(), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then((e) => e?.config && this._resolve_heartbeat(e.config));
2108
+ try {
2109
+ this.api_info = await this.view_api();
2110
+ } catch (e) {
2111
+ console.error(e.message);
2112
+ }
2113
+ this.api_map = E(this.config?.dependencies || []);
2114
+ }
2115
+ async _resolve_heartbeat(e) {
2116
+ if (this.config = e, this.api_prefix = e.api_prefix || "", e.space_id && this.options.token && (this.jwt = await me(e.space_id, this.options.token, this.cookies)), je(this.config, this.jwt), this.config && this.config.connect_heartbeat) {
2117
+ let e = new URL(`${this.config.root}${this.api_prefix}/${_}/${this.session_hash}`);
2118
+ this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_event ||= this.stream(e);
2119
+ }
2120
+ }
2121
+ static async connect(e, t = { events: ["data"] }) {
2122
+ let n = new this(e, t);
2123
+ return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n;
2124
+ }
2125
+ async reconnect() {
2126
+ let e = new URL(`${this.config.root}${this.api_prefix}/${ie}`), t;
2127
+ try {
2128
+ let n = await this.fetch(e);
2129
+ if (!n.ok) throw Error();
2130
+ t = (await n.json()).app_id;
2131
+ } catch {
2132
+ return "broken";
2133
+ }
2134
+ return t === this.config.app_id ? "connected" : "changed";
2135
+ }
2136
+ close() {
2137
+ this.closed = !0, at(this.stream_status, this.abort_controller);
2138
+ }
2139
+ async refresh() {
2140
+ if (!this.config) throw Error(y);
2141
+ let e = await this.resolve_config(this.config.root, !1);
2142
+ if (!e) throw Error(y);
2143
+ this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = E(e.dependencies || []), je(this.config, this.jwt);
2144
+ try {
2145
+ this.api_info = await this.view_api();
2146
+ } catch (e) {
2147
+ console.error(oe + e.message);
2148
+ }
2149
+ return this.get_url_config();
2150
+ }
2151
+ set_current_payload(e) {
2152
+ this.current_payload = e;
2153
+ }
2154
+ static async duplicate(e, t = { events: ["data"] }) {
2155
+ return Ge(e, t);
2156
+ }
2157
+ async _resolve_config() {
2158
+ let { http_protocol: e, host: t, space_id: n } = await F(this.app_reference, this.options.token), { status_callback: r } = this.options;
2159
+ n && r && await ze(n, r);
2160
+ let i;
2161
+ try {
2162
+ let n = `${e}//${t}`;
2163
+ if (i = await this.resolve_config(n), !i) throw Error(y);
2164
+ return this.config_success(i);
2165
+ } catch (e) {
2166
+ if (n && r) G(n, N.test(n) ? "space_name" : "subdomain", this.handle_space_success);
2167
+ else throw r && r({
2168
+ status: "error",
2169
+ message: "Could not load this space.",
2170
+ load_status: "error",
2171
+ detail: "NOT_FOUND"
2172
+ }), e instanceof Error ? e : Error(String(e));
2173
+ }
2174
+ }
2175
+ async config_success(e) {
2176
+ if (this.config = e, this.api_prefix = e.api_prefix || "", e.run_history === !1 && Ht({
2177
+ app_id: e.app_id,
2178
+ username: e.username
2179
+ }), this.config.auth_required) return this.prepare_return_obj();
2180
+ try {
2181
+ this.api_info = await this.view_api();
2182
+ } catch (e) {
2183
+ console.error(oe + e.message);
2184
+ }
2185
+ return this.prepare_return_obj();
2186
+ }
2187
+ async handle_space_success(e) {
2188
+ if (!this) throw Error(y);
2189
+ let { status_callback: t } = this.options;
2190
+ if (t && t(e), e.status === "running") try {
2191
+ if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(y);
2192
+ return await this.config_success(this.config);
2193
+ } catch (e) {
2194
+ throw t && t({
2195
+ status: "error",
2196
+ message: "Could not load this space.",
2197
+ load_status: "error",
2198
+ detail: "NOT_FOUND"
2199
+ }), e;
2200
+ }
2201
+ }
2202
+ async component_server(e, t, n) {
2203
+ if (!this.config) throw Error(y);
2204
+ let r = {}, { token: i } = this.options, { session_hash: a } = this;
2205
+ i && (r.Authorization = `Bearer ${this.options.token}`);
2206
+ let o, s = this.config.components.find((t) => t.id === e);
2207
+ o = s?.props?.root_url ? s.props.root_url : this.config.root;
2208
+ let c;
2209
+ if (typeof n == "object" && n && "binary" in n) {
2210
+ let r = n;
2211
+ c = new FormData();
2212
+ for (let e in r.data) e !== "binary" && c.append(e, r.data[e]);
2213
+ c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a);
2214
+ } else c = JSON.stringify({
2215
+ data: n,
2216
+ component_id: e,
2217
+ fn_name: t,
2218
+ session_hash: a
2219
+ }), r["Content-Type"] = "application/json";
2220
+ i && (r.Authorization = `Bearer ${i}`);
2221
+ try {
2222
+ let e = await this.fetch(`${o}${this.api_prefix}/${te}/`, {
2223
+ method: "POST",
2224
+ body: c,
2225
+ headers: r,
2226
+ credentials: this.options.credentials ?? "same-origin"
2227
+ });
2228
+ if (!e.ok) throw Error("Could not connect to component server: " + e.statusText);
2229
+ let t = await e.json();
2230
+ return Ae(t, this.config.root, this.config.api_prefix || "", this.jwt), t;
2231
+ } catch (e) {
2232
+ console.warn(e);
2233
+ }
2234
+ }
2235
+ set_cookies(e) {
2236
+ this.cookies = M(e).join("; ");
2237
+ }
2238
+ prepare_return_obj() {
2239
+ return {
2240
+ config: this.config,
2241
+ predict: this.predict,
2242
+ submit: this.submit,
2243
+ view_api: this.view_api,
2244
+ component_server: this.component_server
2245
+ };
2246
+ }
2247
+ };
2248
+ async function en(e, t = { events: ["data"] }) {
2249
+ return await $.connect(e, t);
2250
+ }
2251
+ async function tn(e, t) {
2252
+ return await $.duplicate(e, t);
2253
+ }
2254
+ //#endregion
2255
+ //#region src/utils/bucket_sync.ts
2256
+ var nn = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-][a-zA-Z0-9_./-]*$/;
2257
+ function rn(e) {
2258
+ return nn.test(e) ? !e.split("/").some((e) => e === "" || e === "." || e === "..") : !1;
2259
+ }
2260
+ function an(e, t, n) {
2261
+ let r = n ? `?${new URLSearchParams(n)}` : "", i = e.replace(/\/+$/, "");
2262
+ return i ? `${i}/gradio_api/run-history/${t}${r}` : typeof document < "u" && document.baseURI ? new URL(`gradio_api/run-history/${t}${r}`, document.baseURI).toString() : `gradio_api/run-history/${t}${r}`;
2263
+ }
2264
+ async function on(e) {
2265
+ try {
2266
+ let t = await e.json();
2267
+ return typeof t?.detail == "string" ? t.detail : `${e.status}`;
2268
+ } catch {
2269
+ return `${e.status}`;
2270
+ }
2271
+ }
2272
+ async function sn(e, t, n, r) {
2273
+ try {
2274
+ let i = await fetch(e, {
2275
+ credentials: "include",
2276
+ ...t
2277
+ });
2278
+ return i.ok ? {
2279
+ ok: !0,
2280
+ status: i.status,
2281
+ data: r(await i.json())
2282
+ } : {
2283
+ ok: !1,
2284
+ status: i.status,
2285
+ data: n,
2286
+ detail: await on(i)
2287
+ };
2288
+ } catch (e) {
2289
+ return {
2290
+ ok: !1,
2291
+ status: 0,
2292
+ data: n,
2293
+ detail: String(e)
2294
+ };
2295
+ }
2296
+ }
2297
+ async function cn(e, t) {
2298
+ return rn(t) ? sn(an(e, "connect"), {
2299
+ method: "POST",
2300
+ headers: { "Content-Type": "application/json" },
2301
+ body: JSON.stringify({ bucket_id: t })
2302
+ }, null, () => null) : {
2303
+ ok: !1,
2304
+ status: 422,
2305
+ data: null,
2306
+ detail: "invalid bucket id"
2307
+ };
2308
+ }
2309
+ async function ln(e) {
2310
+ return sn(an(e, "buckets"), {}, [], (e) => Array.isArray(e?.buckets) ? e.buckets : []);
2311
+ }
2312
+ async function un(e, t) {
2313
+ return sn(an(e, "records", { bucket: t }), {}, [], (e) => Array.isArray(e?.records) ? e.records : []);
2314
+ }
2315
+ function dn(e, t, n, r, i) {
2316
+ return an(e, `records/${encodeURIComponent(n)}/${encodeURIComponent(r)}/assets/${encodeURIComponent(i)}`, { bucket: t });
2317
+ }
2318
+ //#endregion
2319
+ export { $ as Client, V as FileData, w as MISSING_CREDENTIALS_MSG, Kt as apply_run_history_replay, dn as asset_url, Ht as clear_run_history, en as client, cn as connect_bucket, Gt as consume_run_history_replay, Ut as delete_run_history, tn as duplicate, Oe as handle_file, rn as is_valid_bucket_id, un as list_bucket_records, ln as list_user_buckets, Xt as on_run_history_change, Re as predict, B as prepare_files, zt as read_run_history, Bt as read_run_history_storage, mt as run_history_url, Vt as set_run_history_storage, Wt as stage_run_history_replay, Zt as submit, z as upload, Se as upload_files };
static/index.html CHANGED
@@ -5,6 +5,7 @@
5
  <meta name="theme-color" content="#faf9f6">
6
  <title>PixText · Text repair studio</title>
7
  <link rel="stylesheet" href="/static/style.css">
 
8
  <script defer src="/static/app.js"></script>
9
  </head>
10
  <body>
 
5
  <meta name="theme-color" content="#faf9f6">
6
  <title>PixText · Text repair studio</title>
7
  <link rel="stylesheet" href="/static/style.css">
8
+ <link rel="modulepreload" href="/static/gradio-client.js">
9
  <script defer src="/static/app.js"></script>
10
  </head>
11
  <body>