Skip to content

Commit

Permalink
various client refactors + tweaks (#4357)
Browse files Browse the repository at this point in the history
* changeset

* Add a type annotation on the `api` variable to which the return value of `view_config()` is assigned, and update the type annotation and exception handling on `view_config` as well (#4311)

* Remove unnecessary @ts-ignore (#4314)

* Remove unnecessary Promise wrapping another promise (#4313)

* Remove unnecessary Promise wrapping another promise

* Remove an error handeler that may remove detailed error stacks

* changeset

* remove changeset

---------

Co-authored-by: pngwn <hello@pngwn.io>

* Stop using `let` for unchanged variables in `client.ts` (#4312)

* Stop using `let` for unchanged variables in `client.ts`

* fixes

---------

Co-authored-by: pngwn <hello@pngwn.io>

---------

Co-authored-by: Yuichiro Tachibana (Tsuchiya) <t.yic.yt@gmail.com>
  • Loading branch information
2 people authored and dawoodkhan82 committed Jun 2, 2023
1 parent 9a053b2 commit 665c427
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 78 deletions.
5 changes: 5 additions & 0 deletions .changeset/soft-insects-know.md
@@ -0,0 +1,5 @@
---
"@gradio/client": patch
---

Various internal refactors and cleanups.
146 changes: 68 additions & 78 deletions client/js/src/client.ts
Expand Up @@ -45,7 +45,7 @@ type client_return = {
data?: unknown[],
event_data?: unknown
) => SubmitReturn;
view_api: (c?: Config) => Promise<Record<string, any>>;
view_api: (c?: Config) => Promise<ApiInfo<JsApiData>>;
};

type SubmitReturn = {
Expand Down Expand Up @@ -214,7 +214,7 @@ export async function client(
// duplicate
};

let transform_files = normalise_files ?? true;
const transform_files = normalise_files ?? true;
if (typeof window === "undefined" || !("WebSocket" in window)) {
const ws = await import("ws");
NodeBlob = (await import("node:buffer")).Blob;
Expand Down Expand Up @@ -250,7 +250,7 @@ export async function client(
...return_obj
};
}
let api;
let api: ApiInfo<JsApiData>;
async function handle_space_sucess(status: SpaceStatus) {
if (status_callback) status_callback(status);
if (status.status === "running")
Expand Down Expand Up @@ -357,7 +357,6 @@ export async function client(
let complete: false | Record<string, any> = false;
const listener_map: ListenerMap<EventType> = {};

//@ts-ignore
handle_blob(
`${http_protocol}//${host + config.path}`,
data,
Expand Down Expand Up @@ -548,7 +547,7 @@ export async function client(

function fire_event<K extends EventType>(event: Event<K>) {
const narrowed_listener_map: ListenerMap<K> = listener_map;
let listeners = narrowed_listener_map[event.type] || [];
const listeners = narrowed_listener_map[event.type] || [];
listeners?.forEach((l) => l(event));
}

Expand All @@ -557,7 +556,7 @@ export async function client(
listener: EventListener<K>
) {
const narrowed_listener_map: ListenerMap<K> = listener_map;
let listeners = narrowed_listener_map[eventType] || [];
const listeners = narrowed_listener_map[eventType] || [];
narrowed_listener_map[eventType] = listeners;
listeners?.push(listener);

Expand Down Expand Up @@ -627,9 +626,7 @@ export async function client(
};
}

async function view_api(
config?: Config
): Promise<ApiInfo<JsApiData> | [{ error: string }, 500]> {
async function view_api(config?: Config): Promise<ApiInfo<JsApiData>> {
if (api) return api;

const headers: {
Expand All @@ -639,46 +636,46 @@ export async function client(
if (hf_token) {
headers.Authorization = `Bearer ${hf_token}`;
}
try {
let response: Response;
// @ts-ignore
if (semiver(config.version || "2.0.0", "3.30") < 0) {
response = await fetch(
"https://gradio-space-api-fetcher-v2.hf.space/api",
{
method: "POST",
body: JSON.stringify({
serialize: false,
config: JSON.stringify(config)
}),
headers
}
);
} else {
response = await fetch(`${config.root}/info`, {
let response: Response;
// @ts-ignore
if (semiver(config.version || "2.0.0", "3.30") < 0) {
response = await fetch(
"https://gradio-space-api-fetcher-v2.hf.space/api",
{
method: "POST",
body: JSON.stringify({
serialize: false,
config: JSON.stringify(config)
}),
headers
});
}
}
);
} else {
response = await fetch(`${config.root}/info`, {
headers
});
}

let api_info = (await response.json()) as
| ApiInfo<ApiData>
| { api: ApiInfo<ApiData> };
if ("api" in api_info) {
api_info = api_info.api;
}
if (!response.ok) {
throw new Error(BROKEN_CONNECTION_MSG);
}

if (
api_info.named_endpoints["/predict"] &&
!api_info.unnamed_endpoints["0"]
) {
api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
}
let api_info = (await response.json()) as
| ApiInfo<ApiData>
| { api: ApiInfo<ApiData> };
if ("api" in api_info) {
api_info = api_info.api;
}

const x = transform_api_info(api_info, config, api_map);
return x;
} catch (e) {
return [{ error: BROKEN_CONNECTION_MSG }, 500];
if (
api_info.named_endpoints["/predict"] &&
!api_info.unnamed_endpoints["0"]
) {
api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
}

const x = transform_api_info(api_info, config, api_map);
return x;
}
});
}
Expand All @@ -689,7 +686,7 @@ function transform_output(
root_url: string,
remote_url?: string
): unknown[] {
let transformed_data = data.map((d, i) => {
return data.map((d, i) => {
if (api_info.returns?.[i]?.component === "File") {
return normalise_file(d, root_url, remote_url);
} else if (api_info.returns?.[i]?.component === "Gallery") {
Expand All @@ -704,8 +701,6 @@ function transform_output(
return d;
}
});

return transformed_data;
}

function normalise_file(
Expand Down Expand Up @@ -921,38 +916,33 @@ export async function handle_blob(
api_info
);

return new Promise((res) => {
Promise.all(
blob_refs.map(async ({ path, blob, data, type }) => {
if (blob) {
const file_url = (await upload_files(endpoint, [blob], token))
.files[0];
return { path, file_url, type };
} else {
return { path, base64: data, type };
}
})
)
.then((r) => {
r.forEach(({ path, file_url, base64, type }) => {
if (base64) {
update_object(data, base64, path);
} else if (type === "Gallery") {
update_object(data, file_url, path);
} else if (file_url) {
const o = {
is_file: true,
name: `${file_url}`,
data: null
// orig_name: "file.csv"
};
update_object(data, o, path);
}
});
return Promise.all(
blob_refs.map(async ({ path, blob, data, type }) => {
if (blob) {
const file_url = (await upload_files(endpoint, [blob], token)).files[0];
return { path, file_url, type };
} else {
return { path, base64: data, type };
}
})
).then((r) => {
r.forEach(({ path, file_url, base64, type }) => {
if (base64) {
update_object(data, base64, path);
} else if (type === "Gallery") {
update_object(data, file_url, path);
} else if (file_url) {
const o = {
is_file: true,
name: `${file_url}`,
data: null
// orig_name: "file.csv"
};
update_object(data, o, path);
}
});

res(data);
})
.catch(console.log);
return data;
});
}

Expand Down

0 comments on commit 665c427

Please sign in to comment.