import {z} from 'zod' export type CreateApiOcrPdfToTextArgs = {recognitionMode?: string | undefined, language?: string | undefined, preprocessing?: string | undefined, body: BodyInit}; export type CreateApiOcrPdfToTextOptions = {baseUrl?: string | undefined, Apikey?: string | undefined, fetch?: typeof fetch | undefined}; export const ocrPageResult = z.object({PageNumber: z.number().int().optional(), MeanConfidenceLevel: z.number().optional(), TextResult: z.string().optional()}); export const pdfToTextResponse = z.object({Successful: z.boolean().optional(), OcrPages: z.array(ocrPageResult).optional(), AsyncJobID: z.string().optional(), AsyncJobStatus: z.string().optional()}); 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 }; /** * Converts an uploaded PDF file into text via Optical Character Recognition. * * POST /ocr/pdf/toText */ export const createApiOcrPdfToText = async (args: CreateApiOcrPdfToTextArgs, options?: CreateApiOcrPdfToTextOptions) => { const {baseUrl = "http://localhost", fetch: fetchFn = fetch, Apikey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.recognitionMode != null) headers.set("recognitionMode", String(args.recognitionMode)) if (args.language != null) headers.set("language", String(args.language)) if (args.preprocessing != null) headers.set("preprocessing", String(args.preprocessing)) if (Apikey !== undefined) headers.set("Apikey", Apikey) const url = `${baseUrl.replace(/\/+$/, '')}/ocr/pdf/toText${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(pdfToTextResponse, await res.json()) };