gradio-pr-bot commited on
Commit
dbc4841
·
verified ·
1 Parent(s): 06be0f4

Upload folder using huggingface_hub

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