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 1.3.0 to 1.3.1

4

dist/bvocr.esm.js

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

*
* @version 1.3.0
* @version 1.3.1
* @author waiting

@@ -900,2 +900,2 @@ * @license MIT

export { initialBankZone, initialBaseTmpDir, initialResizeImgDir, initialSplitTmpDir, zoneTmpDirPrefix, Bvo, recognize };
export { initialBankZone, initialBaseTmpDir, initialResizeImgDir, initialSplitTmpDir, zoneTmpDirPrefix, Bvo, recognize, splitPageToImgs };

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

*
* @version 1.3.0
* @version 1.3.1
* @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{basename,join,normalize,resolve,sep}from"path";import{promisify}from"util";import{tmpdir,cpus}from"os";import{crop,info,resize}from"easyimage";import*as moment_ from"moment";import{from,of,range,defer}from"rxjs";import{concatMap,map,mergeMap,catchError,last,mapTo,reduce,defaultIfEmpty,filter,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(n=>{stat(e,(e,i)=>{n(!(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 n=resolve(await e,t);return await isPathAcessible(n)||await mkdirAsync(n,493),n},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 n of t)await _rimraf(join(e,n));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,n){return readImgInfo(e).pipe(map(i=>{const r=calcItemsPerPage(i.height,n.height);return r?range(0,r).pipe(mergeMap(r=>{const a={index:r,itemConfig:Object.assign({},n),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 e.name&&t.set(e.name,e),of(t)}))})):of(new Map)}),concatMap(e=>e))}function resizeAndSaveImg(e,t,n,i){if(n<=0||n>1)throw new Error(`value of scale invalid: "${n}"`);return readImgInfo(e).pipe(mergeMap(r=>{const a={src:e,dst:t,width:r.width*n,height:r.height*n,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:n,pageHeight:i}=e,{width:r,marginBottom:a}=e.itemConfig;let{height:o}=e.itemConfig;const s=0,c=t*o;if(c+o>i&&(o=i-c),o/i<.1||o<100){const e={name:"",path:"",width:0,height:0,size:0};return of(e)}const p=basename(n),m=p.split(".")[0],l=moment().format("YYYYMMDD"),f=join(e.targetDir,`${l}-${m}-${Math.random()}-${t}.jpg`),u={dst:f,src:n,quality:100,cropWidth:r,cropHeight:o+a,x:0,y:c};return from(crop(u)).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 n=33;return e>=t?Math.ceil((e+33)/t):1}function getOcrZoneOptsByBankName(e,t){return t.get(e)}function cropImgAllZones(e,t,n,i){const r=[],a=new Set;for(const e of Object.values(n))e&&!a.has(e)&&a.add(e);for(const e of i){const t=e.zoneName;t&&a.has(t)&&r.push(e)}return from(r).pipe(mergeMap(n=>cropImgZone(e,t,n).pipe(map(e=>[n.zoneName,e]))),reduce((e,t)=>(e.set(t[0],t[1]),e),new Map))}function cropImgZone(e,t,n){const{zoneName:i,width:r,height:a,offsetX:o,offsetY:s}=n,c=join(t,`${i}-${Math.random()}.png`),p={dst:c,src:e,quality:100,cropWidth:r,cropHeight:a,x:o,y:s};return from(crop(p)).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,n){t||(t="eng");const i=`tesseract "${e}" "${n}" -l ${t}`;return run(i).pipe(last(),catchError(()=>of(void 0)),mapTo(void 0))}function retrieveKeyValuesFromOcrResult(e,t,n,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 r=n&&"function"==typeof n?n(e):e.toString("utf8");return retrieveValueByRegexp(r,t,i)}))}function getRegexpOptsByName(e,t){for(const n of Object.keys(t))if(n===e)return t[n]}function retrieveValueByRegexp(e,t,n=!1){const i=regexMatch(e,t,n);return n&&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,n=!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?(n&&console.info("----------multi matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<-------------ignore matched result---------------\n\n"),""):(n&&console.info("----------matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<----------------------------\n\n"),t[0])}}function getOcrRetLangPath(e,t,n){const i=getOcrRetLangMap(e,t);if(!i)return"";const r=i.get(n);return r||""}function updateOcrRetTxtMap(e,t,n,i){if(!t||!n||!i)return;let r=getOcrRetLangMap(e,t);r||(r=new Map),n&&i&&updateOcrRetLangMap(r,n,i),e.set(t,r)}function updateOcrRetLangMap(e,t,n){e.set(t,n)}function getOcrRetLangMap(e,t){return e.get(t)}const moment$1=moment_;class Bvo{constructor(e){this.options=e;const t=+this.options.globalScale;this.options.globalScale=Number.isNaN(t)||t<=0?1:t,this.options.debug=!!this.options.debug;const{baseTmpDir:n,splitTmpDir:i,resizeImgDir:r}=e,a=n||initialBaseTmpDir,o=i||initialSplitTmpDir,s=r||initialResizeImgDir;from(createDir(a)).pipe(catchError(e=>(console.info(e),of(null))),concatMap(()=>createDir(o)),catchError(e=>(console.info(e),of(null))),concatMap(()=>createDir(s)),catchError(e=>(console.info(e),of(null)))).subscribe(()=>{},console.error)}run(e){return recognize(e,this.options)}}function recognize(e,t){const{bankZone:n,baseTmpDir:i,concurrent:r,debug:a,defaultOcrLang:o,jpegQuality:s,scale:c,splitTmpDir:p,resizeImgDir:m,voucherConfigMap:l,globalScale:f,skipImgDir:u}=t,g=i||initialBaseTmpDir,h=p||initialSplitTmpDir,d=m||initialResizeImgDir,y=u?join(u,moment$1().format("YYYYMMDD")):"",b="number"==typeof r&&r>0?r:cpus().length,w=parseVoucherConfigMapScale(l,f),k=parseOcrZoneScale(n,f),D=c/f,M=getBankRegexpOpts(w),v={baseDir:g,path:e,bankZone:k,bankRegexpOptsMap:M,debug:!!a,lang:o,skipImgDir:y},x=recognizePageBank(v).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),mergeMap(({bankName:e,pagePath:t})=>(a&&console.info("start split page"),splitPageToImgs(t,e,h,w))),mergeMap(({bankName:e,imgFile:t})=>{const n=getOcrFields(e,w);if(!n)throw new Error(`ocrFields not defined with bankName: "${e}"`);const i={bankName:e,baseDir:g,debug:!!a,defaultValue:"",imgFile:t,ocrFields:n,voucherConfigMap:w};return a&&console.info("recognize item"),recognizeFields(i).pipe(map(n=>(n.set("bank",e),n.set("filename",t.name.trim()),n.set("path",t.path.trim()),n)))},b>0?b:1),mergeMap(e=>{const t={retInfo:e,resizeDir:d,scale:D,jpegQuality:s,debug:!!a};return saveImgAndPrune(t)})),I=from(isFileExists(e)).pipe(filter(e=>e));return I.pipe(mergeMap(()=>x))}function recognizePageBank(e){const{baseDir:t,path:n,bankZone:i,bankRegexpOptsMap:r,debug:a,lang:o,skipImgDir:s}=e,c=join(t,zoneTmpDirPrefix,`${basename(n)}-${Math.random().toString()}`);return a&&console.info("recognize pageBank:",c,n),from(createDir(c)).pipe(catchError(e=>(console.info(e),of(null))),mergeMap(()=>cropImgZone(join(n),c,i)),concatMap(e=>runOcr(e.path,o,e.path).pipe(mapTo(e.path))),concatMap(e=>from(r.entries()).pipe(concatMap(([t,n])=>retrieveKeyValuesFromOcrResult(e+".txt",n,e=>e.toString().replace(/(?<=\S)[. ]{1,2}(?=\S)/g,"").replace(/\n{2,}/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:n})),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: "${n}", pagePath: "${i}" `),cpSkipImg(n,s)),a||rimraf(c).catch(console.info)}))}async function cpSkipImg(e,t){t&&(await isPathAcessible(t)||await createDir(t),copyFileAsync(e,join(t,basename(e))).catch(console.error))}function splitPageToImgs(e,t,n,i){const r=i.get(t);if(!r)throw new Error("bank config empty during split page to images");return splitPagetoItems(e,n,r).pipe(mergeMap(e=>{const n=from(e.values()).pipe(map(e=>({bankName:t,imgFile:e})));return n}))}function recognizeFields(e){const{bankName:t,baseDir:n,debug:i,defaultValue:r,imgFile:a,ocrFields:o,voucherConfigMap:s}=e,c=join(n,zoneTmpDirPrefix,`${basename(a.path)}`),p=getOcrZoneOptsByBankName(t,s);if(!p)throw new Error(`get bankConfig empty with bankName: "${t}"`);const m=from(createDir(c)).pipe(mergeMap(()=>cropImgAllZones(a.path,c,o,p.ocrZones)),concatMap(e=>{const t={bankConfig:p,ocrFields:o,defaultValue:r,debug:i,zoneImgMap:e};return batchOcrAndRetrieve(t)}),tap(()=>{i||setTimeout(e=>{rimraf(e).catch(console.info)},5e3,c)}));return m}function batchOcrAndRetrieve(e){const{zoneImgMap:t,bankConfig:n,ocrFields:i,defaultValue:r,debug:a}=e,{bankName:o}=n,s=from(t.entries()).pipe(concatMap(e=>ocrAndPickFromZoneImg(e,n,a)),reduce((e,t)=>e.set(t.fieldName,t.value),new Map),map(e=>e.set("bank",o)),map(e=>setDefaultValue(e,i,r)));return s}function setDefaultValue(e,t,n=""){const i=new Map;for(const n of Object.keys(t)){const t=e.get(n);"string"==typeof t?i.set(n,t):i.set(n,"")}return i}function processZoneImgRow(e){const{fieldName:t,value:n}=e,i=Object.assign({},e);switch(t){case"amount":i.value=n.trim().replace(/,/g,"");break;case"date":i.value=n.trim().replace(/\D/g,""),i.value&&"0"===i.value.slice(0,1)&&(i.value="2"+i.value);break;case"sn":case"destAccountNumber":case"paymentAccountNumber":i.value=n.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:n,regexpOpts:i}of e.values())i&&i.bank&&t.set(n,i.bank);if(!t.size)throw new Error("not BankRegexpOpts found, should not set");return t}function getOcrFields(e,t){const n=t.get(e);if(!n)throw new Error(`get ocrFields empty by bankName: "${e}"`);return n.ocrFields}function saveImgAndPrune(e){const{retInfo:t,resizeDir:n,debug:i,scale:r,jpegQuality:a}=e,o=t.get("filename"),s=t.get("path"),c=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 p=o.split(".").slice(0,-1).join("").split("-");p.splice(2,1);let m=p.join("-");c&&(m+=`-${c.replace(/[^\d\w]/g,"_")}`),m+=".jpg";const l=moment$1().format("YYYY-MM-DD"),f=join(n,l,m);return t.set("filename",m),resizeAndSaveImg(s,f,r,a).pipe(map(e=>(t.set("path",e.path),t)),tap(()=>{i||unlinkAsync(s).catch(console.info)}))}function genFieldLangs(e,t,n){return n&&"undefined"!=typeof n[e]&&Array.isArray(n[e])?n[e]:t}function ocrAndPickFromZoneImg(e,t,n=!1){const{ocrDefaultLangs:i,ocrFieldLangs:r,regexpOpts:a,ocrFields:o}=t,s=new Map;return from(Object.entries(o)).pipe(filter(t=>{const n=t[1];return!!n&&n===e[0]}),concatMap(t=>{const o=t[0],c=t[1];return ocrAndPickFieldFromZoneImg(o,c,e,a,i,r,n,s)}))}function ocrAndPickFieldFromZoneImg(e,t,n,i,r,a,o=!1,s){const[,c]=n,p=genFieldLangs(e,r,a),m=p.length-1,l=getRegexpOptsByName(e,i);if(!l)throw new Error(`got regexp empty by zoneName: "${e}"`);return from(p).pipe(concatMap(n=>{const i=getOcrRetLangPath(s,t,n);if(i)return retrieveKeyValuesFromOcrResult(i+".txt",l,prepareContent,o).pipe(map(r=>({fieldName:e,zoneName:t,value:r,usedLang:n,txtPath:i})));{const i=c.path,r=i.split(".").slice(0,-1).join(".")+`-${Math.random()}`;return runOcr(i,n,r).pipe(concatMap(()=>retrieveKeyValuesFromOcrResult(r+".txt",l,prepareContent,o).pipe(map(i=>({fieldName:e,zoneName:t,value:i,usedLang:n,txtPath:r})))))}}),tap(({zoneName:e,usedLang:t,txtPath:n})=>{updateOcrRetTxtMap(s,e,t,n)}),skipWhile((e,t)=>{const n=validateZoneImgRow(e.fieldName,e.value);return!n&&t!==m}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}function parseVoucherConfigMapScale(e,t){const n=new Map;for(const[i,r]of e){const e=Object.assign({},r),a=[];for(const n of e.ocrZones)a.push(parseOcrZoneScale(n,t));e.ocrZones=a,e.width=e.width*t,e.height=e.height*t,e.marginBottom=e.marginBottom*t,n.set(i,e)}return n}function parseOcrZoneScale(e,t){const n=Object.assign({},e);return n.width=n.width*t,n.height=n.height*t,n.offsetX=n.offsetX*t,n.offsetY=n.offsetY*t,n}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{basename,join,normalize,resolve,sep}from"path";import{promisify}from"util";import{tmpdir,cpus}from"os";import{crop,info,resize}from"easyimage";import*as moment_ from"moment";import{from,of,range,defer}from"rxjs";import{concatMap,map,mergeMap,catchError,last,mapTo,reduce,defaultIfEmpty,filter,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(n=>{stat(e,(e,i)=>{n(!(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 n=resolve(await e,t);return await isPathAcessible(n)||await mkdirAsync(n,493),n},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 n of t)await _rimraf(join(e,n));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,n){return readImgInfo(e).pipe(map(i=>{const r=calcItemsPerPage(i.height,n.height);return r?range(0,r).pipe(mergeMap(r=>{const a={index:r,itemConfig:Object.assign({},n),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 e.name&&t.set(e.name,e),of(t)}))})):of(new Map)}),concatMap(e=>e))}function resizeAndSaveImg(e,t,n,i){if(n<=0||n>1)throw new Error(`value of scale invalid: "${n}"`);return readImgInfo(e).pipe(mergeMap(r=>{const a={src:e,dst:t,width:r.width*n,height:r.height*n,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:n,pageHeight:i}=e,{width:r,marginBottom:a}=e.itemConfig;let{height:o}=e.itemConfig;const s=0,c=t*o;if(c+o>i&&(o=i-c),o/i<.1||o<100){const e={name:"",path:"",width:0,height:0,size:0};return of(e)}const p=basename(n),m=p.split(".")[0],l=moment().format("YYYYMMDD"),f=join(e.targetDir,`${l}-${m}-${Math.random()}-${t}.jpg`),u={dst:f,src:n,quality:100,cropWidth:r,cropHeight:o+a,x:0,y:c};return from(crop(u)).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 n=33;return e>=t?Math.ceil((e+33)/t):1}function getOcrZoneOptsByBankName(e,t){return t.get(e)}function cropImgAllZones(e,t,n,i){const r=[],a=new Set;for(const e of Object.values(n))e&&!a.has(e)&&a.add(e);for(const e of i){const t=e.zoneName;t&&a.has(t)&&r.push(e)}return from(r).pipe(mergeMap(n=>cropImgZone(e,t,n).pipe(map(e=>[n.zoneName,e]))),reduce((e,t)=>(e.set(t[0],t[1]),e),new Map))}function cropImgZone(e,t,n){const{zoneName:i,width:r,height:a,offsetX:o,offsetY:s}=n,c=join(t,`${i}-${Math.random()}.png`),p={dst:c,src:e,quality:100,cropWidth:r,cropHeight:a,x:o,y:s};return from(crop(p)).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,n){t||(t="eng");const i=`tesseract "${e}" "${n}" -l ${t}`;return run(i).pipe(last(),catchError(()=>of(void 0)),mapTo(void 0))}function retrieveKeyValuesFromOcrResult(e,t,n,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 r=n&&"function"==typeof n?n(e):e.toString("utf8");return retrieveValueByRegexp(r,t,i)}))}function getRegexpOptsByName(e,t){for(const n of Object.keys(t))if(n===e)return t[n]}function retrieveValueByRegexp(e,t,n=!1){const i=regexMatch(e,t,n);return n&&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,n=!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?(n&&console.info("----------multi matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<-------------ignore matched result---------------\n\n"),""):(n&&console.info("----------matched regex: --------------\x3e\n",t,"\n--- used regex ----: ",i,"\n<----------------------------\n\n"),t[0])}}function getOcrRetLangPath(e,t,n){const i=getOcrRetLangMap(e,t);if(!i)return"";const r=i.get(n);return r||""}function updateOcrRetTxtMap(e,t,n,i){if(!t||!n||!i)return;let r=getOcrRetLangMap(e,t);r||(r=new Map),n&&i&&updateOcrRetLangMap(r,n,i),e.set(t,r)}function updateOcrRetLangMap(e,t,n){e.set(t,n)}function getOcrRetLangMap(e,t){return e.get(t)}const moment$1=moment_;class Bvo{constructor(e){this.options=e;const t=+this.options.globalScale;this.options.globalScale=Number.isNaN(t)||t<=0?1:t,this.options.debug=!!this.options.debug;const{baseTmpDir:n,splitTmpDir:i,resizeImgDir:r}=e,a=n||initialBaseTmpDir,o=i||initialSplitTmpDir,s=r||initialResizeImgDir;from(createDir(a)).pipe(catchError(e=>(console.info(e),of(null))),concatMap(()=>createDir(o)),catchError(e=>(console.info(e),of(null))),concatMap(()=>createDir(s)),catchError(e=>(console.info(e),of(null)))).subscribe(()=>{},console.error)}run(e){return recognize(e,this.options)}}function recognize(e,t){const{bankZone:n,baseTmpDir:i,concurrent:r,debug:a,defaultOcrLang:o,jpegQuality:s,scale:c,splitTmpDir:p,resizeImgDir:m,voucherConfigMap:l,globalScale:f,skipImgDir:u}=t,g=i||initialBaseTmpDir,h=p||initialSplitTmpDir,d=m||initialResizeImgDir,y=u?join(u,moment$1().format("YYYYMMDD")):"",b="number"==typeof r&&r>0?r:cpus().length,w=parseVoucherConfigMapScale(l,f),k=parseOcrZoneScale(n,f),D=c/f,M=getBankRegexpOpts(w),v={baseDir:g,path:e,bankZone:k,bankRegexpOptsMap:M,debug:!!a,lang:o,skipImgDir:y},x=recognizePageBank(v).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),mergeMap(({bankName:e,pagePath:t})=>(a&&console.info("start split page"),splitPageToImgs(t,e,h,w))),mergeMap(({bankName:e,imgFile:t})=>{const n=getOcrFields(e,w);if(!n)throw new Error(`ocrFields not defined with bankName: "${e}"`);const i={bankName:e,baseDir:g,debug:!!a,defaultValue:"",imgFile:t,ocrFields:n,voucherConfigMap:w};return a&&console.info("recognize item"),recognizeFields(i).pipe(map(n=>(n.set("bank",e),n.set("filename",t.name.trim()),n.set("path",t.path.trim()),n)))},b>0?b:1),mergeMap(e=>{const t={retInfo:e,resizeDir:d,scale:D,jpegQuality:s,debug:!!a};return saveImgAndPrune(t)})),I=from(isFileExists(e)).pipe(filter(e=>e));return I.pipe(mergeMap(()=>x))}function recognizePageBank(e){const{baseDir:t,path:n,bankZone:i,bankRegexpOptsMap:r,debug:a,lang:o,skipImgDir:s}=e,c=join(t,zoneTmpDirPrefix,`${basename(n)}-${Math.random().toString()}`);return a&&console.info("recognize pageBank:",c,n),from(createDir(c)).pipe(catchError(e=>(console.info(e),of(null))),mergeMap(()=>cropImgZone(join(n),c,i)),concatMap(e=>runOcr(e.path,o,e.path).pipe(mapTo(e.path))),concatMap(e=>from(r.entries()).pipe(concatMap(([t,n])=>retrieveKeyValuesFromOcrResult(e+".txt",n,e=>e.toString().replace(/(?<=\S)[. ]{1,2}(?=\S)/g,"").replace(/\n{2,}/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:n})),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: "${n}", pagePath: "${i}" `),cpSkipImg(n,s)),a||rimraf(c).catch(console.info)}))}async function cpSkipImg(e,t){t&&(await isPathAcessible(t)||await createDir(t),copyFileAsync(e,join(t,basename(e))).catch(console.error))}function splitPageToImgs(e,t,n,i){const r=i.get(t);if(!r)throw new Error("bank config empty during split page to images");return splitPagetoItems(e,n,r).pipe(mergeMap(e=>{const n=from(e.values()).pipe(map(e=>({bankName:t,imgFile:e})));return n}))}function recognizeFields(e){const{bankName:t,baseDir:n,debug:i,defaultValue:r,imgFile:a,ocrFields:o,voucherConfigMap:s}=e,c=join(n,zoneTmpDirPrefix,`${basename(a.path)}`),p=getOcrZoneOptsByBankName(t,s);if(!p)throw new Error(`get bankConfig empty with bankName: "${t}"`);const m=from(createDir(c)).pipe(mergeMap(()=>cropImgAllZones(a.path,c,o,p.ocrZones)),concatMap(e=>{const t={bankConfig:p,ocrFields:o,defaultValue:r,debug:i,zoneImgMap:e};return batchOcrAndRetrieve(t)}),tap(()=>{i||setTimeout(e=>{rimraf(e).catch(console.info)},5e3,c)}));return m}function batchOcrAndRetrieve(e){const{zoneImgMap:t,bankConfig:n,ocrFields:i,defaultValue:r,debug:a}=e,{bankName:o}=n,s=from(t.entries()).pipe(concatMap(e=>ocrAndPickFromZoneImg(e,n,a)),reduce((e,t)=>e.set(t.fieldName,t.value),new Map),map(e=>e.set("bank",o)),map(e=>setDefaultValue(e,i,r)));return s}function setDefaultValue(e,t,n=""){const i=new Map;for(const n of Object.keys(t)){const t=e.get(n);"string"==typeof t?i.set(n,t):i.set(n,"")}return i}function processZoneImgRow(e){const{fieldName:t,value:n}=e,i=Object.assign({},e);switch(t){case"amount":i.value=n.trim().replace(/,/g,"");break;case"date":i.value=n.trim().replace(/\D/g,""),i.value&&"0"===i.value.slice(0,1)&&(i.value="2"+i.value);break;case"sn":case"destAccountNumber":case"paymentAccountNumber":i.value=n.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:n,regexpOpts:i}of e.values())i&&i.bank&&t.set(n,i.bank);if(!t.size)throw new Error("not BankRegexpOpts found, should not set");return t}function getOcrFields(e,t){const n=t.get(e);if(!n)throw new Error(`get ocrFields empty by bankName: "${e}"`);return n.ocrFields}function saveImgAndPrune(e){const{retInfo:t,resizeDir:n,debug:i,scale:r,jpegQuality:a}=e,o=t.get("filename"),s=t.get("path"),c=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 p=o.split(".").slice(0,-1).join("").split("-");p.splice(2,1);let m=p.join("-");c&&(m+=`-${c.replace(/[^\d\w]/g,"_")}`),m+=".jpg";const l=moment$1().format("YYYY-MM-DD"),f=join(n,l,m);return t.set("filename",m),resizeAndSaveImg(s,f,r,a).pipe(map(e=>(t.set("path",e.path),t)),tap(()=>{i||unlinkAsync(s).catch(console.info)}))}function genFieldLangs(e,t,n){return n&&"undefined"!=typeof n[e]&&Array.isArray(n[e])?n[e]:t}function ocrAndPickFromZoneImg(e,t,n=!1){const{ocrDefaultLangs:i,ocrFieldLangs:r,regexpOpts:a,ocrFields:o}=t,s=new Map;return from(Object.entries(o)).pipe(filter(t=>{const n=t[1];return!!n&&n===e[0]}),concatMap(t=>{const o=t[0],c=t[1];return ocrAndPickFieldFromZoneImg(o,c,e,a,i,r,n,s)}))}function ocrAndPickFieldFromZoneImg(e,t,n,i,r,a,o=!1,s){const[,c]=n,p=genFieldLangs(e,r,a),m=p.length-1,l=getRegexpOptsByName(e,i);if(!l)throw new Error(`got regexp empty by zoneName: "${e}"`);return from(p).pipe(concatMap(n=>{const i=getOcrRetLangPath(s,t,n);if(i)return retrieveKeyValuesFromOcrResult(i+".txt",l,prepareContent,o).pipe(map(r=>({fieldName:e,zoneName:t,value:r,usedLang:n,txtPath:i})));{const i=c.path,r=i.split(".").slice(0,-1).join(".")+`-${Math.random()}`;return runOcr(i,n,r).pipe(concatMap(()=>retrieveKeyValuesFromOcrResult(r+".txt",l,prepareContent,o).pipe(map(i=>({fieldName:e,zoneName:t,value:i,usedLang:n,txtPath:r})))))}}),tap(({zoneName:e,usedLang:t,txtPath:n})=>{updateOcrRetTxtMap(s,e,t,n)}),skipWhile((e,t)=>{const n=validateZoneImgRow(e.fieldName,e.value);return!n&&t!==m}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}function parseVoucherConfigMapScale(e,t){const n=new Map;for(const[i,r]of e){const e=Object.assign({},r),a=[];for(const n of e.ocrZones)a.push(parseOcrZoneScale(n,t));e.ocrZones=a,e.width=e.width*t,e.height=e.height*t,e.marginBottom=e.marginBottom*t,n.set(i,e)}return n}function parseOcrZoneScale(e,t){const n=Object.assign({},e);return n.width=n.width*t,n.height=n.height*t,n.offsetX=n.offsetX*t,n.offsetY=n.offsetY*t,n}export{initialBankZone,initialBaseTmpDir,initialResizeImgDir,initialSplitTmpDir,zoneTmpDirPrefix,Bvo,recognize,splitPageToImgs};
//# sourceMappingURL=bvocr.esm.min.js.map

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

*
* @version 1.3.0
* @version 1.3.1
* @author waiting

@@ -913,1 +913,2 @@ * @license MIT

exports.recognize = recognize;
exports.splitPageToImgs = splitPageToImgs;
import { Observable } from 'rxjs';
import { OcrOpts, OcrRetInfo } from './model';
import { BankName, OcrOpts, OcrRetInfo, PageToImgRet, VoucherConfigMap } from './model';
export declare class Bvo {

@@ -9,1 +9,2 @@ options: OcrOpts;

export declare function recognize(imgPath: string, options: OcrOpts): Observable<OcrRetInfo>;
export declare function splitPageToImgs(pagePath: string, bankName: BankName, targetDir: string, voucherConfigMap: VoucherConfigMap): Observable<PageToImgRet>;

@@ -154,3 +154,3 @@ import * as moment_ from 'moment'

// 切分页面为多张凭证
function splitPageToImgs(pagePath, bankName, targetDir, voucherConfigMap) {
export function splitPageToImgs(pagePath, bankName, targetDir, voucherConfigMap) {
const config = voucherConfigMap.get(bankName)

@@ -157,0 +157,0 @@

{
"name": "bank-voucher-ocr",
"author": "waiting",
"version": "1.3.0",
"version": "1.3.1",
"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