@gradio/client 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +49 -43
  3. package/dist/client.d.ts +63 -70
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/constants.d.ts +23 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/helpers/api_info.d.ts +25 -0
  8. package/dist/helpers/api_info.d.ts.map +1 -0
  9. package/dist/helpers/data.d.ts +8 -0
  10. package/dist/helpers/data.d.ts.map +1 -0
  11. package/dist/{utils.d.ts → helpers/init_helpers.d.ts} +6 -18
  12. package/dist/helpers/init_helpers.d.ts.map +1 -0
  13. package/dist/helpers/spaces.d.ts +7 -0
  14. package/dist/helpers/spaces.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1628 -1398
  18. package/dist/test/handlers.d.ts +3 -0
  19. package/dist/test/handlers.d.ts.map +1 -0
  20. package/dist/test/mock_eventsource.d.ts +2 -0
  21. package/dist/test/mock_eventsource.d.ts.map +1 -0
  22. package/dist/test/server.d.ts +2 -0
  23. package/dist/test/server.d.ts.map +1 -0
  24. package/dist/test/test_data.d.ts +76 -0
  25. package/dist/test/test_data.d.ts.map +1 -0
  26. package/dist/types.d.ts +153 -49
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/upload.d.ts +2 -2
  29. package/dist/upload.d.ts.map +1 -1
  30. package/dist/utils/duplicate.d.ts +4 -0
  31. package/dist/utils/duplicate.d.ts.map +1 -0
  32. package/dist/utils/handle_blob.d.ts +4 -0
  33. package/dist/utils/handle_blob.d.ts.map +1 -0
  34. package/dist/utils/post_data.d.ts +4 -0
  35. package/dist/utils/post_data.d.ts.map +1 -0
  36. package/dist/utils/predict.d.ts +4 -0
  37. package/dist/utils/predict.d.ts.map +1 -0
  38. package/dist/utils/stream.d.ts +8 -0
  39. package/dist/utils/stream.d.ts.map +1 -0
  40. package/dist/utils/submit.d.ts +4 -0
  41. package/dist/utils/submit.d.ts.map +1 -0
  42. package/dist/utils/upload_files.d.ts +4 -0
  43. package/dist/utils/upload_files.d.ts.map +1 -0
  44. package/dist/utils/view_api.d.ts +3 -0
  45. package/dist/utils/view_api.d.ts.map +1 -0
  46. package/dist/{wrapper-6f348d45.js → wrapper-CviSselG.js} +259 -17
  47. package/package.json +10 -3
  48. package/src/client.ts +314 -1691
  49. package/src/constants.ts +27 -0
  50. package/src/globals.d.ts +2 -21
  51. package/src/helpers/api_info.ts +300 -0
  52. package/src/helpers/data.ts +133 -0
  53. package/src/helpers/init_helpers.ts +130 -0
  54. package/src/helpers/spaces.ts +197 -0
  55. package/src/index.ts +16 -10
  56. package/src/test/api_info.test.ts +456 -0
  57. package/src/test/data.test.ts +281 -0
  58. package/src/test/handlers.ts +438 -0
  59. package/src/test/init.test.ts +139 -0
  60. package/src/test/init_helpers.test.ts +94 -0
  61. package/src/test/mock_eventsource.ts +11 -0
  62. package/src/test/post_data.test.ts +45 -0
  63. package/src/test/server.ts +6 -0
  64. package/src/test/spaces.test.ts +145 -0
  65. package/src/test/stream.test.ts +67 -0
  66. package/src/test/test_data.ts +557 -0
  67. package/src/test/upload_files.test.ts +42 -0
  68. package/src/test/view_api.test.ts +53 -0
  69. package/src/types.ts +201 -59
  70. package/src/upload.ts +19 -15
  71. package/src/utils/duplicate.ts +104 -0
  72. package/src/utils/handle_blob.ts +47 -0
  73. package/src/utils/post_data.ts +37 -0
  74. package/src/utils/predict.ts +56 -0
  75. package/src/utils/stream.ts +175 -0
  76. package/src/utils/submit.ts +697 -0
  77. package/src/utils/upload_files.ts +51 -0
  78. package/src/utils/view_api.ts +67 -0
  79. package/src/vite-env.d.ts +1 -0
  80. package/tsconfig.json +15 -2
  81. package/vite.config.js +11 -17
  82. package/dist/utils.d.ts.map +0 -1
  83. package/src/client.node-test.ts +0 -172
  84. package/src/utils.ts +0 -314
