UNPKG

mindee

Version:

Mindee Client Library for Node.js

231 lines (230 loc) 9.74 kB
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Endpoint_instances, _Endpoint_predictReqPost, _Endpoint_predictAsyncReqPost, _Endpoint_documentQueueReqGet, _Endpoint_documentGetReq, _Endpoint_documentFeedbackPutReq; import { URLSearchParams } from "url"; import { FormData } from "undici"; import { LocalInputSource } from "../../input/index.js"; import { cutDocPages, sendRequestAndReadResponse, } from "../../http/apiCore.js"; import { handleError } from "./errors.js"; import { isValidAsyncResponse, isValidSyncResponse } from "./responseValidation.js"; /** * Endpoint for a product (OTS or Custom). */ export class Endpoint { constructor(urlName, owner, version, settings) { _Endpoint_instances.add(this); this.settings = settings; this.urlRoot = `/v1/products/${owner}/${urlName}/v${version}`; this.owner = owner; this.urlName = urlName; this.version = version; } /** * Sends a document to the API and parses out the result. * Throws an error if the server's response contains one. * @param {PredictParams} params parameters relating to prediction options. * @category Synchronous * @returns a `Promise` containing parsing results. */ async predict(params) { await params.inputDoc.init(); if (params.pageOptions !== undefined) { await cutDocPages(params.inputDoc, params.pageOptions); } const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper); if (!isValidSyncResponse(response)) { handleError(this.urlName, response, this.extractStatusMessage(response)); } return response; } /** * Enqueues a prediction to the API. * Throws an error if the server's response contains one. * @param {PredictParams} params parameters relating to prediction options. * @category Asynchronous * @returns a `Promise` containing queue data. */ async predictAsync(params) { await params.inputDoc.init(); if (params.pageOptions !== undefined) { await cutDocPages(params.inputDoc, params.pageOptions); } const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictAsyncReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper, params.rag, params.workflowId); if (!isValidAsyncResponse(response)) { handleError(this.urlName, response, this.extractStatusMessage(response)); } return response; } extractStatusMessage(response) { if (response.messageObj?.statusMessage !== undefined && response.messageObj?.statusMessage !== null) { return response.messageObj?.statusMessage; } const errorDetail = response.data?.api_request?.error?.detail; if (errorDetail) { return JSON.stringify(errorDetail); } const errorMessage = response.data?.api_request?.error?.message; if (errorMessage) { return JSON.stringify(errorMessage); } return undefined; } /** * Requests the results of a queued document from the API. * Throws an error if the server's response contains one. * @param queueId The document's ID in the queue. * @category Asynchronous * @returns a `Promise` containing the parsed result. */ async getQueuedDocument(queueId) { const queueResponse = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentQueueReqGet).call(this, queueId); const queueStatusCode = queueResponse.messageObj.statusCode; if (!isValidAsyncResponse(queueResponse)) { handleError(this.urlName, queueResponse, this.extractStatusMessage(queueResponse)); } if (queueStatusCode === 302 && queueResponse.messageObj.headers.location !== undefined) { const docId = queueResponse.messageObj.headers.location.split("/").pop(); if (docId !== undefined) { return await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentGetReq).call(this, docId); } } return queueResponse; } /** * Send a feedback * @param {string} documentId */ async getDocument(documentId) { const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentGetReq).call(this, documentId); if (!isValidAsyncResponse(response)) { handleError("document", response, this.extractStatusMessage(response)); } return response; } /** * Send a feedback * @param {string} documentId - ID of the document to send feedback to. * @param {StringDict} feedback - Feedback object to send. */ async sendFeedback(documentId, feedback) { const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentFeedbackPutReq).call(this, documentId, feedback); if (!isValidSyncResponse(response)) { handleError("feedback", response, this.extractStatusMessage(response)); } return response; } /** * Send a file to a prediction API. * @param input * @param predictUrl * @param includeWords * @param fullText * @param cropper * @param rag * @param workflowId */ async sendFileForPrediction(input, predictUrl, includeWords = false, fullText = false, cropper = false, rag = false, workflowId = undefined) { const searchParams = new URLSearchParams(); if (cropper) { searchParams.set("cropper", "true"); } if (rag) { searchParams.set("rag", "true"); } if (fullText) { searchParams.set("full_text_ocr", "true"); } const form = new FormData(); if (input instanceof LocalInputSource && input.fileObject instanceof Buffer) { form.set("document", new Blob([input.fileObject]), input.filename); } else { form.set("document", input.fileObject); } if (includeWords) { form.set("include_mvision", "true"); } let path; if (workflowId === undefined) { path = `${this.urlRoot}/${predictUrl}`; } else { path = `/v1/workflows/${workflowId}/predict_async`; } if (searchParams.toString().length > 0) { path += `?${searchParams}`; } const options = { method: "POST", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: path, timeoutSecs: this.settings.timeoutSecs, body: form, }; return await sendRequestAndReadResponse(this.settings.dispatcher, options); } } _Endpoint_instances = new WeakSet(), _Endpoint_predictReqPost = function _Endpoint_predictReqPost(input, includeWords = false, fullText = false, cropper = false) { return this.sendFileForPrediction(input, "predict", includeWords, fullText, cropper); }, _Endpoint_predictAsyncReqPost = function _Endpoint_predictAsyncReqPost( /** * Make a request to POST a document for async prediction. * @param input * @param includeWords * @param fullText * @param cropper * @param rag * @param workflowId */ input, includeWords = false, fullText = false, cropper = false, rag = false, workflowId = undefined) { return this.sendFileForPrediction(input, "predict_async", includeWords, fullText, cropper, rag, workflowId); }, _Endpoint_documentQueueReqGet = /** * Make a request to GET the status of a document in the queue. * @param queueId */ async function _Endpoint_documentQueueReqGet(queueId) { const options = { method: "GET", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: `${this.urlRoot}/documents/queue/${queueId}`, timeoutSecs: this.settings.timeoutSecs, }; return await sendRequestAndReadResponse(this.settings.dispatcher, options); }, _Endpoint_documentGetReq = /** * Make a request to GET a document. * @param documentId */ async function _Endpoint_documentGetReq(documentId) { const options = { method: "GET", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: `${this.urlRoot}/documents/${documentId}`, timeoutSecs: this.settings.timeoutSecs, }; return await sendRequestAndReadResponse(this.settings.dispatcher, options); }, _Endpoint_documentFeedbackPutReq = /** * Make a request to PUT a document feedback. * @param documentId * @param feedback */ async function _Endpoint_documentFeedbackPutReq(documentId, feedback) { const options = { method: "PUT", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: `/v1/documents/${documentId}/feedback`, body: JSON.stringify(feedback), timeoutSecs: this.settings.timeoutSecs, }; return await sendRequestAndReadResponse(this.settings.dispatcher, options); };