import {z} from 'zod' export type DetectRequest = {image: string, model?: string | undefined, confidence_threshold?: number | undefined, classes?: (Array | null) | undefined}; export type CreateApiV1VisionDetectArgs = {body: DetectRequest}; export type CreateApiV1VisionDetectOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const boundingBox = z.object({x1: z.number(), y1: z.number(), x2: z.number(), y2: z.number()}); export const detection = z.object({box: boundingBox, class_name: z.string(), class_id: z.number().int(), confidence: z.number()}); export const detectResponse = z.object({detections: z.array(detection), model: z.string(), inference_time_ms: z.number()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Detect Objects * * POST /v1/vision/detect */ export const createApiV1VisionDetect = async (args: CreateApiV1VisionDetectArgs, options: CreateApiV1VisionDetectOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/vision/detect${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(detectResponse, await res.json()) };