mindee
Version:
Mindee Client Library for Node.js
265 lines (264 loc) • 10.4 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.cli = cli;
const commander_1 = require("commander");
const client_1 = require("./client");
const input_1 = require("./input");
const console = __importStar(require("console"));
const cliProducts_1 = require("./cliProducts");
const program = new commander_1.Command();
//
// EXECUTE THE COMMANDS
//
function initClient(options) {
return new client_1.Client({
apiKey: options.apiKey,
debug: options.debug,
});
}
function getConfig(command) {
const conf = cliProducts_1.CLI_COMMAND_CONFIG.get(command);
if (conf === undefined) {
throw new Error(`Invalid document type ${command}`);
}
return conf;
}
function getPageOptions(options) {
let pageOptions = undefined;
if (options.cutPages) {
pageOptions = {
operation: input_1.PageOptionsOperation.KeepOnly,
pageIndexes: [0, 1, 2, 3, 4],
onMinPages: 5,
};
}
return pageOptions;
}
function getPredictParams(options) {
return {
allWords: options.allWords,
cropper: options.cropper,
};
}
async function callParse(productClass, command, inputPath, options) {
const mindeeClient = initClient(options);
const predictParams = getPredictParams(options);
const pageOptions = getPageOptions(options);
const inputSource = mindeeClient.docFromPath(inputPath);
let response;
if (command === cliProducts_1.COMMAND_CUSTOM || command === cliProducts_1.COMMAND_GENERATED) {
const customEndpoint = mindeeClient.createEndpoint(options.endpoint, options.account, options.version);
response = await mindeeClient.parse(productClass, inputSource, {
endpoint: customEndpoint,
pageOptions: pageOptions,
allWords: predictParams.allWords,
cropper: predictParams.cropper,
});
}
else {
response = await mindeeClient.parse(productClass, inputSource, {
pageOptions: pageOptions,
allWords: predictParams.allWords,
cropper: predictParams.cropper,
});
}
printResponse(response.document, options);
}
async function callEnqueueAndParse(productClass, command, inputPath, options) {
const mindeeClient = initClient(options);
const predictParams = getPredictParams(options);
const pageOptions = getPageOptions(options);
const inputSource = mindeeClient.docFromPath(inputPath);
let response;
if (command === cliProducts_1.COMMAND_CUSTOM || command === cliProducts_1.COMMAND_GENERATED) {
const customEndpoint = mindeeClient.createEndpoint(options.endpoint, options.account, options.version);
response = await mindeeClient.enqueueAndParse(productClass, inputSource, {
endpoint: customEndpoint,
pageOptions: pageOptions,
allWords: predictParams.allWords,
cropper: predictParams.cropper,
initialDelaySec: 2,
delaySec: 1.5,
maxRetries: 80,
});
}
else {
response = await mindeeClient.enqueueAndParse(productClass, inputSource, {
pageOptions: pageOptions,
allWords: predictParams.allWords,
cropper: predictParams.cropper,
initialDelaySec: 2,
delaySec: 1.5,
maxRetries: 80,
});
if (!response.document) {
throw Error("Document could not be retrieved");
}
printResponse(response.document, options);
}
}
async function callGetDocument(productClass, documentId, options) {
const mindeeClient = initClient(options);
const response = await mindeeClient.getDocument(productClass, documentId);
printResponse(response.document, options);
}
async function callSendFeedback(productClass, documentId, feedbackStr, options) {
const mindeeClient = initClient(options);
const feedback = {
feedback: JSON.parse(feedbackStr),
};
const response = await mindeeClient.sendFeedback(productClass, documentId, feedback);
console.log(response.feedback);
}
function printResponse(document, options) {
if (options.allWords) {
document.ocr?.mVisionV1.pages.forEach((page) => {
console.log(page.allWords.toString());
});
}
if (options.pages) {
document.inference.pages.forEach((page) => {
console.log(`\n${page}`);
});
}
if (document) {
console.log(`\n${document}`);
}
}
//
// BUILD THE COMMANDS
//
function addMainOptions(prog) {
prog.option("-k, --api-key <api_key>", "API key for document endpoint");
}
function addPostOptions(prog, info) {
prog.option("-c, --cut-pages", "keep only the first 5 pages of the document");
if (info.allWords) {
prog.option("-w, --all-words", "to get all the words in the current document. False by default.");
}
prog.argument("<input_path>", "full path to the file");
}
function addCustomPostOptions(prog) {
prog.requiredOption("-e, --endpoint <endpoint_name>", "API endpoint name (required)");
prog.requiredOption("-a, --account <account_name>", "API account name for the endpoint (required)");
prog.option("-v, --version <version>", "version for the endpoint, use the latest version if not specified");
}
function addDisplayOptions(prog) {
prog.option("-p, --pages", "show content of individual pages");
}
function routeSwitchboard(command, inputPath, allOptions) {
if (command.parent === null || command.parent === undefined) {
throw new Error(`Improperly configured command: ${command.name()}`);
}
const docClass = getConfig(command.parent.name()).docClass;
if ("async" in command.opts() && command.opts()["async"]) {
return callEnqueueAndParse(docClass, command.name(), inputPath, allOptions);
}
return callParse(docClass, command.name(), inputPath, allOptions);
}
function addPredictAction(prog) {
if (prog.name() === cliProducts_1.COMMAND_CUSTOM || prog.name() === cliProducts_1.COMMAND_GENERATED) {
prog.action(function (inputPath, options, command) {
const allOptions = {
...prog.parent?.parent?.opts(),
...prog.parent?.opts(),
...prog.opts(),
...options,
};
return routeSwitchboard(command, inputPath, allOptions);
});
}
else {
prog.action(function (inputPath, options, command) {
const allOptions = {
...prog.parent?.parent?.opts(),
...prog.parent?.opts(),
...prog.opts(),
...options,
};
return routeSwitchboard(command, inputPath, allOptions);
});
}
}
function cli() {
program.name("mindee")
.description("Command line interface for Mindee products.")
.option("-d, --debug", "high verbosity mode");
cliProducts_1.CLI_COMMAND_CONFIG.forEach((info, name) => {
const productCmd = program.command(name)
.description(info.displayName);
if (info.async) {
const getDocProductCmd = productCmd.command("fetch")
.description("Fetch previously parsed results.")
.argument("<documentId>", "Unique ID of the document.")
.action(async (documentId, options) => {
const docClass = getConfig(name).docClass;
await callGetDocument(docClass, documentId, { ...options, ...productCmd.opts(), ...program.opts() });
});
addMainOptions(getDocProductCmd);
}
const feedbackProductCmd = productCmd.command("feedback")
.description("Send feedback for a document.")
.argument("<documentId>", "Unique ID of the document.")
.argument("<feedback>", "Feedback to send, ex '{\"key\": \"value\"}'.")
.action(async (documentId, feedback, options) => {
const docClass = getConfig(name).docClass;
await callSendFeedback(docClass, documentId, feedback, { ...options, ...productCmd.opts(), ...program.opts() });
});
addMainOptions(feedbackProductCmd);
const predictProductCmd = productCmd.command("parse")
.description("Send a file for parsing.");
if (info.async) {
const asyncOpt = new commander_1.Option("-A, --async", "Call asynchronously");
if (info.sync) {
asyncOpt.default(false);
}
else {
asyncOpt.default(true);
asyncOpt.hideHelp();
}
predictProductCmd.addOption(asyncOpt);
}
if (name === cliProducts_1.COMMAND_CUSTOM || name === cliProducts_1.COMMAND_GENERATED) {
addCustomPostOptions(predictProductCmd);
}
addMainOptions(predictProductCmd);
addDisplayOptions(predictProductCmd);
addPostOptions(predictProductCmd, info);
addPredictAction(predictProductCmd);
});
program.parse(process.argv);
}
;