New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

bank-voucher-ocr

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bank-voucher-ocr - npm Package Compare versions

Comparing version 0.8.0 to 0.9.0

15

dist/bvocr.esm.js

@@ -5,3 +5,3 @@ /**

*
* @version 0.8.0
* @version 0.9.0
* @author waiting

@@ -324,2 +324,3 @@ * @license MIT

}
// default text parse
function prepareContent(buf) {

@@ -331,3 +332,3 @@ let content = buf && buf.byteLength ? buf.toString() : '';

}
content = content.replace(/[\t ]/g, ''); // remove tab character and space character
content = content.replace(/(?<=\S) /g, ''); // remove ONE space character after word
return content

@@ -347,4 +348,10 @@ }

if (Array.isArray(arr) && arr.length) {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n');
return arr[0]
if (regex.global && arr.length > 1) { // regexp with g and multi matched
debug && console.info('----------multi matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<-------------ignore matched result---------------\n\n');
return ''
}
else {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n');
return arr[0]
}
}

@@ -351,0 +358,0 @@ }

@@ -5,3 +5,3 @@ /**

*
* @version 0.8.0
* @version 0.9.0
* @author waiting

@@ -12,3 +12,3 @@ * @license MIT

import{access,chmod,close,copyFile,mkdir,open,readdir,readFile,rmdir,stat,unlink,write,writeFile}from"fs";import{join,normalize,resolve,sep}from"path";import{promisify}from"util";import{tmpdir}from"os";import{crop,info,resize}from"easyimage";import*as moment_ from"moment";import{from,of,range,defer}from"rxjs";import{concatMap,map,mergeMap,reduce,catchError,defaultIfEmpty,delay,filter,mapTo,retry,skipWhile,take,tap}from"rxjs/operators";import run from"rxrunscript";const closeAsync=promisify(close),chmodAsync=promisify(chmod),copyFileAsync=promisify(copyFile),mkdirAsync=promisify(mkdir),openAsync=promisify(open),readFileAsync=promisify(readFile),readDirAsync=promisify(readdir),rmdirAsync=promisify(rmdir),unlinkAsync=promisify(unlink),writeAsync=promisify(write),writeFileAsync=promisify(writeFile);function isPathAcessible(e){return e?new Promise(t=>access(e,e=>t(!e))):Promise.resolve(!1)}function isDirExists(e){return e?isDirFileExists(e,"DIR"):Promise.resolve(!1)}function isFileExists(e){return e?isDirFileExists(e,"FILE"):Promise.resolve(!1)}function isDirFileExists(e,t){return e?new Promise(r=>{stat(e,(e,i)=>{r(!(e||!i)&&("DIR"===t?i.isDirectory():i.isFile()))})}):Promise.resolve(!1)}async function createDir(e){if(!e)throw new Error("value of path param invalid");e=normalize(e),await isDirExists(e)||await e.split(sep).reduce(async(e,t)=>{const r=resolve(await e,t);return await isPathAcessible(r)||await mkdirAsync(r,493),r},Promise.resolve(sep))}async function rimraf(e){e&&(await _rimraf(e),await isDirExists(e)&&await rmdirAsync(e))}async function _rimraf(e){if(e&&await isPathAcessible(e)){if(await isFileExists(e))return void await unlinkAsync(e);const t=await readDirAsync(e);if(t.length)for(const r of t)await _rimraf(join(e,r));else await rmdirAsync(e)}}const initialBaseTmpDir=join(tmpdir(),"voucher-ocr"),initialResizeImgDir=join(initialBaseTmpDir,"resize"),initialSplitTmpDir=join(initialBaseTmpDir,"split"),zoneTmpDirPrefix="zone",initialBankZone={zoneName:"bank",width:2250,height:390,offsetX:70,offsetY:10},moment=moment_;function splitPagetoItems(e,t,r){return readImgInfo(e).pipe(map(i=>{const n=calcItemsPerPage(i.height,r.height);return n?range(0,n).pipe(mergeMap(n=>{const a={index:n,itemConfig:Object.assign({},r),srcPath:e,targetDir:t,pageHeight:i.height};return i.width<a.itemConfig.width&&(a.itemConfig.width=i.width),parseSplitPage(a).pipe(mergeMap(e=>{const t=new Map;return t.set(e.name,e),of(t)}))})):of(new Map)}),concatMap(e=>e))}function resizeAndSaveImg(e,t,r,i){if(r<=0||r>1)throw new Error(`value of scale invalid: "${r}"`);return readImgInfo(e).pipe(mergeMap(n=>{const a={src:e,dst:t,width:n.width*r,height:n.height*r,quality:i};return from(resize(a))}),map(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return t}))}function parseSplitPage(e){const{index:t,srcPath:r,pageHeight:i}=e,{width:n}=e.itemConfig;let{height:a}=e.itemConfig;const o=36,s=0,p=t*a;p+a>i&&(a=i-p);const c=moment().format("YYYYMMDD"),m=join(e.targetDir,`${c}-${Math.random()}-${t}.jpg`),f={dst:m,src:r,quality:100,cropWidth:n,cropHeight:a+36,x:0,y:p};return from(crop(f)).pipe(mergeMap(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return of(t)}))}function readImgInfo(e){return from(info(e))}function calcItemsPerPage(e,t){const r=33;return e>=t?Math.floor((e+33)/t):1}function getOcrZoneOptsByBankName(e,t){return t.get(e)}function cropImgAllZones(e,t,r){return from(r).pipe(mergeMap(r=>cropImgZone(e,t,r).pipe(map(e=>[r.zoneName,e]))),reduce((e,t)=>(e.set(t[0],t[1]),e),new Map))}function cropImgZone(e,t,r){const{zoneName:i,width:n,height:a,offsetX:o,offsetY:s}=r,p=join(t,`${i}-${Math.random()}.png`),c={dst:p,src:e,quality:100,cropWidth:n,cropHeight:a,x:o,y:s};return from(crop(c)).pipe(map(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return t}))}function runOcr(e,t){t||(t="eng");const r=`tesseract "${e}" "${e}" -l ${t}`;return run(r)}function retrieveKeyValuesFromOcrResult(e,t,r,i=!1){if(!t)throw new Error("matchRules empty");return readTxtFile(e).pipe(map(e=>({buf:e,regexp:t})),map(({buf:e,regexp:t})=>{const n=r&&"function"==typeof r?r(e):e.toString("utf8");return retrieveValueByRegexp(n,t,i)}))}function getRegexpOptsByName(e,t){for(const r of Object.keys(t))if(r===e)return t[r]}function retrieveValueByRegexp(e,t,r=!1){const i=regexMatch(e,t,r);return r&&console.info("retrieveValueByRegexp ----- text start: ---------------\x3e \n",e,"\n<--------------- text END ----------------\n\n",t,">>>>>>>>matched value: ",i,"\n"),i}function readTxtFile(e){if(!e)throw new Error("path empty");const t=e.split(".");if(t.length>1&&"txt"!==t[t.length-1].toLowerCase())throw new Error(`file extensiion must empty or be '.txt', but is: "${e}"`);return defer(async()=>readFileAsync(e))}function prepareContent(e){let t=e&&e.byteLength?e.toString():"";return t?t=t.replace(/[\t ]/g,""):""}function regexMatch(e,t,r=!1){if(e)for(const i of t){const t=e.match(i);if(Array.isArray(t)&&t.length)return r&&console.info("----------matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<----------------------------\n\n"),t[0]}}const moment$1=moment_;class Bvo{constructor(e){this.options=e,this.options.debug=!!this.options.debug;const{baseTmpDir:t,splitTmpDir:r,resizeImgDir:i}=e,n=t||initialBaseTmpDir,a=r||initialSplitTmpDir,o=i||initialResizeImgDir;from(createDir(n)).pipe(concatMap(()=>createDir(a)),concatMap(()=>createDir(o))).subscribe(()=>{},console.error)}run(e){return recognize(e,this.options)}}function recognize(e,t){const{bankZone:r,baseTmpDir:i,debug:n,defaultOcrLang:a,jpegQuality:o,scale:s,splitTmpDir:p,resizeImgDir:c,voucherConfigMap:m}=t,f=i||initialBaseTmpDir,l=p||initialSplitTmpDir,u=c||initialResizeImgDir,g=getBankRegexpOpts(m),h={baseDir:f,path:e,bankZone:r,bankRegexpOptsMap:g,debug:!!n,lang:a},d=recognizePageBank(h).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),concatMap(({bankName:e,pagePath:t})=>(n&&console.info("start split page"),splitPageToImgs(t,e,l,m))),concatMap(({bankName:e,imgFile:t})=>{const r=getOcrFields(e,m);if(!r)throw new Error(`ocrFields not defined with bankName: "${e}"`);const i={bankName:e,baseDir:f,concurrent:2,debug:!!n,defaultValue:"",imgFile:t,ocrFields:r,voucherConfigMap:m};return n&&console.info("recognize item"),recognizeFields(i).pipe(map(r=>(r.set("bank",e),r.set("filename",t.name.trim()),r.set("path",t.path.trim()),r)))}),mergeMap(e=>{const t={retInfo:e,resizeDir:u,scale:s,jpegQuality:o,debug:!!n};return saveImgAndPrune(t)})),y=from(isFileExists(e)).pipe(filter(e=>e));return y.pipe(mergeMap(()=>d))}function recognizePageBank(e){const{baseDir:t,path:r,bankZone:i,bankRegexpOptsMap:n,debug:a,lang:o}=e,s=join(t,zoneTmpDirPrefix,Math.random().toString());return a&&console.info("recognize pageBank:",s,r),from(createDir(s)).pipe(mergeMap(()=>cropImgZone(join(r),s,i)),concatMap(e=>runOcr(e.path,o).pipe(map(()=>({path:r,zoneImgPath:e.path})),mapTo(e.path),catchError(()=>of(e.path)))),concatMap(e=>from(n.entries()).pipe(concatMap(([t,r])=>retrieveKeyValuesFromOcrResult(e+".txt",r,e=>e.toString().replace(/(?<=\S)[. ]{1,2}(?=\S)/g,""),a).pipe(map(e=>({bankName:t,value:e})))),skipWhile(({value:e})=>"undefined"==typeof e||"string"==typeof e&&!e.length),take(1),map(({bankName:e})=>({bankName:e,pagePath:r})),defaultIfEmpty({bankName:"n/a",pagePath:""}))),tap(e=>{const{bankName:t,pagePath:i}=e;"n/a"!==t&&i||console.info(`recognize bank of page fail. no matached regexp. file: "${r}", pagePath: "${i}" `),a||rimraf(s).catch(console.info)}))}function splitPageToImgs(e,t,r,i){const n=i.get(t);if(!n)throw new Error("bank config empty during split page to images");return splitPagetoItems(e,r,n).pipe(mergeMap(e=>{const r=from(e.values()).pipe(map(e=>({bankName:t,imgFile:e})));return r}))}function recognizeFields(e){const{bankName:t,baseDir:r,concurrent:i,debug:n,defaultValue:a,imgFile:o,ocrFields:s,voucherConfigMap:p}=e,c=join(r,zoneTmpDirPrefix,moment$1().format("YYYYMMDD")+"-"+Math.random().toString()),m=getOcrZoneOptsByBankName(t,p);if(!m)throw new Error(`get bankConfig empty with bankName: "${t}"`);const f=from(createDir(c)).pipe(mergeMap(()=>cropImgAllZones(o.path,c,m.ocrZones)),concatMap(e=>{const t={bankConfig:m,ocrFields:s,defaultValue:a,debug:n,concurrent:i>0?i:2,zoneImgMap:e};return batchOcrAndRetrieve(t)}));return f}function batchOcrAndRetrieve(e){const{zoneImgMap:t,bankConfig:r,ocrFields:i,defaultValue:n,concurrent:a,debug:o}=e,{bankName:s}=r,p=from(t.entries()).pipe(delay(5e3),mergeMap(([,e])=>defer(async()=>{const t=e.path,r=t+".txt";return await isFileExists(t)&&await rimraf(t),await isFileExists(r)&&await rimraf(r),null}).pipe(delay(2e4),retry(2),catchError(e=>(console.info("Delete zone file retry failed:",e),of(null))))),catchError(()=>of(null))),c=from(t.entries()).pipe(concatMap(e=>ocrAndPickFromZoneImg(e,r,a,o)),reduce((e,t)=>e.set(t.fieldName,t.value),new Map),map(e=>e.set("bank",s)),map(e=>setDefaultValue(e,i,n)),tap(()=>o||p.subscribe()));return c}function setDefaultValue(e,t,r=""){const i=new Map;for(const r of Object.keys(t)){const t=e.get(r);"string"==typeof t?i.set(r,t):i.set(r,"")}return i}function processZoneImgRow(e){const{fieldName:t,value:r}=e,i={fieldName:t,value:r};switch(t){case"amount":i.value=r.trim().replace(/,/g,"");break;case"date":i.value=r.trim().replace(/\D/g,"");break;case"sn":i.value=r.trim()}return i}function validateZoneImgRow(e,t){if("string"!=typeof t)return!1;switch(e){case"amount":if(validateRetInfoAmout(t))return!0;break;case"sn":if(t)return!0;break;case"date":if(validateRetInfoDate(t))return!0;break;case"bank":return!0;default:if("string"==typeof t)return!0}return!1}function validateRetInfoAmout(e){if(!e)return!1;if(!e.trim())return!1;const t=parseFloat(e);return!Number.isNaN(t)&&"number"==typeof t}function validateRetInfoDate(e){return!!e&&moment$1(e,"YYYYMMDD").isValid()}function getBankRegexpOpts(e){const t=new Map;for(const{bankName:r,regexpOpts:i}of e.values())i&&i.bank&&t.set(r,i.bank);if(!t.size)throw new Error("not BankRegexpOpts found, should not set");return t}function getOcrFields(e,t){const r=t.get(e);if(!r)throw new Error(`get ocrFields empty by bankName: "${e}"`);return r.ocrFields}function saveImgAndPrune(e){const{retInfo:t,resizeDir:r,debug:i,scale:n,jpegQuality:a}=e,o=t.get("filename"),s=t.get("path"),p=t.get("sn");if(!o)throw new Error(`result info map invalid with empty path. info: ${t}`);if(!s)throw new Error(`result info map invalid with empty path. info: ${t}`);const c=p?`${(new Date).getTime()}-${p.replace(/[^\d\w]/g,"_")}.jpg`:o,m=moment$1().format("YYYY-MM-DD"),f=join(r,m,c);return t.set("filename",c),resizeAndSaveImg(s,f,n,a).pipe(map(e=>(t.set("path",e.path),t)),tap(()=>{i||unlinkAsync(s).catch(console.info)}))}function genFieldLangs(e,t,r){return r&&"undefined"!=typeof r[e]&&Array.isArray(r[e])?r[e]:t}function ocrAndPickFromZoneImg(e,t,r=2,i=!1){const{ocrDefaultLangs:n,ocrFieldLangs:a,regexpOpts:o,ocrFields:s}=t;return from(Object.entries(s)).pipe(filter(t=>{const r=t[1];return!!r&&r===e[0]}),mergeMap(t=>{const r=t[0];return ocrAndPickFieldFromZoneImg(r,e,o,n,a,i)},r))}function ocrAndPickFieldFromZoneImg(e,t,r,i,n,a=!1){const[,o]=t,s=genFieldLangs(e,i,n),p=s.length-1,c=getRegexpOptsByName(e,r);if(!c)throw new Error(`got regexp empty by zoneName: "${e}"`);return from(s).pipe(concatMap(e=>runOcr(o.path,e).pipe(mapTo(!0),catchError(()=>of(!0)))),concatMap(()=>retrieveKeyValuesFromOcrResult(o.path+".txt",c,prepareContent,a).pipe(map(t=>({fieldName:e,value:t})))),skipWhile((e,t)=>{const r=validateZoneImgRow(e.fieldName,e.value);return!r&&t!==p}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}export{initialBankZone,initialBaseTmpDir,initialResizeImgDir,initialSplitTmpDir,zoneTmpDirPrefix,Bvo,recognize};
import{access,chmod,close,copyFile,mkdir,open,readdir,readFile,rmdir,stat,unlink,write,writeFile}from"fs";import{join,normalize,resolve,sep}from"path";import{promisify}from"util";import{tmpdir}from"os";import{crop,info,resize}from"easyimage";import*as moment_ from"moment";import{from,of,range,defer}from"rxjs";import{concatMap,map,mergeMap,reduce,catchError,defaultIfEmpty,delay,filter,mapTo,retry,skipWhile,take,tap}from"rxjs/operators";import run from"rxrunscript";const closeAsync=promisify(close),chmodAsync=promisify(chmod),copyFileAsync=promisify(copyFile),mkdirAsync=promisify(mkdir),openAsync=promisify(open),readFileAsync=promisify(readFile),readDirAsync=promisify(readdir),rmdirAsync=promisify(rmdir),unlinkAsync=promisify(unlink),writeAsync=promisify(write),writeFileAsync=promisify(writeFile);function isPathAcessible(e){return e?new Promise(t=>access(e,e=>t(!e))):Promise.resolve(!1)}function isDirExists(e){return e?isDirFileExists(e,"DIR"):Promise.resolve(!1)}function isFileExists(e){return e?isDirFileExists(e,"FILE"):Promise.resolve(!1)}function isDirFileExists(e,t){return e?new Promise(r=>{stat(e,(e,i)=>{r(!(e||!i)&&("DIR"===t?i.isDirectory():i.isFile()))})}):Promise.resolve(!1)}async function createDir(e){if(!e)throw new Error("value of path param invalid");e=normalize(e),await isDirExists(e)||await e.split(sep).reduce(async(e,t)=>{const r=resolve(await e,t);return await isPathAcessible(r)||await mkdirAsync(r,493),r},Promise.resolve(sep))}async function rimraf(e){e&&(await _rimraf(e),await isDirExists(e)&&await rmdirAsync(e))}async function _rimraf(e){if(e&&await isPathAcessible(e)){if(await isFileExists(e))return void await unlinkAsync(e);const t=await readDirAsync(e);if(t.length)for(const r of t)await _rimraf(join(e,r));else await rmdirAsync(e)}}const initialBaseTmpDir=join(tmpdir(),"voucher-ocr"),initialResizeImgDir=join(initialBaseTmpDir,"resize"),initialSplitTmpDir=join(initialBaseTmpDir,"split"),zoneTmpDirPrefix="zone",initialBankZone={zoneName:"bank",width:2250,height:390,offsetX:70,offsetY:10},moment=moment_;function splitPagetoItems(e,t,r){return readImgInfo(e).pipe(map(i=>{const n=calcItemsPerPage(i.height,r.height);return n?range(0,n).pipe(mergeMap(n=>{const a={index:n,itemConfig:Object.assign({},r),srcPath:e,targetDir:t,pageHeight:i.height};return i.width<a.itemConfig.width&&(a.itemConfig.width=i.width),parseSplitPage(a).pipe(mergeMap(e=>{const t=new Map;return t.set(e.name,e),of(t)}))})):of(new Map)}),concatMap(e=>e))}function resizeAndSaveImg(e,t,r,i){if(r<=0||r>1)throw new Error(`value of scale invalid: "${r}"`);return readImgInfo(e).pipe(mergeMap(n=>{const a={src:e,dst:t,width:n.width*r,height:n.height*r,quality:i};return from(resize(a))}),map(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return t}))}function parseSplitPage(e){const{index:t,srcPath:r,pageHeight:i}=e,{width:n}=e.itemConfig;let{height:a}=e.itemConfig;const o=36,s=0,p=t*a;p+a>i&&(a=i-p);const c=moment().format("YYYYMMDD"),m=join(e.targetDir,`${c}-${Math.random()}-${t}.jpg`),l={dst:m,src:r,quality:100,cropWidth:n,cropHeight:a+36,x:0,y:p};return from(crop(l)).pipe(mergeMap(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return of(t)}))}function readImgInfo(e){return from(info(e))}function calcItemsPerPage(e,t){const r=33;return e>=t?Math.floor((e+33)/t):1}function getOcrZoneOptsByBankName(e,t){return t.get(e)}function cropImgAllZones(e,t,r){return from(r).pipe(mergeMap(r=>cropImgZone(e,t,r).pipe(map(e=>[r.zoneName,e]))),reduce((e,t)=>(e.set(t[0],t[1]),e),new Map))}function cropImgZone(e,t,r){const{zoneName:i,width:n,height:a,offsetX:o,offsetY:s}=r,p=join(t,`${i}-${Math.random()}.png`),c={dst:p,src:e,quality:100,cropWidth:n,cropHeight:a,x:o,y:s};return from(crop(c)).pipe(map(e=>{const t={name:e.name,path:e.path,width:e.width,height:e.height,size:e.size};return t}))}function runOcr(e,t){t||(t="eng");const r=`tesseract "${e}" "${e}" -l ${t}`;return run(r)}function retrieveKeyValuesFromOcrResult(e,t,r,i=!1){if(!t)throw new Error("matchRules empty");return readTxtFile(e).pipe(map(e=>({buf:e,regexp:t})),map(({buf:e,regexp:t})=>{const n=r&&"function"==typeof r?r(e):e.toString("utf8");return retrieveValueByRegexp(n,t,i)}))}function getRegexpOptsByName(e,t){for(const r of Object.keys(t))if(r===e)return t[r]}function retrieveValueByRegexp(e,t,r=!1){const i=regexMatch(e,t,r);return r&&console.info("retrieveValueByRegexp ----- text start: ---------------\x3e \n",e,"\n<--------------- text END ----------------\n\n",t,">>>>>>>>matched value: ",i,"\n"),i}function readTxtFile(e){if(!e)throw new Error("path empty");const t=e.split(".");if(t.length>1&&"txt"!==t[t.length-1].toLowerCase())throw new Error(`file extensiion must empty or be '.txt', but is: "${e}"`);return defer(async()=>readFileAsync(e))}function prepareContent(e){let t=e&&e.byteLength?e.toString():"";return t?t=t.replace(/(?<=\S) /g,""):""}function regexMatch(e,t,r=!1){if(e)for(const i of t){const t=e.match(i);if(Array.isArray(t)&&t.length)return i.global&&t.length>1?(r&&console.info("----------multi matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<-------------ignore matched result---------------\n\n"),""):(r&&console.info("----------matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<----------------------------\n\n"),t[0])}}const moment$1=moment_;class Bvo{constructor(e){this.options=e,this.options.debug=!!this.options.debug;const{baseTmpDir:t,splitTmpDir:r,resizeImgDir:i}=e,n=t||initialBaseTmpDir,a=r||initialSplitTmpDir,o=i||initialResizeImgDir;from(createDir(n)).pipe(concatMap(()=>createDir(a)),concatMap(()=>createDir(o))).subscribe(()=>{},console.error)}run(e){return recognize(e,this.options)}}function recognize(e,t){const{bankZone:r,baseTmpDir:i,debug:n,defaultOcrLang:a,jpegQuality:o,scale:s,splitTmpDir:p,resizeImgDir:c,voucherConfigMap:m}=t,l=i||initialBaseTmpDir,f=p||initialSplitTmpDir,u=c||initialResizeImgDir,g=getBankRegexpOpts(m),h={baseDir:l,path:e,bankZone:r,bankRegexpOptsMap:g,debug:!!n,lang:a},d=recognizePageBank(h).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),concatMap(({bankName:e,pagePath:t})=>(n&&console.info("start split page"),splitPageToImgs(t,e,f,m))),concatMap(({bankName:e,imgFile:t})=>{const r=getOcrFields(e,m);if(!r)throw new Error(`ocrFields not defined with bankName: "${e}"`);const i={bankName:e,baseDir:l,concurrent:2,debug:!!n,defaultValue:"",imgFile:t,ocrFields:r,voucherConfigMap:m};return n&&console.info("recognize item"),recognizeFields(i).pipe(map(r=>(r.set("bank",e),r.set("filename",t.name.trim()),r.set("path",t.path.trim()),r)))}),mergeMap(e=>{const t={retInfo:e,resizeDir:u,scale:s,jpegQuality:o,debug:!!n};return saveImgAndPrune(t)})),y=from(isFileExists(e)).pipe(filter(e=>e));return y.pipe(mergeMap(()=>d))}function recognizePageBank(e){const{baseDir:t,path:r,bankZone:i,bankRegexpOptsMap:n,debug:a,lang:o}=e,s=join(t,zoneTmpDirPrefix,Math.random().toString());return a&&console.info("recognize pageBank:",s,r),from(createDir(s)).pipe(mergeMap(()=>cropImgZone(join(r),s,i)),concatMap(e=>runOcr(e.path,o).pipe(map(()=>({path:r,zoneImgPath:e.path})),mapTo(e.path),catchError(()=>of(e.path)))),concatMap(e=>from(n.entries()).pipe(concatMap(([t,r])=>retrieveKeyValuesFromOcrResult(e+".txt",r,e=>e.toString().replace(/(?<=\S)[. ]{1,2}(?=\S)/g,""),a).pipe(map(e=>({bankName:t,value:e})))),skipWhile(({value:e})=>"undefined"==typeof e||"string"==typeof e&&!e.length),take(1),map(({bankName:e})=>({bankName:e,pagePath:r})),defaultIfEmpty({bankName:"n/a",pagePath:""}))),tap(e=>{const{bankName:t,pagePath:i}=e;"n/a"!==t&&i||console.info(`recognize bank of page fail. no matached regexp. file: "${r}", pagePath: "${i}" `),a||rimraf(s).catch(console.info)}))}function splitPageToImgs(e,t,r,i){const n=i.get(t);if(!n)throw new Error("bank config empty during split page to images");return splitPagetoItems(e,r,n).pipe(mergeMap(e=>{const r=from(e.values()).pipe(map(e=>({bankName:t,imgFile:e})));return r}))}function recognizeFields(e){const{bankName:t,baseDir:r,concurrent:i,debug:n,defaultValue:a,imgFile:o,ocrFields:s,voucherConfigMap:p}=e,c=join(r,zoneTmpDirPrefix,moment$1().format("YYYYMMDD")+"-"+Math.random().toString()),m=getOcrZoneOptsByBankName(t,p);if(!m)throw new Error(`get bankConfig empty with bankName: "${t}"`);const l=from(createDir(c)).pipe(mergeMap(()=>cropImgAllZones(o.path,c,m.ocrZones)),concatMap(e=>{const t={bankConfig:m,ocrFields:s,defaultValue:a,debug:n,concurrent:i>0?i:2,zoneImgMap:e};return batchOcrAndRetrieve(t)}));return l}function batchOcrAndRetrieve(e){const{zoneImgMap:t,bankConfig:r,ocrFields:i,defaultValue:n,concurrent:a,debug:o}=e,{bankName:s}=r,p=from(t.entries()).pipe(delay(5e3),mergeMap(([,e])=>defer(async()=>{const t=e.path,r=t+".txt";return await isFileExists(t)&&await rimraf(t),await isFileExists(r)&&await rimraf(r),null}).pipe(delay(2e4),retry(2),catchError(e=>(console.info("Delete zone file retry failed:",e),of(null))))),catchError(()=>of(null))),c=from(t.entries()).pipe(concatMap(e=>ocrAndPickFromZoneImg(e,r,a,o)),reduce((e,t)=>e.set(t.fieldName,t.value),new Map),map(e=>e.set("bank",s)),map(e=>setDefaultValue(e,i,n)),tap(()=>o||p.subscribe()));return c}function setDefaultValue(e,t,r=""){const i=new Map;for(const r of Object.keys(t)){const t=e.get(r);"string"==typeof t?i.set(r,t):i.set(r,"")}return i}function processZoneImgRow(e){const{fieldName:t,value:r}=e,i={fieldName:t,value:r};switch(t){case"amount":i.value=r.trim().replace(/,/g,"");break;case"date":i.value=r.trim().replace(/\D/g,"");break;case"sn":i.value=r.trim()}return i}function validateZoneImgRow(e,t){if("string"!=typeof t)return!1;switch(e){case"amount":if(validateRetInfoAmout(t))return!0;break;case"sn":if(t)return!0;break;case"date":if(validateRetInfoDate(t))return!0;break;case"bank":return!0;default:if("string"==typeof t)return!0}return!1}function validateRetInfoAmout(e){if(!e)return!1;if(!e.trim())return!1;const t=parseFloat(e);return!Number.isNaN(t)&&"number"==typeof t}function validateRetInfoDate(e){return!!e&&moment$1(e,"YYYYMMDD").isValid()}function getBankRegexpOpts(e){const t=new Map;for(const{bankName:r,regexpOpts:i}of e.values())i&&i.bank&&t.set(r,i.bank);if(!t.size)throw new Error("not BankRegexpOpts found, should not set");return t}function getOcrFields(e,t){const r=t.get(e);if(!r)throw new Error(`get ocrFields empty by bankName: "${e}"`);return r.ocrFields}function saveImgAndPrune(e){const{retInfo:t,resizeDir:r,debug:i,scale:n,jpegQuality:a}=e,o=t.get("filename"),s=t.get("path"),p=t.get("sn");if(!o)throw new Error(`result info map invalid with empty path. info: ${t}`);if(!s)throw new Error(`result info map invalid with empty path. info: ${t}`);const c=p?`${(new Date).getTime()}-${p.replace(/[^\d\w]/g,"_")}.jpg`:o,m=moment$1().format("YYYY-MM-DD"),l=join(r,m,c);return t.set("filename",c),resizeAndSaveImg(s,l,n,a).pipe(map(e=>(t.set("path",e.path),t)),tap(()=>{i||unlinkAsync(s).catch(console.info)}))}function genFieldLangs(e,t,r){return r&&"undefined"!=typeof r[e]&&Array.isArray(r[e])?r[e]:t}function ocrAndPickFromZoneImg(e,t,r=2,i=!1){const{ocrDefaultLangs:n,ocrFieldLangs:a,regexpOpts:o,ocrFields:s}=t;return from(Object.entries(s)).pipe(filter(t=>{const r=t[1];return!!r&&r===e[0]}),mergeMap(t=>{const r=t[0];return ocrAndPickFieldFromZoneImg(r,e,o,n,a,i)},r))}function ocrAndPickFieldFromZoneImg(e,t,r,i,n,a=!1){const[,o]=t,s=genFieldLangs(e,i,n),p=s.length-1,c=getRegexpOptsByName(e,r);if(!c)throw new Error(`got regexp empty by zoneName: "${e}"`);return from(s).pipe(concatMap(e=>runOcr(o.path,e).pipe(mapTo(!0),catchError(()=>of(!0)))),concatMap(()=>retrieveKeyValuesFromOcrResult(o.path+".txt",c,prepareContent,a).pipe(map(t=>({fieldName:e,value:t})))),skipWhile((e,t)=>{const r=validateZoneImgRow(e.fieldName,e.value);return!r&&t!==p}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}export{initialBankZone,initialBaseTmpDir,initialResizeImgDir,initialSplitTmpDir,zoneTmpDirPrefix,Bvo,recognize};
//# sourceMappingURL=bvocr.esm.min.js.map

@@ -5,3 +5,3 @@ /**

*
* @version 0.8.0
* @version 0.9.0
* @author waiting

@@ -330,2 +330,3 @@ * @license MIT

}
// default text parse
function prepareContent(buf) {

@@ -337,3 +338,3 @@ let content = buf && buf.byteLength ? buf.toString() : '';

}
content = content.replace(/[\t ]/g, ''); // remove tab character and space character
content = content.replace(/(?<=\S) /g, ''); // remove ONE space character after word
return content

@@ -353,4 +354,10 @@ }

if (Array.isArray(arr) && arr.length) {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n');
return arr[0]
if (regex.global && arr.length > 1) { // regexp with g and multi matched
debug && console.info('----------multi matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<-------------ignore matched result---------------\n\n');
return ''
}
else {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n');
return arr[0]
}
}

@@ -357,0 +364,0 @@ }

@@ -48,2 +48,3 @@ import { defer } from 'rxjs'

}
// default text parse
export function prepareContent(buf) {

@@ -55,3 +56,3 @@ let content = buf && buf.byteLength ? buf.toString() : ''

}
content = content.replace(/[\t ]/g, '') // remove tab character and space character
content = content.replace(/(?<=\S) /g, '') // remove ONE space character after word
return content

@@ -71,6 +72,12 @@ }

if (Array.isArray(arr) && arr.length) {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n')
return arr[0]
if (regex.global && arr.length > 1) { // regexp with g and multi matched
debug && console.info('----------multi matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<-------------ignore matched result---------------\n\n')
return ''
}
else {
debug && console.info('----------matched regex: -------------->\n', arr, '\n--- used regex ----: ', regex, '\n<----------------------------\n\n')
return arr[0]
}
}
}
}
{
"name": "bank-voucher-ocr",
"author": "waiting",
"version": "0.8.0",
"version": "0.9.0",
"description": "Bank Voucher ocr by tesseract and retrieve fields",

@@ -6,0 +6,0 @@ "keywords": [

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc