bank-voucher-ocr
Advanced tools
Comparing version 0.10.0 to 0.10.1
@@ -5,3 +5,3 @@ /** | ||
* | ||
* @version 0.10.0 | ||
* @version 0.10.1 | ||
* @author waiting | ||
@@ -222,3 +222,3 @@ * @license MIT | ||
return pageHeight >= itemHeight | ||
? Math.floor((pageHeight + delta) / itemHeight) | ||
? Math.ceil((pageHeight + delta) / itemHeight) | ||
: 1 // use one ! | ||
@@ -225,0 +225,0 @@ } |
@@ -5,3 +5,3 @@ /** | ||
* | ||
* @version 0.10.0 | ||
* @version 0.10.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{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,marginBottom:a}=e.itemConfig;let{height:o}=e.itemConfig;const s=0,c=t*o;c+o>i&&(o=i-c);const p=moment().format("YYYYMMDD"),m=join(e.targetDir,`${p}-${Math.random()}-${t}.jpg`),l={dst:m,src:r,quality:100,cropWidth:n,cropHeight:o+a,x:0,y:c};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,c=join(t,`${i}-${Math.random()}.png`),p={dst:c,src:e,quality:100,cropWidth:n,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){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;const t=+this.options.globalScale;this.options.globalScale=Number.isNaN(t)||t<=0?1:t,this.options.debug=!!this.options.debug;const{baseTmpDir:r,splitTmpDir:i,resizeImgDir:n}=e,a=r||initialBaseTmpDir,o=i||initialSplitTmpDir,s=n||initialResizeImgDir;from(createDir(a)).pipe(concatMap(()=>createDir(o)),concatMap(()=>createDir(s))).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:c,resizeImgDir:p,voucherConfigMap:m,globalScale:l}=t,f=i||initialBaseTmpDir,u=c||initialSplitTmpDir,g=p||initialResizeImgDir,h=parseVoucherConfigMapScale(m,l),d=parseOcrZoneScale(r,l),y=s/l,w=getBankRegexpOpts(h),b={baseDir:f,path:e,bankZone:d,bankRegexpOptsMap:w,debug:!!n,lang:a},k=recognizePageBank(b).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),concatMap(({bankName:e,pagePath:t})=>(n&&console.info("start split page"),splitPageToImgs(t,e,u,h))),concatMap(({bankName:e,imgFile:t})=>{const r=getOcrFields(e,h);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:h};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:g,scale:y,jpegQuality:o,debug:!!n};return saveImgAndPrune(t)})),D=from(isFileExists(e)).pipe(filter(e=>e));return D.pipe(mergeMap(()=>k))}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:c}=e,p=join(r,zoneTmpDirPrefix,moment$1().format("YYYYMMDD")+"-"+Math.random().toString()),m=getOcrZoneOptsByBankName(t,c);if(!m)throw new Error(`get bankConfig empty with bankName: "${t}"`);const l=from(createDir(p)).pipe(mergeMap(()=>cropImgAllZones(o.path,p,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,c=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))),p=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||c.subscribe()));return p}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"),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=c?`${(new Date).getTime()}-${c.replace(/[^\d\w]/g,"_")}.jpg`:o,m=moment$1().format("YYYY-MM-DD"),l=join(r,m,p);return t.set("filename",p),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),c=s.length-1,p=getRegexpOptsByName(e,r);if(!p)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",p,prepareContent,a).pipe(map(t=>({fieldName:e,value:t})))),skipWhile((e,t)=>{const r=validateZoneImgRow(e.fieldName,e.value);return!r&&t!==c}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}function parseVoucherConfigMapScale(e,t){const r=new Map;for(const[i,n]of e){const e=Object.assign({},n),a=[];for(const r of e.ocrZones)a.push(parseOcrZoneScale(r,t));e.ocrZones=a,e.width=e.width*t,e.height=e.height*t,e.marginBottom=e.marginBottom*t,r.set(i,e)}return r}function parseOcrZoneScale(e,t){const r=Object.assign({},e);return r.width=r.width*t,r.height=r.height*t,r.offsetX=r.offsetX*t,r.offsetY=r.offsetY*t,r}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,marginBottom:a}=e.itemConfig;let{height:o}=e.itemConfig;const s=0,c=t*o;c+o>i&&(o=i-c);const p=moment().format("YYYYMMDD"),m=join(e.targetDir,`${p}-${Math.random()}-${t}.jpg`),l={dst:m,src:r,quality:100,cropWidth:n,cropHeight:o+a,x:0,y:c};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.ceil((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,c=join(t,`${i}-${Math.random()}.png`),p={dst:c,src:e,quality:100,cropWidth:n,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){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;const t=+this.options.globalScale;this.options.globalScale=Number.isNaN(t)||t<=0?1:t,this.options.debug=!!this.options.debug;const{baseTmpDir:r,splitTmpDir:i,resizeImgDir:n}=e,a=r||initialBaseTmpDir,o=i||initialSplitTmpDir,s=n||initialResizeImgDir;from(createDir(a)).pipe(concatMap(()=>createDir(o)),concatMap(()=>createDir(s))).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:c,resizeImgDir:p,voucherConfigMap:m,globalScale:l}=t,f=i||initialBaseTmpDir,u=c||initialSplitTmpDir,g=p||initialResizeImgDir,h=parseVoucherConfigMapScale(m,l),d=parseOcrZoneScale(r,l),y=s/l,w=getBankRegexpOpts(h),b={baseDir:f,path:e,bankZone:d,bankRegexpOptsMap:w,debug:!!n,lang:a},k=recognizePageBank(b).pipe(filter(({bankName:e})=>!!e&&"n/a"!==e),concatMap(({bankName:e,pagePath:t})=>(n&&console.info("start split page"),splitPageToImgs(t,e,u,h))),concatMap(({bankName:e,imgFile:t})=>{const r=getOcrFields(e,h);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:h};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:g,scale:y,jpegQuality:o,debug:!!n};return saveImgAndPrune(t)})),D=from(isFileExists(e)).pipe(filter(e=>e));return D.pipe(mergeMap(()=>k))}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:c}=e,p=join(r,zoneTmpDirPrefix,moment$1().format("YYYYMMDD")+"-"+Math.random().toString()),m=getOcrZoneOptsByBankName(t,c);if(!m)throw new Error(`get bankConfig empty with bankName: "${t}"`);const l=from(createDir(p)).pipe(mergeMap(()=>cropImgAllZones(o.path,p,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,c=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))),p=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||c.subscribe()));return p}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"),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=c?`${(new Date).getTime()}-${c.replace(/[^\d\w]/g,"_")}.jpg`:o,m=moment$1().format("YYYY-MM-DD"),l=join(r,m,p);return t.set("filename",p),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),c=s.length-1,p=getRegexpOptsByName(e,r);if(!p)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",p,prepareContent,a).pipe(map(t=>({fieldName:e,value:t})))),skipWhile((e,t)=>{const r=validateZoneImgRow(e.fieldName,e.value);return!r&&t!==c}),take(1),map(e=>("string"!=typeof e.value&&(e.value=""),e)),map(processZoneImgRow))}function parseVoucherConfigMapScale(e,t){const r=new Map;for(const[i,n]of e){const e=Object.assign({},n),a=[];for(const r of e.ocrZones)a.push(parseOcrZoneScale(r,t));e.ocrZones=a,e.width=e.width*t,e.height=e.height*t,e.marginBottom=e.marginBottom*t,r.set(i,e)}return r}function parseOcrZoneScale(e,t){const r=Object.assign({},e);return r.width=r.width*t,r.height=r.height*t,r.offsetX=r.offsetX*t,r.offsetY=r.offsetY*t,r}export{initialBankZone,initialBaseTmpDir,initialResizeImgDir,initialSplitTmpDir,zoneTmpDirPrefix,Bvo,recognize}; | ||
//# sourceMappingURL=bvocr.esm.min.js.map |
@@ -5,3 +5,3 @@ /** | ||
* | ||
* @version 0.10.0 | ||
* @version 0.10.1 | ||
* @author waiting | ||
@@ -228,3 +228,3 @@ * @license MIT | ||
return pageHeight >= itemHeight | ||
? Math.floor((pageHeight + delta) / itemHeight) | ||
? Math.ceil((pageHeight + delta) / itemHeight) | ||
: 1 // use one ! | ||
@@ -231,0 +231,0 @@ } |
@@ -109,4 +109,4 @@ import { crop, info as getImgInfo, resize } from 'easyimage' | ||
return pageHeight >= itemHeight | ||
? Math.floor((pageHeight + delta) / itemHeight) | ||
? Math.ceil((pageHeight + delta) / itemHeight) | ||
: 1 // use one ! | ||
} |
{ | ||
"name": "bank-voucher-ocr", | ||
"author": "waiting", | ||
"version": "0.10.0", | ||
"version": "0.10.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
153555