mindee
Version:
Mindee Client Library for Node.js
108 lines (107 loc) • 3.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneratedObjectField = void 0;
exports.isGeneratedObject = isGeneratedObject;
const standard_1 = require("../standard");
/** A JSON-like object, with miscellaneous values. */
class GeneratedObjectField {
constructor({ prediction = {}, pageId, }) {
let itemPageId = null;
this.printableValues = [];
for (const [fieldName, fieldValue] of Object.entries(prediction)) {
if (fieldName === "page_id") {
itemPageId = fieldValue;
}
else if (["polygon", "rectangle", "quadrangle", "bounding_box"].includes(fieldName)) {
Object.assign(this, {
[fieldName]: new standard_1.PositionField({
prediction: { [fieldName]: fieldValue },
valueKey: fieldName,
pageId: pageId,
}),
});
this.printableValues.push(fieldName);
}
else if (fieldName === "confidence") {
this.confidence = fieldValue;
}
else if (fieldName === "raw_value") {
this.rawValue = fieldValue;
}
else {
if (fieldValue !== null &&
fieldValue !== undefined &&
typeof fieldValue === "number" &&
!isNaN(fieldValue) &&
fieldName !== "degrees") {
Object.assign(this, { [fieldName]: this.toNumberString(fieldValue) });
}
else if (typeof fieldValue === "boolean") {
Object.assign(this, { [fieldName]: fieldValue });
}
else {
Object.assign(this, {
[fieldName]: (fieldValue !== undefined && fieldValue !== null) ?
String(fieldValue) : null,
});
}
this.printableValues.push(fieldName);
}
this.pageId = pageId ?? itemPageId;
}
}
/**
* ReSTructured-compliant string representation.
Takes into account level of indentation & displays elements as list elements.
* @param level Level of indentation. 0 by default.
*/
toStringLevel(level = 0) {
const indent = " " + " ".repeat(level);
let outStr = "";
this.printableValues.forEach((printableValue) => {
const strValue = this[printableValue];
outStr += `\n${indent}:${printableValue}: ${strValue !== null && strValue !== undefined ? strValue : ""}`;
});
return `\n${indent}${outStr.trim()}`;
}
/**
* Formats a float number to have at least one decimal place.
* @param n Input number.
* @returns
*/
toNumberString(n) {
if (Number.isInteger(n)) {
return n + ".0";
}
return n.toString();
}
toString() {
return this.toStringLevel();
}
get(fieldName) {
return this[fieldName];
}
}
exports.GeneratedObjectField = GeneratedObjectField;
/**
* Checks whether a field is a custom object or not.
* @param strDict input dictionary to check.
*/
function isGeneratedObject(strDict) {
const commonKeys = [
"value",
"polygon",
"rectangle",
"page_id",
"confidence",
"quadrangle",
"values",
"raw_value",
];
for (const key in strDict) {
if (Object.prototype.hasOwnProperty.call(strDict, key) && !commonKeys.includes(key)) {
return true;
}
}
return false;
}