@@ -0,0 +1,51 @@
1
+ import type { Client } from "..";
2
+ import { BROKEN_CONNECTION_MSG, UPLOAD_URL } from "../constants";
3
+ import type { UploadResponse } from "../types";
4
+
5
+ export async function upload_files(
6
+ this: Client,
7
+ root_url: string,
8
+ files: (Blob | File)[],
9
+ upload_id?: string
10
+ ): Promise<UploadResponse> {
11
+ const headers: {
12
+ Authorization?: string;
13
+ } = {};
14
+ if (this?.options?.hf_token) {
15
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
16
+ }
17
+
18
+ const chunkSize = 1000;
19
+ const uploadResponses = [];
20
+ let response: Response;
21
+
22
+ for (let i = 0; i < files.length; i += chunkSize) {
23
+ const chunk = files.slice(i, i + chunkSize);
24
+ const formData = new FormData();
25
+ chunk.forEach((file) => {
26
+ formData.append("files", file);
27
+ });
28
+ try {
29
+ const upload_url = upload_id
30
+ ? `${root_url}/upload?upload_id=${upload_id}`
31
+ : `${root_url}/${UPLOAD_URL}`;
32
+
33
+ response = await this.fetch(upload_url, {
34
+ method: "POST",
35
+ body: formData,
36
+ headers
37
+ });
38
+ } catch (e) {
39
+ throw new Error(BROKEN_CONNECTION_MSG + (e as Error).message);
40
+ }
41
+ if (!response.ok) {
42
+ const error_text = await response.text();
43
+ return { error: `HTTP ${response.status}: ${error_text}` };
44
+ }
45
+ const output: UploadResponse["files"] = await response.json();
46
+ if (output) {
47
+ uploadResponses.push(...output);
48
+ }
49
+ }
50
+ return { files: uploadResponses };
51
+ }
@@ -0,0 +1,67 @@
1
+ import type { ApiInfo, ApiData } from "../types";
2
+ import semiver from "semiver";
3
+ import { API_INFO_URL, BROKEN_CONNECTION_MSG } from "../constants";
4
+ import { Client } from "../client";
5
+ import { SPACE_FETCHER_URL } from "../constants";
6
+ import { transform_api_info } from "../helpers/api_info";
7
+
8
+ export async function view_api(this: Client): Promise<any> {
9
+ if (this.api_info) return this.api_info;
10
+
11
+ const { hf_token } = this.options;
12
+ const { config } = this;
13
+
14
+ const headers: {
15
+ Authorization?: string;
16
+ "Content-Type": "application/json";
17
+ } = { "Content-Type": "application/json" };
18
+
19
+ if (hf_token) {
20
+ headers.Authorization = `Bearer ${hf_token}`;
21
+ }
22
+
23
+ if (!config) {
24
+ return;
25
+ }
26
+
27
+ try {
28
+ let response: Response;
29
+
30
+ if (semiver(config?.version || "2.0.0", "3.30") < 0) {
31
+ response = await this.fetch(SPACE_FETCHER_URL, {
32
+ method: "POST",
33
+ body: JSON.stringify({
34
+ serialize: false,
35
+ config: JSON.stringify(config)
36
+ }),
37
+ headers
38
+ });
39
+ } else {
40
+ response = await this.fetch(`${config?.root}/${API_INFO_URL}`, {
41
+ headers
42
+ });
43
+ }
44
+
45
+ if (!response.ok) {
46
+ throw new Error(BROKEN_CONNECTION_MSG);
47
+ }
48
+
49
+ let api_info = (await response.json()) as
50
+ | ApiInfo<ApiData>
51
+ | { api: ApiInfo<ApiData> };
52
+ if ("api" in api_info) {
53
+ api_info = api_info.api;
54
+ }
55
+
56
+ if (
57
+ api_info.named_endpoints["/predict"] &&
58
+ !api_info.unnamed_endpoints["0"]
59
+ ) {
60
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
61
+ }
62
+
63
+ return transform_api_info(api_info, config, this.api_map);
64
+ } catch (e) {
65
+ "Could not get API info. " + (e as Error).message;
66
+ }
67
+ }
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
package/tsconfig.json CHANGED
@@ -7,8 +7,21 @@
7
7
  "emitDeclarationOnly": true,
