UNPKG

openalpr

Version:

Open ALPR JavaScript SDK for Multei

220 lines (174 loc) 7.18 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('debug'), require('axios')) : typeof define === 'function' && define.amd ? define(['debug', 'axios'], factory) : (global = global || self, factory(global.debug, global.axios)); }(this, (function (Debug, axios) { 'use strict'; Debug = Debug && Object.prototype.hasOwnProperty.call(Debug, 'default') ? Debug['default'] : Debug; axios = axios && Object.prototype.hasOwnProperty.call(axios, 'default') ? axios['default'] : axios; const debug = Debug('openalpr:removeBase64Prefix'); function removeBase64Prefix(data) { if(typeof data !== "string") { throw new Error(`Can not recognize base64 data. This is not a valid base64 string. Got ${data}`) } if(data === '') { throw new Error('Can not recognize base64 data from an empty string.') } debug('Splitting base64 prefix from image data...'); const dataSplit = data.split(','); debug('Checking if split data contains prefix...'); if(dataSplit.length > 1) { debug('Split data contains prefix: %o', dataSplit[0]); return dataSplit[1]; } debug('Returning original string (it does not have base64 prefix)'); return dataSplit[0]; } const debug$1 = Debug('openalpr:handler:error'); function handleErrorResponse(error) { debug$1('Handling error response...'); if(typeof error.response !== "undefined") { debug$1('Request made, server responded with error status code'); /* * The request was made and the server responded with a * status code that falls out of the range of 2xx */ const { data, status, headers } = error.response; return { data, status, headers } } if(typeof error.request !== "undefined") { debug$1('Request made but no response received'); /* * The request was made but no response was received, `error.request` * is an instance of XMLHttpRequest in the browser and an instance * of http.ClientRequest in Node.js */ return error.request } if(typeof error.message !== "undefined") { debug$1('Request not made. Found error %o', error.message); // Something happened in setting up the request and triggered an Error return error.message } debug$1('Unknown error found: %o', error); return error; } const debug$2 = Debug('openalpr:handler:response'); function handleResponse(response) { debug$2('Returning response data...'); return response.data } const debug$3 = Debug('openalpr:openalpr'); /** * Create a new instance of OpenALPR * * @param instanceConfig * @constructor */ function OpenALPR(instanceConfig) { debug$3('Constructing OpenALPR instance...'); this.defaults = instanceConfig; } /** * Dispatch a recognition * * @param {Object} config The config specific for this request (merged with this.defaults) * @return {Promise<*>} */ OpenALPR.prototype.recognize = async function recognize(data, config = {}) { if(typeof data === 'undefined') { throw new Error('Image base64 data is missing. Please check recognize() function call') } if(data === '' || data === null) { throw new Error('Image data is empty or null. Please check recognize() function call') } debug$3('Setting config...'); config = {...this.defaults, ...config}; debug$3('Creating axios instance with OpenALPR API data...'); const instance = axios.create({baseURL: 'https://api.openalpr.com/v2'}); debug$3('Building request URL...'); const url = `/recognize_bytes?recognize_vehicle=1&country=br&secret_key=${config["secretKey"]}`; try { debug$3('Removing base64 prefix (if needed)...'); data = removeBase64Prefix(data); if(typeof data === "undefined") { throw new Error("Cannot make request to API. Image data is undefined after base64 prefix removal") } debug$3('Making request to OpenALPR with raw data...'); const response = await instance.post(url, data, { headers: {'content-type': 'raw'} }); debug$3('Calling response handler...'); return handleResponse(response) } catch (error) { debug$3('Calling error handler...'); throw handleErrorResponse(error) } }; const defaults = { secretKey: null }; const debug$4 = Debug('openalpr:main'); /** * Create an instance of OpenALPR * * @param {Object} defaultConfig The default config for the instance * @return {OpenALPR} A new instance of OpenALPR */ function createInstance(instanceConfig = defaults) { debug$4('Creating an instance...'); return new OpenALPR(instanceConfig); } /** * Create the default instance to be exported */ const openALPR = createInstance(defaults); /** * Expose OpenALPR class to allow class inheritance * * @type {OpenALPR} */ openALPR.OpenALPR = OpenALPR; /** * Factory for creating new instances * * @param {Object} instanceConfig * @return {OpenALPR} */ openALPR.create = function create(instanceConfig) { debug$4('Returning the new instance...'); return createInstance({...defaults, ...instanceConfig}) }; const debug$5 = Debug('openalpr:express-middleware'); module.exports = (fileIndex) => async (req, res, next) => { debug$5('Entered OpenALPR middleware...'); if(typeof process.env.OPENALPR_SECRET_KEY === 'undefined') { throw new Error('Can not call OpenALPR API. Secret key is missing.') } const openALPR$1 = openALPR.create({ secretKey: process.env.OPENALPR_SECRET_KEY }); const handleRecognition = result => { debug$5('Recognition result: %o', result); if(result.status === 400) { throw new Error('Can not recognize data from image. OpenALPR returned 400') } else if(result.results.length == 0) { throw new Error('There is no car plate on image') } debug$5('Success recognizing vehicle!'); req.recognitionData = req.recognitionData || {}; req.recognitionData[fileIndex] = result; }; try { const encoded = req.files[fileIndex][0].buffer.toString('base64'); debug$5('Generating encoded base64 file'); debug$5('Starting vehicle recognition'); const result = await openALPR$1.recognize(encoded); debug$5('Starting to handle recognition...'); handleRecognition(result); next(); } catch(err) { debug$5('Vehicle recognition failed'); next(err); } }; })));