gradio/frontend
1442k
1import { Client } from "../client";2import type { Dependency, PredictReturn } from "../types";3 4export async function predict<T = unknown>(5 this: Client,6 endpoint: string | number,7 data: unknown[] | Record<string, unknown> = {}8): Promise<PredictReturn<T>> {9 let data_returned = false;10 let status_complete = false;11 let dependency: Dependency;12 13 if (!this.config) {14 throw new Error("Could not resolve app config");15 }16 17 if (typeof endpoint === "number") {18 dependency = this.config.dependencies.find((dep) => dep.id == endpoint)!;19 } else {20 const trimmed_endpoint = endpoint.replace(/^\//, "");21 dependency = this.config.dependencies.find(22 (dep) => dep.id == this.api_map[trimmed_endpoint]23 )!;24 }25 26 const app = this.submit(endpoint, data, null, null, true);27 let result: unknown;28 29 for await (const message of app) {30 if (message.type === "data") {31 data_returned = true;32 result = message;33 if (status_complete) {34 return result as PredictReturn<T>;35 }36 }37 38 if (message.type === "status") {39 if (message.stage === "error") {40 // Throw a real `Error` (rather than the raw status object) so that41 // uncaught failures surface a readable message instead of42 // crashing Node with `ERR_UNHANDLED_REJECTION ... reason "#<Object>"`.43 // The status fields are preserved on the error for callers that44 // inspect them.45 const { message: error_message, ...status } = message;46 const error = new Error(47 (typeof error_message === "string"48 ? error_message49 : error_message && JSON.stringify(error_message)) ||50 "An unknown error occurred while making a prediction."51 );52 Object.assign(error, status);53 throw error;54 }55 if (message.stage === "complete") {56 status_complete = true;57 // if complete message comes after data, resolve here58 if (data_returned) {59 return result as PredictReturn<T>;60 }61 }62 }63 }64 65 return result as PredictReturn<T>;66}67 