gradio-pr-bot commited on
Commit
7ea7a23
·
verified ·
1 Parent(s): 9b3883f

Upload folder using huggingface_hub

Browse files
6.14.0/utils/package.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/utils",
3
+ "version": "0.12.2",
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.14.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.14.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.14.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.14.0/utils/src/utils.svelte.ts ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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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
+ mounted: boolean = false;
365
+ old_value: any;
366
+ register_component!: (
367
+ id: number,
368
+ set_data: (data: Record<string, any> & SharedProps) => void,
369
+ get_data: Function
370
+ ) => void;
371
+
372
+ constructor(
373
+ _props: { shared_props: SharedProps; props: U },
374
+ default_values?: Partial<U>
375
+ ) {
376
+ for (const key in _props.shared_props) {
377
+ // @ts-ignore i'm not doing pointless typescript gymanstics
378
+ this.shared[key] = _props.shared_props[key];
379
+ }
380
+ for (const key in _props.props) {
381
+ // @ts-ignore same here
382
+ this.props[key] = _props.props[key];
383
+ }
384
+
385
+ if (default_values) {
386
+ for (const key in default_values) {
387
+ if (this.props[key as keyof U] === undefined) {
388
+ // @ts-ignore
389
+ this.props[key] = default_values[key as keyof U];
390
+ }
391
+ }
392
+ }
393
+ // @ts-ignore same here
394
+ this.i18n = this.props.i18n ?? ((v: string) => v);
395
+
396
+ for (const key of TRANSLATABLE_PROPS) {
397
+ // @ts-ignore
398
+ this.shared[key] = this._translate_and_store(
399
+ "shared",
400
+ key,
401
+ // @ts-ignore
402
+ _props.shared_props[key]
403
+ );
404
+ // @ts-ignore
405
+ this.props[key] = this._translate_and_store(
406
+ "props",
407
+ key,
408
+ // @ts-ignore
409
+ _props.props[key]
410
+ );
411
+ }
412
+
413
+ this.load_component = this.shared.load_component;
414
+
415
+ this.register_component = this.shared.register_component || (() => {});
416
+ this.dispatcher = this.shared.dispatcher || (() => {});
417
+
418
+ this.register_component(
419
+ _props.shared_props.id,
420
+ // @ts-ignore
421
+ this.set_data.bind(this),
422
+ this.get_data.bind(this)
423
+ );
424
+
425
+ $effect(() => {
426
+ // Need to update the props here
427
+ // otherwise UI won't reflect latest state from render
428
+ for (const key in _props.shared_props) {
429
+ // @ts-ignore
430
+ if (this._is_i18n_managed(`shared.${key}`, _props.shared_props[key]))
431
+ continue;
432
+ // @ts-ignore i'm not doing pointless typescript gymanstics
433
+ this.shared[key] = _props.shared_props[key];
434
+ }
435
+ for (const key in _props.props) {
436
+ if (this._is_i18n_managed(`props.${key}`, _props.props[key])) continue;
437
+ // @ts-ignore same here
438
+ this.props[key] = _props.props[key];
439
+ }
440
+ this.register_component(
441
+ _props.shared_props.id,
442
+ // @ts-ignore
443
+ this.set_data.bind(this),
444
+ this.get_data.bind(this)
445
+ );
446
+ untrack(() => {
447
+ this.shared.id = _props.shared_props.id;
448
+ });
449
+ });
450
+
451
+ // retranslate props when locale changes
452
+ if (Object.keys(this.translatable_props).length > 0) {
453
+ locale.subscribe(() => {
454
+ for (const [full_key, original] of Object.entries(
455
+ this.translatable_props
456
+ )) {
457
+ const [target, key] = full_key.split(".");
458
+ const translated = this.i18n(original);
459
+ // @ts-ignore
460
+ if (target === "shared") this.shared[key] = translated;
461
+ // @ts-ignore
462
+ else this.props[key] = translated;
463
+ }
464
+ });
465
+ }
466
+ }
467
+
468
+ // check if props are translatable
469
+ _is_i18n_managed(key: string, new_value: unknown): boolean {
470
+ const original_marker = this.translatable_props[key];
471
+ if (!original_marker) return false;
472
+ if (new_value === original_marker) return true;
473
+ // if value has changed then remove key
474
+ delete this.translatable_props[key];
475
+ return false;
476
+ }
477
+
478
+ _translate_and_store(
479
+ target: "shared" | "props",
480
+ key: string,
481
+ value: unknown
482
+ ): unknown {
483
+ if (typeof value !== "string") return value;
484
+ const translated = this.i18n(value);
485
+ if (translated !== value) {
486
+ this.translatable_props[`${target}.${key}`] = value;
487
+ }
488
+ return translated;
489
+ }
490
+
491
+ dispatch<E extends keyof T>(event_name: E, data?: T[E]): void {
492
+ this.dispatcher(this.shared.id, event_name, data);
493
+ }
494
+
495
+ async get_data() {
496
+ return $state.snapshot(this.props);
497
+ }
498
+
499
+ update(data: Partial<U & SharedProps>): void {
500
+ this.set_data(data as U & SharedProps);
501
+ }
502
+
503
+ set_data(data: Partial<U & SharedProps>): void {
504
+ for (const key in data) {
505
+ // @ts-ignore
506
+ const value = data[key];
507
+ const translated = has_i18n_marker(value)
508
+ ? this._translate_and_store(
509
+ this.shared_props.includes(key as keyof SharedProps)
510
+ ? "shared"
511
+ : "props",
512
+ key,
513
+ value
514
+ )
515
+ : value;
516
+
517
+ if (this.shared_props.includes(key as keyof SharedProps)) {
518
+ const _key = key as keyof SharedProps;
519
+ // @ts-ignore i'm not doing pointless typescript gymanstics
520
+ this.shared[_key] = translated;
521
+ continue;
522
+ }
523
+ // @ts-ignore
524
+ this.props[key] = translated;
525
+ }
526
+ }
527
+
528
+ watch_for_change() {
529
+ $effect(() => {
530
+ if (!this.mounted) {
531
+ // @ts-ignore
532
+ this.old_value = this.props.value;
533
+ this.mounted = true;
534
+ }
535
+ // @ts-ignore
536
+ if (this.old_value != this.props.value) {
537
+ // @ts-ignore
538
+ this.old_value = this.props.value;
539
+ // @ts-ignore
540
+ this.dispatch("change");
541
+ }
542
+ });
543
+ }
544
+ }
545
+
546
+ // function _load_component(
547
+ // this: Gradio,
548
+ // name: string,
549
+ // variant: "component" | "example" | "base" = "component"
550
+ // ): ReturnType<component_loader> {
551
+ // return this._load_component!({
552
+ // name,
553
+ // api_url: this.shared.client.config?.root!,
554
+ // variant
555
+ // });
556
+ // }
557
+
558
+ export const css_units = (dimension_value: string | number): string => {
559
+ return typeof dimension_value === "number"
560
+ ? dimension_value + "px"
561
+ : dimension_value;
562
+ };
563
+
564
+ export function should_show_scroll_fade(
565
+ container: HTMLElement | null
566
+ ): boolean {
567
+ if (!container) return false;
568
+ const has_overflow = container.scrollHeight > container.clientHeight;
569
+ const at_bottom =
570
+ container.scrollTop >= container.scrollHeight - container.clientHeight - 1;
571
+ return has_overflow && !at_bottom;
572
+ }
573
+
574
+ type MappedProps<T> = { [K in keyof T]: T[K] };
575
+ type MappedProp<T, K extends keyof T> = { [P in K]: T[P] };