8
8
  "outDir": "dist",
9
9
  "declarationMap": true,
10
- "module": "es2020",
10
+ "module": "ESNext",
11
+ "target": "ES2020",
12
+ "useDefineForClassFields": true,
13
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
14
+ "skipLibCheck": true,
15
+
16
+ /* Bundler */
11
17
  "moduleResolution": "bundler",
12
- "skipDefaultLibCheck": true
18
+ "skipDefaultLibCheck": true,
19
+ "allowImportingTsExtensions": true,
20
+ "esModuleInterop": true,
21
+ "resolveJsonModule": true,
22
+ "isolatedModules": true,
23
+
24
+ /* Linting */
25
+ "strict": true
13
26
  }
14
27
  }
package/vite.config.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { defineConfig } from "vite";
2
2
  import { svelte } from "@sveltejs/vite-plugin-svelte";
3
- import { fileURLToPath } from "url";
4
- import path from "path";
5
- const __dirname = fileURLToPath(new URL(".", import.meta.url));
3
+
4
+ const TEST_MODE = process.env.TEST_MODE || "happy-dom";
6
5
 
7
6
  export default defineConfig({
8
7
  build: {
9
8
  lib: {
10
9
  entry: "src/index.ts",
11
- formats: ["es"]
10
+ formats: ["es"],
11
+ fileName: (format) => `index.${format}.js`
12
12
  },
13
13
  rollupOptions: {
14
14
  input: "src/index.ts",
@@ -17,22 +17,16 @@ export default defineConfig({
17
17
  }
18
18
  }
19
19
  },
20
- plugins: [
21
- svelte()
22
- // {
23
- // name: "resolve-gradio-client",
24
- // enforce: "pre",
25
- // resolveId(id) {
26
- // if (id === "@gradio/client") {
27
- // return path.join(__dirname, "src", "index.ts");
28
- // }
29
- // }
30
- // }
31
- ],
20
+ plugins: [svelte()],
32
21
 
22
+ mode: process.env.MODE || "development",
23
+ test: {
24
+ include: ["./src/test/*.test.*"],
25
+ environment: TEST_MODE
26
+ },
33
27
  ssr: {
34
28
  target: "node",
35
29
  format: "esm",
36
- noExternal: ["ws", "semiver", "@gradio/upload"]
30
+ noExternal: ["ws", "semiver", "bufferutil", "@gradio/upload"]
37
31
  }
38
32
  });
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACtB,MAAM,CAKR;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACrD,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;CACb,CAgCA;AAED,eAAO,MAAM,aAAa,QAAqB,CAAC;AAChD,eAAO,MAAM,eAAe,QAAwB,CAAC;AACrD,wBAAsB,gBAAgB,CACrC,aAAa,EAAE,MAAM,EACrB,KAAK,CAAC,EAAE,MAAM,MAAM,EAAE,GACpB,OAAO,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;CAClC,CAAC,CA4CD;AAED,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,MAAM,CAAC,cAAc,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB;AAID,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAe5E;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAqB1C;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,EAC7C,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAuB1C;AAED,wBAAsB,iBAAiB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,MAAM,CAAC,CAuBjB;AAED,eAAO,MAAM,cAAc,0GAQjB,CAAC;AAkDX,wBAAgB,UAAU,CACzB,GAAG,EAAE,GAAG,EACR,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,GACxC,GAAG,CAML;AAED,wBAAgB,YAAY,CAAC,GAAG,GAAG,GAAG,EACrC,OAAO,EAAE,GAAG,EACZ,MAAM,EAAE,MAAM,GACZ,OAAO,CAAC,GAAG,CAAC,CASd"}
@@ -1,172 +0,0 @@
1
- import { test, describe, assert } from "vitest";
2
- import { readFileSync } from "fs";
3
- import { join, dirname } from "path";
4
- import { fileURLToPath } from "url";
5
- import { Blob } from "node:buffer";
6
-
7
- const __dirname = dirname(fileURLToPath(import.meta.url));
8
- const image_path = join(
9
- __dirname,
10
- "..",
11
- "..",
12
- "..",
13
- "demo",
14
- "kitchen_sink",
15
- "files",
16
- "lion.jpg"
17
- );
18
-
19
- import { walk_and_store_blobs, client, handle_blob } from "./client";
20
-
21
- describe.skip("extract blob parts", () => {
22
- test("convert Buffer to Blob", async () => {
23
- const image = readFileSync(image_path);
24
- await client("gradio/hello_world_main");
25
- const parts = walk_and_store_blobs({
26
- data: {
27
- image
28
- }
29
- });
30
-
31
- assert.isTrue(parts[0].blob instanceof Blob);
32
- });
33
-
34
- test("leave node Blob as Blob", async () => {
35
- const image = new Blob([readFileSync(image_path)]);
36
-
37
- await client("gradio/hello_world_main");
38
- const parts = walk_and_store_blobs({
39
- data: {
40
- image
41
- }
42
- });
43
-
44
- assert.isTrue(parts[0].blob instanceof Blob);
45
- });
46
-
47
- test("handle deep structures", async () => {
48
- const image = new Blob([readFileSync(image_path)]);
49
-
50
- await client("gradio/hello_world_main");
51
- const parts = walk_and_store_blobs({
52
- a: {
53
- b: {
54
- data: {
55
- image
56
- }
57
- }
58
- }
59
- });
60
-
61
- assert.isTrue(parts[0].blob instanceof Blob);
62
- });
63
-
64
- test("handle deep structures with arrays", async () => {
65
- const image = new Blob([readFileSync(image_path)]);
66
-
67
- await client("gradio/hello_world_main");
68
- const parts = walk_and_store_blobs({
69
- a: [
70
- {
71
- b: [
72
- {
73
- data: [
74
- {
75
- image
76
- }
77
- ]
78
- }
79
- ]
80
- }
81
- ]
82
- });
83
-
84
- assert.isTrue(parts[0].blob instanceof Blob);
85
- });
86
-
87
- test("handle deep structures with arrays 2", async () => {
88
- const image = new Blob([readFileSync(image_path)]);
89
-
90
- await client("gradio/hello_world_main");
91
- const obj = {
92
- a: [
93
- {
94
- b: [
95
- {
96
- data: [[image], image, [image, [image]]]
97
- }
98
- ]
99
- }
100
- ]
101
- };
102
- const parts = walk_and_store_blobs(obj);
103
-
104
- function map_path(
105
- obj: Record<string, any>,
106
- parts: { path: string[]; blob: any }[]
107
- ) {
108
- const { path, blob } = parts[parts.length - 1];
109
- let ref = obj;
110
- path.forEach((p) => (ref = ref[p]));
111
-
112
- return ref === blob;
113
- }
114
-
115
- assert.isTrue(parts[0].blob instanceof Blob);
116
- // assert.isTrue(map_path(obj, parts));
117
- });
118
- });
119
-
120
- describe("handle_blob", () => {
121
- test("handle blobs", async () => {
122
- const image = new Blob([readFileSync(image_path)]);
123
-
124
- const app = await client("gradio/hello_world_main");
125
- const obj = [
126
- {
127
- a: [
128
- {
129
- b: [
130
- {
131
- data: [[image], image, [image, [image]]]
132
- }
133
- ]
134
- }
135
- ]
136
- }
137
- ];
138
-
139
- const parts = await handle_blob(app.config.root, obj, undefined);
140
- //@ts-ignore
141
- // assert.isString(parts.data[0].a[0].b[0].data[0][0]);
142
- });
143
- });
144
-
145
- describe.skip("private space", () => {
146
- test("can access a private space", async () => {
147
- const image = new Blob([readFileSync(image_path)]);
148
-
149
- const app = await client("pngwn/hello_world", {
150
- hf_token: "hf_"
151
- });
152
-
153
- console.log(app);
154
- const obj = [
155
- {
156
- a: [
157
- {
158
- b: [
159
- {
160
- data: [[image], image, [image, [image]]]
161
- }
162
- ]
163
- }
164
- ]
165
- }
166
- ];
167
-
168
- const parts = await handle_blob(app.config.root, obj, "hf_");
169
- //@ts-ignore
170
- assert.isString(parts.data[0].a[0].b[0].data[0][0]);
171
- });
172
- });
package/src/utils.ts DELETED
@@ -1,314 +0,0 @@
1
- import type { Config } from "./types.js";
2
-
3
- /**
4
- * This function is used to resolve the URL for making requests when the app has a root path.
5
- * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or
6
- * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting
7
- * Gradio apps on Hugging Face Spaces.
8
- * @param {string} base_url The base URL at which the Gradio server is hosted
9
- * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces)
10
- * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized.
11
- * @returns {string} the resolved URL
12
- */
13
- export function resolve_root(
14
- base_url: string,
15
- root_path: string,
16
- prioritize_base: boolean
17
- ): string {
18
- if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
19
- return prioritize_base ? base_url : root_path;
20
- }
21
- return base_url + root_path;
22
- }
23
-
24
- export function determine_protocol(endpoint: string): {
25
- ws_protocol: "ws" | "wss";
26
- http_protocol: "http:" | "https:";
27
- host: string;
28
- } {
29
- if (endpoint.startsWith("http")) {
30
- const { protocol, host } = new URL(endpoint);
31
-
32
- if (host.endsWith("hf.space")) {
33
- return {
34
- ws_protocol: "wss",
35
- host: host,
36
- http_protocol: protocol as "http:" | "https:"
37
- };
38
- }
39
- return {
40
- ws_protocol: protocol === "https:" ? "wss" : "ws",
41
- http_protocol: protocol as "http:" | "https:",
42
- host
43
- };
44
- } else if (endpoint.startsWith("file:")) {
45
- // This case is only expected to be used for the Wasm mode (Gradio-lite),
46
- // where users can create a local HTML file using it and open the page in a browser directly via the `file:` protocol.
47
- return {
48
- ws_protocol: "ws",
49
- http_protocol: "http:",
50
- host: "lite.local" // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`.
51
- };
52
- }
53
-
54
- // default to secure if no protocol is provided
55
- return {
56
- ws_protocol: "wss",
57
- http_protocol: "https:",
58
- host: endpoint
59
- };
60
- }
61
-
62
- export const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
63
- export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
64
- export async function process_endpoint(
65
- app_reference: string,
66
- token?: `hf_${string}`
67
- ): Promise<{
68
- space_id: string | false;
69
- host: string;
70
- ws_protocol: "ws" | "wss";
71
- http_protocol: "http:" | "https:";
72
- }> {
73
- const headers: { Authorization?: string } = {};
74
- if (token) {
75
- headers.Authorization = `Bearer ${token}`;
76
- }
77
-
78
- const _app_reference = app_reference.trim();
79
-
80
- if (RE_SPACE_NAME.test(_app_reference)) {
81
- try {
82
- const res = await fetch(
83
- `https://huggingface.co/api/spaces/${_app_reference}/host`,
84
- { headers }
85
- );
86
-
87
- if (res.status !== 200)
88
- throw new Error("Space metadata could not be loaded.");
89
- const _host = (await res.json()).host;
90
-
91
- return {
92
- space_id: app_reference,
93
- ...determine_protocol(_host)
94
- };
95
- } catch (e: any) {
96
- throw new Error("Space metadata could not be loaded." + e.message);
97
- }
98
- }
99
-
100
- if (RE_SPACE_DOMAIN.test(_app_reference)) {
101
- const { ws_protocol, http_protocol, host } =
102
- determine_protocol(_app_reference);
103
-
104
- return {
105
- space_id: host.replace(".hf.space", ""),
106
- ws_protocol,
107
- http_protocol,
108
- host
109
- };
110
- }
111
-
112
- return {
113
- space_id: false,
114
- ...determine_protocol(_app_reference)
115
- };
116
- }
117
-
118
- export function map_names_to_ids(
119
- fns: Config["dependencies"]
120
- ): Record<string, number> {
121
- let apis: Record<string, number> = {};
122
-
123
- fns.forEach(({ api_name }, i) => {
124
- if (api_name) apis[api_name] = i;
125
- });
126
-
127
- return apis;
128
- }
129
-
130
- const RE_DISABLED_DISCUSSION =
131
- /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
132
- export async function discussions_enabled(space_id: string): Promise<boolean> {
133
- try {
134
- const r = await fetch(
135
- `https://huggingface.co/api/spaces/${space_id}/discussions`,
136
- {
137
- method: "HEAD"
138
- }
139
- );
140
- const error = r.headers.get("x-error-message");
141
-
142
- if (error && RE_DISABLED_DISCUSSION.test(error)) return false;
143
- return true;
144
- } catch (e) {
145
- return false;
146
- }
147
- }
148
-
149
- export async function get_space_hardware(
150
- space_id: string,
151
- token: `hf_${string}`
152
- ): Promise<(typeof hardware_types)[number]> {
153
- const headers: { Authorization?: string } = {};
154
- if (token) {
155
- headers.Authorization = `Bearer ${token}`;
156
- }
157
-
158
- try {
159
- const res = await fetch(
160
- `https://huggingface.co/api/spaces/${space_id}/runtime`,
161
- { headers }
162
- );
163
-
164
- if (res.status !== 200)
165
- throw new Error("Space hardware could not be obtained.");
166
-
167
- const { hardware } = await res.json();
168
-
169
- return hardware;
170
- } catch (e: any) {
171
- throw new Error(e.message);
172
- }
173
- }
174
-
175
- export async function set_space_hardware(
176
- space_id: string,
177
- new_hardware: (typeof hardware_types)[number],
178
- token: `hf_${string}`
179
- ): Promise<(typeof hardware_types)[number]> {
180
- const headers: { Authorization?: string } = {};
181
- if (token) {
182
- headers.Authorization = `Bearer ${token}`;
183
- }
184
-
185
- try {
186
- const res = await fetch(
187
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
188
- { headers, body: JSON.stringify(new_hardware) }
189
- );
190
-
191
- if (res.status !== 200)
192
- throw new Error(
193
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
194
- );
195
-
196
- const { hardware } = await res.json();
197
-
198
- return hardware;
199
- } catch (e: any) {
200
- throw new Error(e.message);
201
- }
202
- }
203
-
204
- export async function set_space_timeout(
205
- space_id: string,
206
- timeout: number,
207
- token: `hf_${string}`
208
- ): Promise<number> {
209
- const headers: { Authorization?: string } = {};
210
- if (token) {
211
- headers.Authorization = `Bearer ${token}`;
212
- }
213
-
214
- try {
215
- const res = await fetch(
216
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
217
- { headers, body: JSON.stringify({ seconds: timeout }) }
218
- );
219
-
220
- if (res.status !== 200)
221
- throw new Error(
222
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
223
- );
224
-
225
- const { hardware } = await res.json();
226
-
227
- return hardware;
228
- } catch (e: any) {
229
- throw new Error(e.message);
230
- }
231
- }
232
-
233
- export const hardware_types = [
234
- "cpu-basic",
235
- "cpu-upgrade",
236
- "t4-small",
237
- "t4-medium",
238
- "a10g-small",
239
- "a10g-large",
240
- "a100-large"
241
- ] as const;
242
-
243
- function apply_edit(
244
- target: any,
245
- path: (number | string)[],
246
- action: string,
247
- value: any
248
- ): any {
249
- if (path.length === 0) {
250
- if (action === "replace") {
251
- return value;
252
- } else if (action === "append") {
253
- return target + value;
254
- }
255
- throw new Error(`Unsupported action: ${action}`);
256
- }
257
-
258
- let current = target;
259
- for (let i = 0; i < path.length - 1; i++) {
260
- current = current[path[i]];
261
- }
262
-
263
- const last_path = path[path.length - 1];
264
- switch (action) {
265
- case "replace":
266
- current[last_path] = value;
267
- break;
268
- case "append":
269
- current[last_path] += value;
270
- break;
271
- case "add":
272
- if (Array.isArray(current)) {
273
- current.splice(Number(last_path), 0, value);
274
- } else {
275
- current[last_path] = value;
276
- }
277
- break;
278
- case "delete":
279
- if (Array.isArray(current)) {
280
- current.splice(Number(last_path), 1);
281
- } else {
282
- delete current[last_path];
283
- }
284
- break;
285
- default:
286
- throw new Error(`Unknown action: ${action}`);
287
- }
288
- return target;
289
- }
290
-
291
- export function apply_diff(
292
- obj: any,
293
- diff: [string, (number | string)[], any][]
294
- ): any {
295
- diff.forEach(([action, path, value]) => {
296
- obj = apply_edit(obj, path, action, value);
297
- });
298
-
299
- return obj;
300
- }
301
-
302
- export function post_message<Res = any>(
303
- message: any,
304
- origin: string
305
- ): Promise<Res> {
306
- return new Promise((res, _rej) => {
307
- const channel = new MessageChannel();
308
- channel.port1.onmessage = (({ data }) => {
309
- channel.port1.close();
310
- res(data);
311
- }) as (ev: MessageEvent<Res>) => void;
312
- window.parent.postMessage(message, origin, [channel.port2]);
313
- });
314
- }