gradio-pr-bot commited on
Commit
d2f94a4
·
verified ·
1 Parent(s): 3fb1ca4

Upload folder using huggingface_hub

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