UNPKG

imgrecog

Version:

Node.js tool to parse and act on images, using the Google Vision and Sightengine APIs.

108 lines (107 loc) 4.97 kB
"use strict"; // SIGHTENGINE Object.defineProperty(exports, "__esModule", { value: true }); exports.Sightengine = void 0; const utils_1 = require("./utils"); const FormData = require("form-data"); const fs = require("fs"); /** * Sightentine API wrapper. */ class Sightengine { constructor() { /** * Prepare the Sightengine client. * @param options Program options. */ this.prepare = async (options) => { utils_1.logDebug(options, `Loaded Sightengine API user and secret`); }; /** * Sightengine image detection. * @param options Program options. * @param filepath Image file to be scanned. */ this.detect = async (options, filepath) => { return new Promise((resolve) => { this.apiCalls++; // Image overal properties are always detected. const models = ["properties"]; try { const form = new FormData(); // Detect unsafe? if (options.unsafe) { models.push("offensive"); models.push("nudity"); models.push("wad"); } // Detect logos? if (options.logos) { models.push("text"); } // Create form data to be posted to Sightengine. form.append("api_user", options.sightengineUser); form.append("api_secret", options.sightengineSecret); form.append("models", models.join(",")); form.append("media", fs.createReadStream(filepath)); utils_1.logDebug(options, `${filepath} - posting to Sightengine now`); form.submit("https://api.sightengine.com/1.0/check.json", (err, res) => { if (err) { utils_1.logError(options, `${filepath} - error detecting ${models.join(", ")}`, err); return resolve(null); } let chunks = ""; // Receive response chucks from the API. res.on("data", (chunk) => { chunks += chunk; }); // Response complete. res.on("end", function () { try { const logtext = []; const tags = {}; // Parse response data as JSON. const data = JSON.parse(chunks); // API returned an error? if (data.error && data.status && data.status == "failure") { utils_1.logError(options, `${filepath} - error parsing`, new Error(data.error.message)); return resolve(null); } // Got good results? if (data.status == "success") { if (data.nudity && data.nudity.raw) { const key = utils_1.normalizeTag("explicit-adult"); const score = utils_1.normalizeScore(data.nudity.raw); if (score) { logtext.push(`${key}:${score}`); tags[key] = score; } } const details = logtext.length > 0 ? logtext.join(", ") : "NONE"; const logDetails = `${filepath}: ${details}`; utils_1.logInfo(options, logDetails); } // Results are ready. return resolve({ file: filepath, tags: tags }); } catch (ex) { utils_1.logError(options, `${filepath} - error parsing response for ${models.join(", ")}`, ex); return resolve(null); } }); }); } catch (ex) { utils_1.logError(options, `${filepath} - error detecting ${models.join(", ")}`, ex); return resolve(null); } }); }; } } exports.Sightengine = Sightengine; // Exports... exports.default = new Sightengine();