sparrow-iq
Version:
A powerful library for intelligent document processing and validation, featuring the advanced SparrowIQ .
188 lines (184 loc) • 6.91 kB
JavaScript
;
var React = require('react');
var constants = require('../common/constants.js');
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
class SparrowIQ extends React.Component {
constructor(props) {
super(props);
__publicField(this, "validateFileType", (file) => {
if (!constants.SUPPORTED_MIME_TYPES.includes(file.type)) {
return {
success: false,
message: constants.MESSAGES.INVALID_FILE_TYPE
};
}
return this.props;
});
__publicField(this, "updateFile", (file) => this.setState({ file }));
__publicField(this, "updateRequirement", (requirement) => this.setState({ requirement }));
__publicField(this, "updateEntities", (entities) => this.setState({ entities }));
__publicField(this, "convertFileToBase64", (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
var _a;
return resolve(((_a = reader.result) == null ? void 0 : _a.toString().split(",")[1]) || "");
};
reader.onerror = () => reject(new Error(constants.MESSAGES.FILE_CONVERSION_FAILED));
reader.readAsDataURL(file);
});
});
__publicField(this, "validateState", () => {
if (!this.state.file) {
return { success: false, message: constants.MESSAGES.FILE_REQUIRED };
}
if (!this.state.requirement.trim()) {
return { success: false, message: constants.MESSAGES.REQUIREMENT_REQUIRED };
}
if (!this.state.entities.length) {
return { success: false, message: constants.MESSAGES.ENTITY_REQUIRED };
}
return { success: true, message: constants.MESSAGES.FILE_PARSED };
});
__publicField(this, "validateFile", async (fileBase64) => {
var _a, _b;
const requestBody = {
contents: [
{
role: constants.API_CONFIG.ROLE_USER,
parts: [
{
inlineData: {
data: fileBase64,
mimeType: (_a = this.state.file) == null ? void 0 : _a.type
}
},
{
text: `${constants.API_CONFIG.REQUIREMENT_PREFIX}${this.state.requirement}`
}
]
}
],
systemInstruction: {
role: constants.API_CONFIG.ROLE_USER,
parts: [
{
text: `${constants.API_CONFIG.SYSTEM_INSTRUCTION} ${this.state.entities.join(", ")}`
}
]
},
generationConfig: {
temperature: 1,
topK: 40,
topP: 0.95,
maxOutputTokens: 8192,
responseMimeType: constants.API_CONFIG.MIME_TYPE_JSON,
responseSchema: {
type: "object",
properties: __spreadValues({
requirement: { type: "string" },
validity: { type: "boolean" },
reason: { type: "string" }
}, Object.fromEntries(
this.state.entities.map((entity) => [entity, { type: "string" }])
))
}
}
};
const response = await fetch(
`${this.props.config.GENERATE_URL}?key=${this.props.config.API_KEY}`,
{
method: "POST",
headers: { "Content-Type": constants.API_CONFIG.MIME_TYPE_JSON },
body: JSON.stringify(requestBody)
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(
`${constants.MESSAGES.API_ERROR}: ${((_b = error.error) == null ? void 0 : _b.message) || constants.MESSAGES.UNKNOWN_ERROR}`
);
}
return response.json();
});
__publicField(this, "parseValidationResponse", async (data) => {
var _a, _b, _c, _d, _e;
if (!((_e = (_d = (_c = (_b = (_a = data.candidates) == null ? void 0 : _a[0]) == null ? void 0 : _b.content) == null ? void 0 : _c.parts) == null ? void 0 : _d[0]) == null ? void 0 : _e.text)) {
throw new Error(constants.MESSAGES.INVALID_RESPONSE);
}
try {
const responseText = data.candidates[0].content.parts[0].text;
const jsonMatch = responseText.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsedData = JSON.parse(jsonMatch[0]);
return {
validity: Boolean(parsedData.validity),
reason: parsedData.reason || constants.MESSAGES.NO_REASON,
entities: Object.fromEntries(
this.state.entities.map((entity) => [
entity.name,
parsedData[entity.name] || constants.MESSAGES.NOT_FOUND
])
)
};
}
const validity = responseText.toLowerCase().includes('"validity": true') || responseText.toLowerCase().includes("validity: true");
const reasonMatch = responseText.match(
/"reason":\s*"([^"]*)"|reason:\s*([^\n]*)/i
);
const reason = (reasonMatch == null ? void 0 : reasonMatch[1]) || constants.MESSAGES.NO_REASON;
const entities = Object.fromEntries(
this.state.entities.map((entity) => {
const match = responseText.match(
new RegExp(
`"${entity.name}":s*"?([^"
]*)"?|${entity.name}:s*([^
]*)`,
"i"
)
);
return [
entity.name,
((match == null ? void 0 : match[1]) || (match == null ? void 0 : match[2]) || "").trim() || constants.MESSAGES.NOT_FOUND
];
})
);
return { validity, reason, entities };
} catch (error) {
console.error("Error parsing response:", error);
throw new Error(constants.MESSAGES.PARSE_ERROR);
}
});
this.state = {
file: null,
requirement: "",
entities: []
};
}
async parseFile(file) {
const fileBase64 = await this.convertFileToBase64(file);
const validationResponse = await this.validateFile(fileBase64);
return this.parseValidationResponse(validationResponse);
}
}
exports.SparrowIQ = SparrowIQ;
//# sourceMappingURL=index.js.map