gradio-pr-bot commited on
Commit
71a50ff
·
verified ·
1 Parent(s): 623a645

Upload folder using huggingface_hub

Browse files
6.11.0/utils/package.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/utils",
3
+ "version": "0.12.1",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "author": "",
8
+ "license": "ISC",
9
+ "dependencies": {
10
+ "@gradio/theme": "workspace:^",
11
+ "svelte-i18n": "^4.0.1"
12
+ },
13
+ "main_changeset": true,
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/gradio-app/gradio.git",
17
+ "directory": "js/utils"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "gradio": "./src/index.ts",
22
+ "types": "./dist/src/index.d.ts",
23
+ "import": "./dist/src/index.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "scripts": {
28
+ "package": "svelte-package --input=. --tsconfig=../../tsconfig.json"
29
+ }
30
+ }
6.11.0/utils/src/color.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import { colors, ordered_colors } from "@gradio/theme";
2
+
3
+ export const get_next_color = (index: number): keyof typeof colors => {
4
+ return ordered_colors[index % ordered_colors.length];
5
+ };
6.11.0/utils/src/index.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export * from "./color.js";
2
+ export * from "./utils.svelte.js";
3
+ export * from "./types.js";
6.11.0/utils/src/types.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import type { FileData } from "@gradio/client";
2
+
3
+ export interface CustomButton {
4
+ id: number;
5
+ value: string | null;
6
+ icon: FileData | null;
7
+ }
6.11.0/utils/src/utils.svelte.ts ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ActionReturn } from "svelte/action";
2
+ import type { Client } from "@gradio/client";
3
+ import type { ComponentType, SvelteComponent } from "svelte";
4
+ import { tick, untrack } from "svelte";
5
+ import type { Component } from "svelte";
6
+ import { locale } from "svelte-i18n";
7
+
8
+ export const I18N_MARKER = "__i18n__";
9
+ const TRANSLATABLE_PROPS = [
10
+ "label",
11
+ "info",
12
+ "placeholder",
13
+ "description",
14
+ "title",
15
+ "value"
16
+ ];
17
+
18
+ export interface SharedProps {
19
+ elem_id?: string;
20
+ elem_classes: string[];
21
+ components?: string[];
22
+ server_fns?: string[];
23
+ interactive: boolean;
24
+ visible: boolean | "hidden";
25
+ id: number;
26
+ container: boolean;
27
+ target: HTMLElement;
28
+ theme_mode: "light" | "dark" | "system";
29
+ version: string;
30
+ root: string;
31
+ autoscroll: boolean;
32
+ max_file_size: number | null;
33
+ formatter: any; //I18nFormatter;
34
+ client: Client;
35
+ scale: number;
36
+ min_width: number;
37
+ padding: number;
38
+ load_component: load_component;
39
+ loading_status?: any;
40
+ label: string;
41
+ show_label: boolean;
42
+ validation_error?: string | null;
43
+ theme?: "light" | "dark";
44
+ show_progress: boolean;
45
+ api_prefix: string;
46
+ server: ServerFunctions;
47
+ attached_events?: string[];
48
+ register_component: (
49
+ id: number,
50
+ set_data: (data: Record<string, any> & SharedProps) => void,
51
+ get_data: Function
52
+ ) => void;
53
+ dispatcher: Function;
54
+ }
55
+
56
+ export type LoadingComponent = Promise<{
57
+ default: Component;
58
+ }>;
59
+
60
+ export const GRADIO_ROOT = "GRADIO_ROOT";
61
+
62
+ export interface ValueData {
63
+ value: any;
64
+ is_value_data: boolean;
65
+ }
66
+
67
+ export interface SelectData {
68
+ row_value?: any[];
69
+ col_value?: any[];
70
+ index: number | [number, number];
71
+ value: any;
72
+ selected?: boolean;
73
+ }
74
+
75
+ export interface LikeData {
76
+ index: number | [number, number];
77
+ value: any;
78
+ liked?: boolean | string;
79
+ }
80
+
81
+ export interface KeyUpData {
82
+ key: string;
83
+ input_value: string;
84
+ }
85
+
86
+ export interface ShareData {
87
+ description: string;
88
+ title?: string;
89
+ }
90
+
91
+ export interface CopyData {
92
+ value: string;
93
+ }
94
+
95
+ export class ShareError extends Error {
96
+ constructor(message: string) {
97
+ super(message);
98
+ this.name = "ShareError";
99
+ }
100
+ }
101
+
102
+ export async function uploadToHuggingFace(
103
+ data: string | { url?: string; path?: string },
104
+ type: "base64" | "url"
105
+ ): Promise<string> {
106
+ if (window.__gradio_space__ == null) {
107
+ throw new ShareError("Must be on Spaces to share.");
108
+ }
109
+ let blob: Blob;
110
+ let contentType: string;
111
+ let filename: string;
112
+ if (type === "url") {
113
+ let url: string;
114
+
115
+ if (typeof data === "object" && data.url) {
116
+ url = data.url;
117
+ } else if (typeof data === "string") {
118
+ url = data;
119
+ } else {
120
+ throw new Error("Invalid data format for URL type");
121
+ }
122
+
123
+ const response = await fetch(url);
124
+ blob = await response.blob();
125
+ contentType = response.headers.get("content-type") || "";
126
+ filename = response.headers.get("content-disposition") || "";
127
+ } else {
128
+ let dataurl: string;
129
+
130
+ if (typeof data === "object" && data.path) {
131
+ dataurl = data.path;
132
+ } else if (typeof data === "string") {
133
+ dataurl = data;
134
+ } else {
135
+ throw new Error("Invalid data format for base64 type");
136
+ }
137
+
138
+ blob = dataURLtoBlob(dataurl);
139
+ contentType = dataurl.split(";")[0].split(":")[1];
140
+ filename = "file." + contentType.split("/")[1];
141
+ }
142
+
143
+ const file = new File([blob], filename, { type: contentType });
144
+
145
+ // Send file to endpoint
146
+ const uploadResponse = await fetch("https://huggingface.co/uploads", {
147
+ method: "POST",
148
+ body: file,
149
+ headers: {
150
+ "Content-Type": file.type,
151
+ "X-Requested-With": "XMLHttpRequest"
152
+ }
153
+ });
154
+
155
+ // Check status of response
156
+ if (!uploadResponse.ok) {
157
+ if (
158
+ uploadResponse.headers.get("content-type")?.includes("application/json")
159
+ ) {
160
+ const error = await uploadResponse.json();
161
+ throw new ShareError(`Upload failed: ${error.error}`);
162
+ }
163
+ throw new ShareError(`Upload failed.`);
164
+ }
165
+
166
+ // Return response if needed
167
+ const result = await uploadResponse.text();
168
+ return result;
169
+ }
170
+
171
+ function dataURLtoBlob(dataurl: string): Blob {
172
+ var arr = dataurl.split(","),
173
+ mime = (arr[0].match(/:(.*?);/) as RegExpMatchArray)[1],
174
+ bstr = atob(arr[1]),
175
+ n = bstr.length,
176
+ u8arr = new Uint8Array(n);
177
+ while (n--) {
178
+ u8arr[n] = bstr.charCodeAt(n);
179
+ }
180
+ return new Blob([u8arr], { type: mime });
181
+ }
182
+
183
+ export function copy(node: HTMLDivElement): ActionReturn {
184
+ node.addEventListener("click", handle_copy);
185
+
186
+ async function handle_copy(event: MouseEvent): Promise<void> {
187
+ const path = event.composedPath() as HTMLButtonElement[];
188
+
189
+ const [copy_button] = path.filter(
190
+ (e) => e?.tagName === "BUTTON" && e.classList.contains("copy_code_button")
191
+ );
192
+
193
+ if (copy_button) {
194
+ event.stopImmediatePropagation();
195
+
196
+ const copy_text = copy_button.parentElement!.innerText.trim();
197
+ const copy_sucess_button = Array.from(
198
+ copy_button.children
199
+ )[1] as HTMLDivElement;
200
+
201
+ const copied = await copy_to_clipboard(copy_text);
202
+
203
+ if (copied) copy_feedback(copy_sucess_button);
204
+
205
+ function copy_feedback(_copy_sucess_button: HTMLDivElement): void {
206
+ _copy_sucess_button.style.opacity = "1";
207
+ setTimeout(() => {
208
+ _copy_sucess_button.style.opacity = "0";
209
+ }, 2000);
210
+ }
211
+ }
212
+ }
213
+
214
+ return {
215
+ destroy(): void {
216
+ node.removeEventListener("click", handle_copy);
217
+ }
218
+ };
219
+ }
220
+
221
+ async function copy_to_clipboard(value: string): Promise<boolean> {
222
+ let copied = false;
223
+ if ("clipboard" in navigator) {
224
+ await navigator.clipboard.writeText(value);
225
+ copied = true;
226
+ } else {
227
+ const textArea = document.createElement("textarea");
228
+ textArea.value = value;
229
+
230
+ textArea.style.position = "absolute";
231
+ textArea.style.left = "-999999px";
232
+
233
+ document.body.prepend(textArea);
234
+ textArea.select();
235
+
236
+ try {
237
+ document.execCommand("copy");
238
+ copied = true;
239
+ } catch (error) {
240
+ console.error(error);
241
+ copied = false;
242
+ } finally {
243
+ textArea.remove();
244
+ }
245
+ }
246
+
247
+ return copied;
248
+ }
249
+
250
+ export const format_time = (seconds: number): string => {
251
+ const hours = Math.floor(seconds / 3600);
252
+ const minutes = Math.floor((seconds % 3600) / 60);
253
+ const seconds_remainder = Math.round(seconds) % 60;
254
+ const padded_minutes = `${minutes < 10 ? "0" : ""}${minutes}`;
255
+ const padded_seconds = `${
256
+ seconds_remainder < 10 ? "0" : ""
257
+ }${seconds_remainder}`;
258
+
259
+ if (hours > 0) {
260
+ return `${hours}:${padded_minutes}:${padded_seconds}`;
261
+ }
262
+ return `${minutes}:${padded_seconds}`;
263
+ };
264
+
265
+ interface Args {
266
+ api_url: string;
267
+ name: string;
268
+ id?: string;
269
+ variant: "component" | "example" | "base";
270
+ }
271
+
272
+ export type component_loader = (args: Args) => {
273
+ component: {
274
+ default: ComponentType<SvelteComponent>;
275
+ };
276
+ };
277
+
278
+ export type LoadedComponentWithRuntime = {
279
+ component: LoadingComponent;
280
+ runtime: false | typeof import("svelte");
281
+ };
282
+
283
+ export type load_component = (
284
+ name: string,
285
+ variant: "component" | "example" | "base",
286
+ component_class_id?: string
287
+ ) => LoadedComponentWithRuntime;
288
+
289
+ const is_browser = typeof window !== "undefined";
290
+
291
+ export type ServerFunctions = Record<string, (...args: any[]) => Promise<any>>;
292
+
293
+ export const allowed_shared_props: (keyof SharedProps)[] = [
294
+ "elem_id",
295
+ "elem_classes",
296
+ "visible",
297
+ "interactive",
298
+ "server_fns",
299
+ "server",
300
+ "id",
301
+ "target",
302
+ "theme_mode",
303
+ "version",
304
+ "root",
305
+ "autoscroll",
306
+ "max_file_size",
307
+ "formatter",
308
+ "client",
309
+ "load_component",
310
+ "scale",
311
+ "min_width",
312
+ "theme",
313
+ "padding",
314
+ "loading_status",
315
+ "label",
316
+ "show_label",
317
+ "validation_error",
318
+ "show_progress",
319
+ "api_prefix",
320
+ "container",
321
+ "attached_events",
322
+ "register_component",
323
+ "dispatcher"
324
+ ] as const;
325
+
326
+ export type I18nFormatter = any;
327
+
328
+ export function has_i18n_marker(value: unknown): value is string {
329
+ return typeof value === "string" && value.includes(I18N_MARKER);
330
+ }
331
+
332
+ export function translate_i18n_marker(
333
+ value: string,
334
+ translate: (key: string) => string
335
+ ): string {
336
+ const start = value.indexOf(I18N_MARKER);
337
+ if (start === -1) return value;
338
+
339
+ const json_start = start + I18N_MARKER.length;
340
+ const json_end = value.indexOf("}", json_start) + 1;
341
+ if (json_end === 0) return value;
342
+
343
+ try {
344
+ const metadata = JSON.parse(value.slice(json_start, json_end));
345
+ if (metadata?.key) {
346
+ const translated = translate(metadata.key);
347
+ const result = translated !== metadata.key ? translated : metadata.key;
348
+ return value.slice(0, start) + result + value.slice(json_end);
349
+ }
350
+ } catch {}
351
+
352
+ return value;
353
+ }
354
+
355
+ export class Gradio<T extends object = {}, U extends object = {}> {
356
+ load_component: load_component;
357
+ shared: SharedProps = $state<SharedProps>({} as SharedProps) as SharedProps;
358
+ props = $state<U>({} as U) as U;
359
+ i18n: I18nFormatter = $state<any>((v: string) => v) as any;
360
+ translatable_props: Record<string, string> = {};
361
+ dispatcher!: Function;
362
+ last_update: ReturnType<typeof tick> | null = null;
363
+ shared_props: (keyof SharedProps)[] = allowed_shared_props;
364
+ register_component!: (
365
+ id: number,
366
+ set_data: (data: Record<string, any> & SharedProps) => void,
367
+ get_data: Function
368
+ ) => void;
369
+
370
+ constructor(
371
+ _props: { shared_props: SharedProps; props: U },
372
+ default_values?: Partial<U>
373
+ ) {
374
+ for (const key in _props.shared_props) {
375
+ // @ts-ignore i'm not doing pointless typescript gymanstics
376
+ this.shared[key] = _props.shared_props[key];
377
+ }
378
+ for (const key in _props.props) {
379
+ // @ts-ignore same here
380
+ this.props[key] = _props.props[key];
381
+ }
382
+
383
+ if (default_values) {
384
+ for (const key in default_values) {
385
+ if (this.props[key as keyof U] === undefined) {
386
+ // @ts-ignore
387
+ this.props[key] = default_values[key as keyof U];
388
+ }
389
+ }
390
+ }
391
+ // @ts-ignore same here
392
+ this.i18n = this.props.i18n ?? ((v: string) => v);
393
+
394
+ for (const key of TRANSLATABLE_PROPS) {
395
+ // @ts-ignore
396
+ this.shared[key] = this._translate_and_store(
397
+ "shared",
398
+ key,
399
+ // @ts-ignore
400
+ _props.shared_props[key]
401
+ );
402
+ // @ts-ignore
403
+ this.props[key] = this._translate_and_store(
404
+ "props",
405
+ key,
406
+ // @ts-ignore
407
+ _props.props[key]
408
+ );
409
+ }
410
+
411
+ this.load_component = this.shared.load_component;
412
+
413
+ this.register_component = this.shared.register_component || (() => {});
414
+ this.dispatcher = this.shared.dispatcher || (() => {});
415
+
416
+ this.register_component(
417
+ _props.shared_props.id,
418
+ // @ts-ignore
419
+ this.set_data.bind(this),
420
+ this.get_data.bind(this)
421
+ );
422
+
423
+ $effect(() => {
424
+ // Need to update the props here
425
+ // otherwise UI won't reflect latest state from render
426
+ for (const key in _props.shared_props) {
427
+ // @ts-ignore
428
+ if (this._is_i18n_managed(`shared.${key}`, _props.shared_props[key]))
429
+ continue;
430
+ // @ts-ignore i'm not doing pointless typescript gymanstics
431
+ this.shared[key] = _props.shared_props[key];
432
+ }
433
+ for (const key in _props.props) {
434
+ if (this._is_i18n_managed(`props.${key}`, _props.props[key])) continue;
435
+ // @ts-ignore same here
436
+ this.props[key] = _props.props[key];
437
+ }
438
+ this.register_component(
439
+ _props.shared_props.id,
440
+ // @ts-ignore
441
+ this.set_data.bind(this),
442
+ this.get_data.bind(this)
443
+ );
444
+ untrack(() => {
445
+ this.shared.id = _props.shared_props.id;
446
+ });
447
+ });
448
+
449
+ // retranslate props when locale changes
450
+ if (Object.keys(this.translatable_props).length > 0) {
451
+ locale.subscribe(() => {
452
+ for (const [full_key, original] of Object.entries(
453
+ this.translatable_props
454
+ )) {
455
+ const [target, key] = full_key.split(".");
456
+ const translated = this.i18n(original);
457
+ // @ts-ignore
458
+ if (target === "shared") this.shared[key] = translated;
459
+ // @ts-ignore
460
+ else this.props[key] = translated;
461
+ }
462
+ });
463
+ }
464
+ }
465
+
466
+ // check if props are translatable
467
+ _is_i18n_managed(key: string, new_value: unknown): boolean {
468
+ const original_marker = this.translatable_props[key];
469
+ if (!original_marker) return false;
470
+ if (new_value === original_marker) return true;
471
+ // if value has changed then remove key
472
+ delete this.translatable_props[key];
473
+ return false;
474
+ }
475
+
476
+ _translate_and_store(
477
+ target: "shared" | "props",
478
+ key: string,
479
+ value: unknown
480
+ ): unknown {
481
+ if (typeof value !== "string") return value;
482
+ const translated = this.i18n(value);
483
+ if (translated !== value) {
484
+ this.translatable_props[`${target}.${key}`] = value;
485
+ }
486
+ return translated;
487
+ }
488
+
489
+ dispatch<E extends keyof T>(event_name: E, data?: T[E]): void {
490
+ this.dispatcher(this.shared.id, event_name, data);
491
+ }
492
+
493
+ async get_data() {
494
+ return $state.snapshot(this.props);
495
+ }
496
+
497
+ update(data: Partial<U & SharedProps>): void {
498
+ this.set_data(data as U & SharedProps);
499
+ }
500
+
501
+ set_data(data: Partial<U & SharedProps>): void {
502
+ for (const key in data) {
503
+ // @ts-ignore
504
+ const value = data[key];
505
+ const translated = has_i18n_marker(value)
506
+ ? this._translate_and_store(
507
+ this.shared_props.includes(key as keyof SharedProps)
508
+ ? "shared"
509
+ : "props",
510
+ key,
511
+ value
512
+ )
513
+ : value;
514
+
515
+ if (this.shared_props.includes(key as keyof SharedProps)) {
516
+ const _key = key as keyof SharedProps;
517
+ // @ts-ignore i'm not doing pointless typescript gymanstics
518
+ this.shared[_key] = translated;
519
+ continue;
520
+ }
521
+ // @ts-ignore
522
+ this.props[key] = translated;
523
+ }
524
+ }
525
+ }
526
+
527
+ // function _load_component(
528
+ // this: Gradio,
529
+ // name: string,
530
+ // variant: "component" | "example" | "base" = "component"
531
+ // ): ReturnType<component_loader> {
532
+ // return this._load_component!({
533
+ // name,
534
+ // api_url: this.shared.client.config?.root!,
535
+ // variant
536
+ // });
537
+ // }
538
+
539
+ export const css_units = (dimension_value: string | number): string => {
540
+ return typeof dimension_value === "number"
541
+ ? dimension_value + "px"
542
+ : dimension_value;
543
+ };
544
+
545
+ export function should_show_scroll_fade(
546
+ container: HTMLElement | null
547
+ ): boolean {
548
+ if (!container) return false;
549
+ const has_overflow = container.scrollHeight > container.clientHeight;
550
+ const at_bottom =
551
+ container.scrollTop >= container.scrollHeight - container.clientHeight - 1;
552
+ return has_overflow && !at_bottom;
553
+ }
554
+
555
+ type MappedProps<T> = { [K in keyof T]: T[K] };
556
+ type MappedProp<T, K extends keyof T> = { [P in K]: T[P] };