UNPKG

mindee

Version:

Mindee Client Library for Node.js

136 lines (135 loc) 6.9 kB
"use strict"; 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _MindeeApiV2_instances, _MindeeApiV2_processResponse, _MindeeApiV2_documentEnqueuePost, _MindeeApiV2_inferenceResultReqGet; Object.defineProperty(exports, "__esModule", { value: true }); exports.MindeeApiV2 = void 0; const apiSettingsV2_1 = require("./apiSettingsV2"); const v2_1 = require("../parsing/v2"); const form_data_1 = __importDefault(require("form-data")); const baseEndpoint_1 = require("./baseEndpoint"); const input_1 = require("../input"); const mindeeError_1 = require("../errors/mindeeError"); const logger_1 = require("../logger"); class MindeeApiV2 { constructor(apiKey) { _MindeeApiV2_instances.add(this); this.settings = new apiSettingsV2_1.ApiSettingsV2({ apiKey: apiKey }); } /** * Sends a file to the inference queue. * @param inputSource Local file loaded as an input. * @param params {InferenceParameters} parameters relating to the enqueueing options. * @category V2 * @throws Error if the server's response contains one. * @returns a `Promise` containing a job response. */ async reqPostInferenceEnqueue(inputSource, params) { await inputSource.init(); if (params.modelId === undefined || params.modelId === null || params.modelId === "") { throw new Error("Model ID must be provided"); } const result = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_documentEnqueuePost).call(this, inputSource, params); if (result.data.error?.code !== undefined) { throw new mindeeError_1.MindeeHttpErrorV2(result.data.error.code, result.data.error.message ?? "Unknown error."); } return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, result, v2_1.JobResponse); } /** * Requests the job of a queued document from the API. * Throws an error if the server's response contains one. * @param inferenceId The document's ID in the queue. * @category Asynchronous * @returns a `Promise` containing either the parsed result, or information on the queue. */ async reqGetInference(inferenceId) { const queueResponse = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_inferenceResultReqGet).call(this, inferenceId, "inferences"); return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, queueResponse, v2_1.InferenceResponse); } /** * Requests the results of a queued document from the API. * Throws an error if the server's response contains one. * @param jobId The document's ID in the queue. * @category Asynchronous * @returns a `Promise` containing either the parsed result, or information on the queue. */ async reqGetJob(jobId) { const queueResponse = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_inferenceResultReqGet).call(this, jobId, "jobs"); return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, queueResponse, v2_1.JobResponse); } } exports.MindeeApiV2 = MindeeApiV2; _MindeeApiV2_instances = new WeakSet(), _MindeeApiV2_processResponse = function _MindeeApiV2_processResponse(result, responseType) { if (result.messageObj?.statusCode && (result.messageObj?.statusCode > 399 || result.messageObj?.statusCode < 200)) { if (result.data?.status !== null) { throw new mindeeError_1.MindeeHttpErrorV2(result.data?.status, result.data?.detail ?? "Unknown error."); } throw new mindeeError_1.MindeeHttpErrorV2(result.messageObj?.statusCode ?? -1, result.data?.statusMessage ?? "Unknown error."); } try { return new responseType(result.data); } catch (e) { logger_1.logger.error(`Raised '${e}' Couldn't deserialize response object:\n${JSON.stringify(result.data)}`); throw new mindeeError_1.MindeeApiV2Error("Couldn't deserialize response object."); } }, _MindeeApiV2_documentEnqueuePost = function _MindeeApiV2_documentEnqueuePost(inputSource, params) { const form = new form_data_1.default(); form.append("model_id", params.modelId); if (params.rag !== undefined && params.rag !== null) { form.append("rag", params.rag.toString()); } if (params.polygon !== undefined && params.polygon !== null) { form.append("polygon", params.polygon.toString().toLowerCase()); } if (params.confidence !== undefined && params.confidence !== null) { form.append("confidence", params.confidence.toString().toLowerCase()); } if (params.rawText !== undefined && params.rawText !== null) { form.append("raw_text", params.rawText.toString().toLowerCase()); } if (params.webhookIds && params.webhookIds.length > 0) { form.append("webhook_ids", params.webhookIds.join(",")); } if (inputSource instanceof input_1.LocalInputSource) { form.append("file", inputSource.fileObject, { filename: inputSource.filename, }); } else { form.append("url", inputSource.url); } const path = "/v2/inferences/enqueue"; const headers = { ...this.settings.baseHeaders, ...form.getHeaders() }; const options = { method: "POST", headers: headers, hostname: this.settings.hostname, path: path, timeout: this.settings.timeout, }; return new Promise((resolve, reject) => { const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject); form.pipe(req); // potential ECONNRESET if we don't end the request. req.end(); }); }, _MindeeApiV2_inferenceResultReqGet = function _MindeeApiV2_inferenceResultReqGet(queueId, slug) { return new Promise((resolve, reject) => { const options = { method: "GET", headers: this.settings.baseHeaders, hostname: this.settings.hostname, path: `/v2/${slug}/${queueId}`, }; const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject); // potential ECONNRESET if we don't end the request. req.end(); }); };