@twintag/twintag-core 0.2.279-fix-ocr-scanner-update-ca129a0ddafcef2f7b1df1960cc45889702617c1 → 0.2.279-fix-ocr-scanner-update-ce883df10b1d4b81e7cf691ed723691d6f7bc81c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1938,15 +1938,15 @@ const TwintagOcrScanner = class {
1938
1938
  }
1939
1939
  drawInCanvas() {
1940
1940
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
1941
- const xLength = stage * this.cropX;
1942
- const yLength = stage * this.cropY;
1941
+ const width = stage * this.cropX;
1942
+ const height = stage * this.cropY;
1943
1943
  const center = {
1944
1944
  x: this.video.videoWidth / 2,
1945
1945
  y: this.video.videoHeight / 2,
1946
1946
  };
1947
- const sx = center.x - xLength / 2;
1948
- const sy = center.y - yLength / 2;
1949
- this.context.drawImage(this.video, sx, sy, xLength, yLength, 0, 0, stage, stage);
1947
+ const sx = center.x - width / 2;
1948
+ const sy = center.y - height / 2;
1949
+ this.context.drawImage(this.video, sx, sy, width, height, 0, 0, width, height);
1950
1950
  }
1951
1951
  async updateStream(constraints) {
1952
1952
  if (this.stream) {
@@ -2053,8 +2053,10 @@ const TwintagOcrScanner = class {
2053
2053
  onComplete: () => {
2054
2054
  this.streamIsActive.emit(true);
2055
2055
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
2056
- this.canvas.width = stage;
2057
- this.canvas.height = stage;
2056
+ const width = stage * this.cropX;
2057
+ const height = stage * this.cropY;
2058
+ this.canvas.width = width;
2059
+ this.canvas.height = height;
2058
2060
  this.canRecognize.emit(true);
2059
2061
  }
2060
2062
  });
@@ -206,7 +206,7 @@ class IndexedDbService {
206
206
  /**
207
207
  * The SDK version.
208
208
  */
209
- const VERSION = '0.2.279-fix-ocr-scanner-update-ca129a0ddafcef2f7b1df1960cc45889702617c1';
209
+ const VERSION = '0.2.279-fix-ocr-scanner-update-ce883df10b1d4b81e7cf691ed723691d6f7bc81c';
210
210
 
211
211
  class TwintagErrorValue {
212
212
  }
@@ -42,15 +42,15 @@ export class TwintagOcrScanner {
42
42
  }
43
43
  drawInCanvas() {
44
44
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
45
- const xLength = stage * this.cropX;
46
- const yLength = stage * this.cropY;
45
+ const width = stage * this.cropX;
46
+ const height = stage * this.cropY;
47
47
  const center = {
48
48
  x: this.video.videoWidth / 2,
49
49
  y: this.video.videoHeight / 2,
50
50
  };
51
- const sx = center.x - xLength / 2;
52
- const sy = center.y - yLength / 2;
53
- this.context.drawImage(this.video, sx, sy, xLength, yLength, 0, 0, stage, stage);
51
+ const sx = center.x - width / 2;
52
+ const sy = center.y - height / 2;
53
+ this.context.drawImage(this.video, sx, sy, width, height, 0, 0, width, height);
54
54
  }
55
55
  async updateStream(constraints) {
56
56
  if (this.stream) {
@@ -157,8 +157,10 @@ export class TwintagOcrScanner {
157
157
  onComplete: () => {
158
158
  this.streamIsActive.emit(true);
159
159
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
160
- this.canvas.width = stage;
161
- this.canvas.height = stage;
160
+ const width = stage * this.cropX;
161
+ const height = stage * this.cropY;
162
+ this.canvas.width = width;
163
+ this.canvas.height = height;
162
164
  this.canRecognize.emit(true);
163
165
  }
164
166
  });
@@ -2,4 +2,4 @@
2
2
  /**
3
3
  * The library version.
4
4
  */
5
- export const VERSION = '0.2.279-fix-ocr-scanner-update-ca129a0ddafcef2f7b1df1960cc45889702617c1';
5
+ export const VERSION = '0.2.279-fix-ocr-scanner-update-ce883df10b1d4b81e7cf691ed723691d6f7bc81c';
@@ -1936,15 +1936,15 @@ const TwintagOcrScanner$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLE
1936
1936
  }
1937
1937
  drawInCanvas() {
1938
1938
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
1939
- const xLength = stage * this.cropX;
1940
- const yLength = stage * this.cropY;
1939
+ const width = stage * this.cropX;
1940
+ const height = stage * this.cropY;
1941
1941
  const center = {
1942
1942
  x: this.video.videoWidth / 2,
1943
1943
  y: this.video.videoHeight / 2,
1944
1944
  };
1945
- const sx = center.x - xLength / 2;
1946
- const sy = center.y - yLength / 2;
1947
- this.context.drawImage(this.video, sx, sy, xLength, yLength, 0, 0, stage, stage);
1945
+ const sx = center.x - width / 2;
1946
+ const sy = center.y - height / 2;
1947
+ this.context.drawImage(this.video, sx, sy, width, height, 0, 0, width, height);
1948
1948
  }
1949
1949
  async updateStream(constraints) {
1950
1950
  if (this.stream) {
@@ -2051,8 +2051,10 @@ const TwintagOcrScanner$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLE
2051
2051
  onComplete: () => {
2052
2052
  this.streamIsActive.emit(true);
2053
2053
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
2054
- this.canvas.width = stage;
2055
- this.canvas.height = stage;
2054
+ const width = stage * this.cropX;
2055
+ const height = stage * this.cropY;
2056
+ this.canvas.width = width;
2057
+ this.canvas.height = height;
2056
2058
  this.canRecognize.emit(true);
2057
2059
  }
2058
2060
  });
@@ -223,7 +223,7 @@ class IndexedDbService {
223
223
  /**
224
224
  * The SDK version.
225
225
  */
226
- const VERSION = '0.2.279-fix-ocr-scanner-update-ca129a0ddafcef2f7b1df1960cc45889702617c1';
226
+ const VERSION = '0.2.279-fix-ocr-scanner-update-ce883df10b1d4b81e7cf691ed723691d6f7bc81c';
227
227
 
228
228
  class TwintagErrorValue {
229
229
  }
@@ -1934,15 +1934,15 @@ const TwintagOcrScanner = class {
1934
1934
  }
1935
1935
  drawInCanvas() {
1936
1936
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
1937
- const xLength = stage * this.cropX;
1938
- const yLength = stage * this.cropY;
1937
+ const width = stage * this.cropX;
1938
+ const height = stage * this.cropY;
1939
1939
  const center = {
1940
1940
  x: this.video.videoWidth / 2,
1941
1941
  y: this.video.videoHeight / 2,
1942
1942
  };
1943
- const sx = center.x - xLength / 2;
1944
- const sy = center.y - yLength / 2;
1945
- this.context.drawImage(this.video, sx, sy, xLength, yLength, 0, 0, stage, stage);
1943
+ const sx = center.x - width / 2;
1944
+ const sy = center.y - height / 2;
1945
+ this.context.drawImage(this.video, sx, sy, width, height, 0, 0, width, height);
1946
1946
  }
1947
1947
  async updateStream(constraints) {
1948
1948
  if (this.stream) {
@@ -2049,8 +2049,10 @@ const TwintagOcrScanner = class {
2049
2049
  onComplete: () => {
2050
2050
  this.streamIsActive.emit(true);
2051
2051
  const stage = Math.min(this.video.videoWidth, this.video.videoHeight);
2052
- this.canvas.width = stage;
2053
- this.canvas.height = stage;
2052
+ const width = stage * this.cropX;
2053
+ const height = stage * this.cropY;
2054
+ this.canvas.width = width;
2055
+ this.canvas.height = height;
2054
2056
  this.canRecognize.emit(true);
2055
2057
  }
2056
2058
  });
@@ -202,7 +202,7 @@ class IndexedDbService {
202
202
  /**
203
203
  * The SDK version.
204
204
  */
205
- const VERSION = '0.2.279-fix-ocr-scanner-update-ca129a0ddafcef2f7b1df1960cc45889702617c1';
205
+ const VERSION = '0.2.279-fix-ocr-scanner-update-ce883df10b1d4b81e7cf691ed723691d6f7bc81c';
206
206
 
207
207
  class TwintagErrorValue {
208
208
  }
@@ -1 +1 @@
1
- import{r as t,c as r,h as e,H as n}from"./p-cb286d41.js";import{g as a}from"./p-60325667.js";import{c as o,a as i,b as c}from"./p-814af281.js";o((function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,a="function"==typeof Symbol?Symbol:{},o=a.iterator||"@@iterator",i=a.asyncIterator||"@@asyncIterator",c=a.toStringTag||"@@toStringTag";function s(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{s({},"")}catch(t){s=function(t,r,e){return t[r]=e}}function l(t,r,e,n){var a=Object.create((r&&r.prototype instanceof g?r:g).prototype),o=new x(n||[]);return a._invoke=function(t,r,e){var n=d;return function(a,o){if(n===f)throw new Error("Generator is already running");if(n===p){if("throw"===a)throw o;return N()}for(e.method=a,e.arg=o;;){var i=e.delegate;if(i){var c=A(i,e);if(c){if(c===w)continue;return c}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===d)throw n=p,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=f;var s=h(t,r,e);if("normal"===s.type){if(n=e.done?p:u,s.arg===w)continue;return{value:s.arg,done:e.done}}"throw"===s.type&&(n=p,e.method="throw",e.arg=s.arg)}}}(t,e,o),a}function h(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=l;var d="suspendedStart",u="suspendedYield",f="executing",p="completed",w={};function g(){}function v(){}function y(){}var m={};m[o]=function(){return this};var b=Object.getPrototypeOf,L=b&&b(b(T([])));L&&L!==e&&n.call(L,o)&&(m=L);var k=y.prototype=g.prototype=Object.create(m);function S(t){["next","throw","return"].forEach((function(r){s(t,r,(function(t){return this._invoke(r,t)}))}))}function E(t,r){function e(a,o,i,c){var s=h(t[a],t,o);if("throw"!==s.type){var l=s.arg,d=l.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(t){e("next",t,i,c)}),(function(t){e("throw",t,i,c)})):r.resolve(d).then((function(t){l.value=t,i(l)}),(function(t){return e("throw",t,i,c)}))}c(s.arg)}var a;this._invoke=function(t,n){function o(){return new r((function(r,a){e(t,n,r,a)}))}return a=a?a.then(o,o):o()}}function A(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,A(t,e),"throw"===e.method))return w;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return w}var a=h(n,t.iterator,e.arg);if("throw"===a.type)return e.method="throw",e.arg=a.arg,e.delegate=null,w;var o=a.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,w):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,w)}function O(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function R(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function x(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var a=-1,i=function e(){for(;++a<t.length;)if(n.call(t,a))return e.value=t[a],e.done=!1,e;return e.value=r,e.done=!0,e};return i.next=i}}return{next:N}}function N(){return{value:r,done:!0}}return v.prototype=k.constructor=y,y.constructor=v,v.displayName=s(y,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===v||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,s(t,c,"GeneratorFunction")),t.prototype=Object.create(k),t},t.awrap=function(t){return{__await:t}},S(E.prototype),E.prototype[i]=function(){return this},t.AsyncIterator=E,t.async=function(r,e,n,a,o){void 0===o&&(o=Promise);var i=new E(l(r,e,n,a),o);return t.isGeneratorFunction(e)?i:i.next().then((function(t){return t.done?t.value:i.next()}))},S(k),s(k,c,"Generator"),k[o]=function(){return this},k.toString=function(){return"[object Generator]"},t.keys=function(t){var r=[];for(var e in t)r.push(e);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=T,x.prototype={constructor:x,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(R),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function a(n,a){return c.type="throw",c.arg=t,e.next=n,a&&(e.method="next",e.arg=r),!!a}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],c=i.completion;if("root"===i.tryLoc)return a("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev<i.catchLoc)return a(i.catchLoc,!0);if(this.prev<i.finallyLoc)return a(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return a(i.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return a(i.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var a=this.tryEntries[e];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev<a.finallyLoc){var o=a;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=r&&r<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=t,i.arg=r,o?(this.method="next",this.next=o.finallyLoc,w):this.complete(i)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),w},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),R(e),w}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var a=n.arg;R(e)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:T(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),w}},t}(t.exports);try{regeneratorRuntime=r}catch(t){Function("r","regeneratorRuntime = r")(r)}}));var s=(t,r)=>`${t}-${r}-${Math.random().toString(16).slice(3,8)}`;let l=0;var h=({id:t,action:r,payload:e={}})=>{let n=t;return void 0===n&&(n=s("Job",l),l+=1),{id:n,action:r,payload:e}};let d=!1;var u={logging:d,setLogging:t=>{d=t},log:(...t)=>d?console.log.apply(void 0,t):null};const{log:f}=u;let p=0;var w=i.process;const g="browser"===(t=>{const r={};return"undefined"!=typeof WorkerGlobalScope?r.type="webworker":"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||void 0!==w&&"object"==typeof w.versions&&w.versions.electron||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0?r.type="electron":"object"==typeof document?r.type="browser":"object"==typeof w&&"function"==typeof c&&(r.type="node"),r[t]})("type")?t=>new URL(t,window.location.href).href:t=>t;var v={TESSERACT_ONLY:0,LSTM_ONLY:1,TESSERACT_LSTM_COMBINED:2,DEFAULT:3};const y=t=>new Promise(((r,e)=>{const n=new FileReader;n.onload=()=>{r(n.result)},n.onerror=({target:{error:{code:t}}})=>{e(Error(`File could not be read! Code=${t}`))},n.readAsArrayBuffer(t)})),m=async t=>{let r=t;if(void 0===t)return"undefined";if("string"==typeof t)if(/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(t))r=atob(t.split(",")[1]).split("").map((t=>t.charCodeAt(0)));else{const e=await fetch(t);r=await e.arrayBuffer()}else if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)"IMG"===t.tagName&&(r=await m(t.src)),"VIDEO"===t.tagName&&(r=await m(t.poster)),"CANVAS"===t.tagName&&await new Promise((e=>{t.toBlob((async t=>{r=await y(t),e()}))}));else if("undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas){const e=await t.convertToBlob();r=await y(e)}else(t instanceof File||t instanceof Blob)&&(r=await y(t));return new Uint8Array(r)};var b={defaultOptions:{workerBlobURL:!0,logger:()=>{},workerPath:"https://cdn.jsdelivr.net/npm/tesseract.js@v5.1.0/dist/worker.min.js"},spawnWorker:({workerPath:t,workerBlobURL:r})=>{let e;if(Blob&&URL&&r){const r=new Blob([`importScripts("${t}");`],{type:"application/javascript"});e=new Worker(URL.createObjectURL(r))}else e=new Worker(t);return e},terminateWorker:t=>{t.terminate()},onMessage:(t,r)=>{t.onmessage=({data:t})=>{r(t)}},send:async(t,r)=>{t.postMessage(r)},loadImage:m};const{log:L}=u,{defaultOptions:k,spawnWorker:S,terminateWorker:E,onMessage:A,loadImage:O,send:R}=b;let x=0;var T=async(t="eng",r=v.LSTM_ONLY,e={},n={})=>{const a=s("Worker",x),{logger:o,errorHandler:i,...c}=(t=>{const r={...t};return["corePath","workerPath","langPath"].forEach((e=>{t[e]&&(r[e]=g(r[e]))})),r})({...k,...e}),l={},d={},u="string"==typeof t?t.split("+"):t;let f=r,p=n;const w=[v.DEFAULT,v.LSTM_ONLY].includes(r)&&!c.legacyCore;let y,m;const b=new Promise(((t,r)=>{m=t,y=r}));let T=S(c);T.onerror=t=>{y(t.message)},x+=1;const N=(t,r)=>{l[t]=r},I=(t,r)=>{d[t]=r},_=({id:t,action:r,payload:e})=>new Promise(((n,o)=>{L(`[${a}]: Start ${t}, action=${r}`);const i=`${r}-${t}`;N(i,n),I(i,o),R(T,{workerId:a,jobId:t,action:r,payload:e})})),j=(t,r)=>_(h({id:r,action:"loadLanguage",payload:{langs:t,options:{langPath:c.langPath,dataPath:c.dataPath,cachePath:c.cachePath,cacheMethod:c.cacheMethod,gzip:c.gzip,lstmOnly:[v.LSTM_ONLY,v.TESSERACT_LSTM_COMBINED].includes(f)&&!c.legacyLang}}})),P=(t,r,e,n)=>_(h({id:n,action:"initialize",payload:{langs:t,oem:r,config:e}}));A(T,(({workerId:t,jobId:r,status:e,action:n,data:a})=>{const c=`${n}-${r}`;if("resolve"===e){L(`[${t}]: Complete ${r}`);let e=a;"recognize"===n?e=(t=>{const r=[],e=[],n=[],a=[],o=[];return t.blocks&&t.blocks.forEach((i=>{i.paragraphs.forEach((r=>{r.lines.forEach((e=>{e.words.forEach((n=>{n.symbols.forEach((a=>{o.push({...a,page:t,block:i,paragraph:r,line:e,word:n})})),a.push({...n,page:t,block:i,paragraph:r,line:e})})),n.push({...e,page:t,block:i,paragraph:r})})),e.push({...r,page:t,block:i})})),r.push({...i,page:t})})),{...t,blocks:r,paragraphs:e,lines:n,words:a,symbols:o}})(a):"getPDF"===n&&(e=Array.from({...a,length:Object.keys(a).length})),l[c]({jobId:r,data:e})}else if("reject"===e){if(d[c](a),"load"===n&&y(a),!i)throw Error(a);i(a)}else"progress"===e&&o({...a,userJobId:r})}));const M={id:a,worker:T,setResolve:N,setReject:I,load:()=>console.warn("`load` is depreciated and should be removed from code (workers now come pre-loaded)"),writeText:(t,r,e)=>_(h({id:e,action:"FS",payload:{method:"writeFile",args:[t,r]}})),readText:(t,r)=>_(h({id:r,action:"FS",payload:{method:"readFile",args:[t,{encoding:"utf8"}]}})),removeFile:(t,r)=>_(h({id:r,action:"FS",payload:{method:"unlink",args:[t]}})),FS:(t,r,e)=>_(h({id:e,action:"FS",payload:{method:t,args:r}})),loadLanguage:()=>console.warn("`loadLanguage` is depreciated and should be removed from code (workers now come with language pre-loaded)"),initialize:()=>console.warn("`initialize` is depreciated and should be removed from code (workers now come pre-initialized)"),reinitialize:(t="eng",r,e,n)=>{if(w&&[v.TESSERACT_ONLY,v.TESSERACT_LSTM_COMBINED].includes(r))throw Error("Legacy model requested but code missing.");const a=r||f;f=a;const o=e||p;p=o;const i=("string"==typeof t?t.split("+"):t).filter((t=>!u.includes(t)));return u.push(...i),i.length>0?j(i,n).then((()=>P(t,a,o,n))):P(t,a,o,n)},setParameters:(t={},r)=>_(h({id:r,action:"setParameters",payload:{params:t}})),recognize:async(t,r={},e={blocks:!0,text:!0,hocr:!0,tsv:!0},n)=>_(h({id:n,action:"recognize",payload:{image:await O(t),options:r,output:e}})),getPDF:(t="Tesseract OCR Result",r=!1,e)=>(console.log("`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead."),_(h({id:e,action:"getPDF",payload:{title:t,textonly:r}}))),detect:async(t,r)=>{if(w)throw Error("`worker.detect` requires Legacy model, which was not loaded.");return _(h({id:r,action:"detect",payload:{image:await O(t)}}))},terminate:async()=>(null!==T&&(E(T),T=null),Promise.resolve())};return _(h({id:undefined,action:"load",payload:{options:{lstmOnly:w,corePath:c.corePath,logging:c.logging}}})).then((()=>j(t))).then((()=>P(t,r,n))).then((()=>m(M))).catch((()=>{})),b},N={recognize:async(t,r,e)=>{const n=await T(r,1,e);return n.recognize(t).finally((async()=>{await n.terminate()}))},detect:async(t,r)=>{const e=await T("osd",0,r);return e.detect(t).finally((async()=>{await e.terminate()}))}};const{setLogging:I}=u;var _={languages:{AFR:"afr",AMH:"amh",ARA:"ara",ASM:"asm",AZE:"aze",AZE_CYRL:"aze_cyrl",BEL:"bel",BEN:"ben",BOD:"bod",BOS:"bos",BUL:"bul",CAT:"cat",CEB:"ceb",CES:"ces",CHI_SIM:"chi_sim",CHI_TRA:"chi_tra",CHR:"chr",CYM:"cym",DAN:"dan",DEU:"deu",DZO:"dzo",ELL:"ell",ENG:"eng",ENM:"enm",EPO:"epo",EST:"est",EUS:"eus",FAS:"fas",FIN:"fin",FRA:"fra",FRK:"frk",FRM:"frm",GLE:"gle",GLG:"glg",GRC:"grc",GUJ:"guj",HAT:"hat",HEB:"heb",HIN:"hin",HRV:"hrv",HUN:"hun",IKU:"iku",IND:"ind",ISL:"isl",ITA:"ita",ITA_OLD:"ita_old",JAV:"jav",JPN:"jpn",KAN:"kan",KAT:"kat",KAT_OLD:"kat_old",KAZ:"kaz",KHM:"khm",KIR:"kir",KOR:"kor",KUR:"kur",LAO:"lao",LAT:"lat",LAV:"lav",LIT:"lit",MAL:"mal",MAR:"mar",MKD:"mkd",MLT:"mlt",MSA:"msa",MYA:"mya",NEP:"nep",NLD:"nld",NOR:"nor",ORI:"ori",PAN:"pan",POL:"pol",POR:"por",PUS:"pus",RON:"ron",RUS:"rus",SAN:"san",SIN:"sin",SLK:"slk",SLV:"slv",SPA:"spa",SPA_OLD:"spa_old",SQI:"sqi",SRP:"srp",SRP_LATN:"srp_latn",SWA:"swa",SWE:"swe",SYR:"syr",TAM:"tam",TEL:"tel",TGK:"tgk",TGL:"tgl",THA:"tha",TIR:"tir",TUR:"tur",UIG:"uig",UKR:"ukr",URD:"urd",UZB:"uzb",UZB_CYRL:"uzb_cyrl",VIE:"vie",YID:"yid"},OEM:v,PSM:{OSD_ONLY:"0",AUTO_OSD:"1",AUTO_ONLY:"2",AUTO:"3",SINGLE_COLUMN:"4",SINGLE_BLOCK_VERT_TEXT:"5",SINGLE_BLOCK:"6",SINGLE_LINE:"7",SINGLE_WORD:"8",CIRCLE_WORD:"9",SINGLE_CHAR:"10",SPARSE_TEXT:"11",SPARSE_TEXT_OSD:"12",RAW_LINE:"13"},createScheduler:()=>{const t=s("Scheduler",p),r={},e={};let n=[];p+=1;const a=()=>Object.keys(r).length,o=()=>{if(0!==n.length){const t=Object.keys(r);for(let a=0;a<t.length;a+=1)if(void 0===e[t[a]]){n[0](r[t[a]]);break}}};return{addWorker:e=>(r[e.id]=e,f(`[${t}]: Add ${e.id}`),f(`[${t}]: Number of workers=${a()}`),o(),e.id),addJob:async(r,...i)=>{if(0===a())throw Error(`[${t}]: You need to have at least one worker before adding jobs`);return((r,a)=>new Promise(((i,c)=>{const s=h({action:r,payload:a});n.push((async t=>{n.shift(),e[t.id]=s;try{i(await t[r].apply(void 0,[...a,s.id]))}catch(t){c(t)}finally{delete e[t.id],o()}})),f(`[${t}]: Add ${s.id} to JobQueue`),f(`[${t}]: JobQueue length=${n.length}`),o()})))(r,i)},terminate:async()=>{Object.keys(r).forEach((async t=>{await r[t].terminate()})),n=[]},getQueueLen:()=>n.length,getNumWorkers:a}},createWorker:T,setLogging:I,...N};const j=class{constructor(e){t(this,e),this.symbol=r(this,"symbol",7),this.streamIsActive=r(this,"streamIsActive",7),this.canRecognize=r(this,"canRecognize",7),this.frame=r(this,"frame",7),this.devices=[],this.stream=null,this.cropX=1,this.cropY=1,this.zoom=0}async ocrHandler(){const{text:t,frame:r}=await this.readBarcodeFromCanvas();this.symbol.emit({text:t,format:"OCR"}),this.frame.emit(r),this.stopStream()}async connectedCallback(){this.worker=await _.createWorker("eng")}async componentDidLoad(){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.videoContainer.style.setProperty("--crop-x",""+50*(1-this.cropX)),this.videoContainer.style.setProperty("--crop-y",""+50*(1-this.cropY)),await this.startStream()}async readBarcodeFromCanvas(){await this.updateVideoZoom(),this.drawInCanvas();const t=this.canvas.toDataURL("image/png"),{data:{text:r}}=await this.worker.recognize(t);return{text:r,frame:t}}drawInCanvas(){const t=Math.min(this.video.videoWidth,this.video.videoHeight),r=t*this.cropX,e=t*this.cropY;this.context.drawImage(this.video,this.video.videoWidth/2-r/2,this.video.videoHeight/2-e/2,r,e,0,0,t,t)}async updateStream(t){this.stream&&this.stream.getTracks().forEach((t=>t.stop()));try{this.stream=await navigator.mediaDevices.getUserMedia(t),this.video.srcObject=this.stream,this.video.setAttribute("playsinline","true"),await this.video.play()}catch(t){console.error(t)}}async getTrackSettings(t){try{return(await navigator.mediaDevices.getUserMedia(t)).getVideoTracks()[0].getSettings()}catch(t){console.error(t)}}async getMedia(t){t.video.width={min:1080,ideal:1600,max:1920};try{await this.updateStream(t);const r=await navigator.mediaDevices.enumerateDevices();if(this.devices=r.filter((t=>"videoinput"===t.kind.toLowerCase()&&t.label.toLowerCase().includes("back"))),0===this.devices.length)return;1===this.devices.length&&(t.video.deviceId={exact:this.devices[0].deviceId},await this.updateStream(t));let e=this.devices.length-1;const n=this.devices.map((t=>{const r=t.label.match(/\b([0-9]+)MP?\b/i);return null!=r?parseInt(r[1],10):NaN}));n.some((t=>isNaN(t)))||(e=n.lastIndexOf(Math.max(...n)));const a=this.devices[e];if(a)return t.video.deviceId={exact:a.deviceId},void await this.updateStream(t);const o=await this.getTrackSettings(t);o.focusDistance&&(t.video.advanced=[{focusMode:"continuous",focusDistance:o.focusDistance}],await this.updateStream(t))}catch(t){console.error(t)}}async updateVideoZoom(){const[t]=this.stream.getVideoTracks();if(t.getCapabilities&&"function"==typeof t.applyConstraints){const r=t.getCapabilities();if("zoom"in t.getSettings()){const e=r.zoom.min,n=r.zoom.max;await t.applyConstraints({advanced:[{zoom:e+(n-e)*this.zoom}]})}}}async startStream(){const t={audio:!1,video:{aspectRatio:{ideal:1},facingMode:"environment"}};navigator.mediaDevices.getSupportedConstraints().zoom&&(t.video.zoom=!0),await this.getMedia(t),await this.updateVideoZoom(),a.to(this.videoContainer,{duration:.2,opacity:1,onComplete:()=>{this.streamIsActive.emit(!0);const t=Math.min(this.video.videoWidth,this.video.videoHeight);this.canvas.width=t,this.canvas.height=t,this.canRecognize.emit(!0)}})}stopStream(){a.to(this.videoContainer,{duration:.2,opacity:0,onComplete:async()=>{this.stream.getTracks().forEach((t=>t.stop())),this.video.srcObject=null,this.context.clearRect(0,0,this.context.canvas.width,this.context.canvas.height),await this.worker.terminate(),this.canRecognize.emit(!1)}})}disconnectedCallback(){this.stopStream()}render(){return e(n,null,e("div",{class:"video-container",ref:t=>this.videoContainer=t},e("div",{class:"video-corners"}),e("video",{crossOrigin:"Anonymous",autoplay:!0,playsinline:!0,ref:t=>this.video=t})))}};j.style=':host{--twintag-scanner-bg-select-cameras:white;--twintag-scanner-text-select-cameras:black;--twintag-scanner-radius-select-cameras:6px 0 0 0;--twintag-scanner-min-height:min-content;--twintag-scanner-corners-color:white;--twintag-scanner-corners-width:4px;--twintag-scanner-corners-length:36px;--twintag-scanner-corners-offset:24px;display:grid;place-items:center;position:relative;width:100%}:host .icon-container{display:grid;place-items:center;position:absolute;inset:0;z-index:-2222}:host .icon-container .check-icon{opacity:0;z-index:2222}:host .video-container{--crop:0;--crop-x:var(--crop);--crop-y:var(--crop);display:flex;align-items:center;justify-content:center;position:relative;width:100%;height:100%;opacity:0;overflow:hidden;z-index:1}:host .video-container::after{content:"";position:absolute;width:100%;height:100%;opacity:inherit;background:rgba(0, 0, 0, 0.5);-webkit-clip-path:polygon(0% 0%, 0% 100%, calc(var(--crop-x) * 1%) 100%, calc(var(--crop-x) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) 100%, 100% 100%, 100% 0%);clip-path:polygon(0% 0%, 0% 100%, calc(var(--crop-x) * 1%) 100%, calc(var(--crop-x) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) 100%, 100% 100%, 100% 0%)}:host .video-container:before{display:block;content:"";width:100%;padding-top:100%}:host .video-container .video-corners{position:absolute;width:calc((1 - var(--crop-x) / 50) * 100% + var(--twintag-scanner-corners-offset));height:calc((1 - var(--crop-y) / 50) * 100% + var(--twintag-scanner-corners-offset));opacity:inherit;background:linear-gradient(to right, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 0, linear-gradient(to right, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 100%, linear-gradient(to left, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 0, linear-gradient(to left, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 100%, linear-gradient(to bottom, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 0, linear-gradient(to bottom, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 0, linear-gradient(to top, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 100%, linear-gradient(to top, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 100%;background-size:var(--twintag-scanner-corners-length) var(--twintag-scanner-corners-length);background-repeat:no-repeat;z-index:2222}:host .video-container video{position:absolute;width:100% !important;object-fit:cover;object-position:center;aspect-ratio:1/1 !important;min-height:var(--twintag-scanner-min-height)}';export{j as twintag_ocr_scanner}
1
+ import{r as t,c as r,h as e,H as n}from"./p-cb286d41.js";import{g as a}from"./p-60325667.js";import{c as o,a as i,b as c}from"./p-814af281.js";o((function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,a="function"==typeof Symbol?Symbol:{},o=a.iterator||"@@iterator",i=a.asyncIterator||"@@asyncIterator",c=a.toStringTag||"@@toStringTag";function s(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{s({},"")}catch(t){s=function(t,r,e){return t[r]=e}}function l(t,r,e,n){var a=Object.create((r&&r.prototype instanceof g?r:g).prototype),o=new x(n||[]);return a._invoke=function(t,r,e){var n=d;return function(a,o){if(n===f)throw new Error("Generator is already running");if(n===p){if("throw"===a)throw o;return N()}for(e.method=a,e.arg=o;;){var i=e.delegate;if(i){var c=A(i,e);if(c){if(c===w)continue;return c}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===d)throw n=p,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=f;var s=h(t,r,e);if("normal"===s.type){if(n=e.done?p:u,s.arg===w)continue;return{value:s.arg,done:e.done}}"throw"===s.type&&(n=p,e.method="throw",e.arg=s.arg)}}}(t,e,o),a}function h(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=l;var d="suspendedStart",u="suspendedYield",f="executing",p="completed",w={};function g(){}function v(){}function y(){}var m={};m[o]=function(){return this};var b=Object.getPrototypeOf,L=b&&b(b(T([])));L&&L!==e&&n.call(L,o)&&(m=L);var k=y.prototype=g.prototype=Object.create(m);function S(t){["next","throw","return"].forEach((function(r){s(t,r,(function(t){return this._invoke(r,t)}))}))}function E(t,r){function e(a,o,i,c){var s=h(t[a],t,o);if("throw"!==s.type){var l=s.arg,d=l.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(t){e("next",t,i,c)}),(function(t){e("throw",t,i,c)})):r.resolve(d).then((function(t){l.value=t,i(l)}),(function(t){return e("throw",t,i,c)}))}c(s.arg)}var a;this._invoke=function(t,n){function o(){return new r((function(r,a){e(t,n,r,a)}))}return a=a?a.then(o,o):o()}}function A(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,A(t,e),"throw"===e.method))return w;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return w}var a=h(n,t.iterator,e.arg);if("throw"===a.type)return e.method="throw",e.arg=a.arg,e.delegate=null,w;var o=a.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,w):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,w)}function O(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function R(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function x(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var a=-1,i=function e(){for(;++a<t.length;)if(n.call(t,a))return e.value=t[a],e.done=!1,e;return e.value=r,e.done=!0,e};return i.next=i}}return{next:N}}function N(){return{value:r,done:!0}}return v.prototype=k.constructor=y,y.constructor=v,v.displayName=s(y,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===v||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,s(t,c,"GeneratorFunction")),t.prototype=Object.create(k),t},t.awrap=function(t){return{__await:t}},S(E.prototype),E.prototype[i]=function(){return this},t.AsyncIterator=E,t.async=function(r,e,n,a,o){void 0===o&&(o=Promise);var i=new E(l(r,e,n,a),o);return t.isGeneratorFunction(e)?i:i.next().then((function(t){return t.done?t.value:i.next()}))},S(k),s(k,c,"Generator"),k[o]=function(){return this},k.toString=function(){return"[object Generator]"},t.keys=function(t){var r=[];for(var e in t)r.push(e);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=T,x.prototype={constructor:x,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(R),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function a(n,a){return c.type="throw",c.arg=t,e.next=n,a&&(e.method="next",e.arg=r),!!a}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],c=i.completion;if("root"===i.tryLoc)return a("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev<i.catchLoc)return a(i.catchLoc,!0);if(this.prev<i.finallyLoc)return a(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return a(i.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return a(i.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var a=this.tryEntries[e];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev<a.finallyLoc){var o=a;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=r&&r<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=t,i.arg=r,o?(this.method="next",this.next=o.finallyLoc,w):this.complete(i)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),w},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),R(e),w}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var a=n.arg;R(e)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:T(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),w}},t}(t.exports);try{regeneratorRuntime=r}catch(t){Function("r","regeneratorRuntime = r")(r)}}));var s=(t,r)=>`${t}-${r}-${Math.random().toString(16).slice(3,8)}`;let l=0;var h=({id:t,action:r,payload:e={}})=>{let n=t;return void 0===n&&(n=s("Job",l),l+=1),{id:n,action:r,payload:e}};let d=!1;var u={logging:d,setLogging:t=>{d=t},log:(...t)=>d?console.log.apply(void 0,t):null};const{log:f}=u;let p=0;var w=i.process;const g="browser"===(t=>{const r={};return"undefined"!=typeof WorkerGlobalScope?r.type="webworker":"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||void 0!==w&&"object"==typeof w.versions&&w.versions.electron||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0?r.type="electron":"object"==typeof document?r.type="browser":"object"==typeof w&&"function"==typeof c&&(r.type="node"),r[t]})("type")?t=>new URL(t,window.location.href).href:t=>t;var v={TESSERACT_ONLY:0,LSTM_ONLY:1,TESSERACT_LSTM_COMBINED:2,DEFAULT:3};const y=t=>new Promise(((r,e)=>{const n=new FileReader;n.onload=()=>{r(n.result)},n.onerror=({target:{error:{code:t}}})=>{e(Error(`File could not be read! Code=${t}`))},n.readAsArrayBuffer(t)})),m=async t=>{let r=t;if(void 0===t)return"undefined";if("string"==typeof t)if(/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(t))r=atob(t.split(",")[1]).split("").map((t=>t.charCodeAt(0)));else{const e=await fetch(t);r=await e.arrayBuffer()}else if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)"IMG"===t.tagName&&(r=await m(t.src)),"VIDEO"===t.tagName&&(r=await m(t.poster)),"CANVAS"===t.tagName&&await new Promise((e=>{t.toBlob((async t=>{r=await y(t),e()}))}));else if("undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas){const e=await t.convertToBlob();r=await y(e)}else(t instanceof File||t instanceof Blob)&&(r=await y(t));return new Uint8Array(r)};var b={defaultOptions:{workerBlobURL:!0,logger:()=>{},workerPath:"https://cdn.jsdelivr.net/npm/tesseract.js@v5.1.0/dist/worker.min.js"},spawnWorker:({workerPath:t,workerBlobURL:r})=>{let e;if(Blob&&URL&&r){const r=new Blob([`importScripts("${t}");`],{type:"application/javascript"});e=new Worker(URL.createObjectURL(r))}else e=new Worker(t);return e},terminateWorker:t=>{t.terminate()},onMessage:(t,r)=>{t.onmessage=({data:t})=>{r(t)}},send:async(t,r)=>{t.postMessage(r)},loadImage:m};const{log:L}=u,{defaultOptions:k,spawnWorker:S,terminateWorker:E,onMessage:A,loadImage:O,send:R}=b;let x=0;var T=async(t="eng",r=v.LSTM_ONLY,e={},n={})=>{const a=s("Worker",x),{logger:o,errorHandler:i,...c}=(t=>{const r={...t};return["corePath","workerPath","langPath"].forEach((e=>{t[e]&&(r[e]=g(r[e]))})),r})({...k,...e}),l={},d={},u="string"==typeof t?t.split("+"):t;let f=r,p=n;const w=[v.DEFAULT,v.LSTM_ONLY].includes(r)&&!c.legacyCore;let y,m;const b=new Promise(((t,r)=>{m=t,y=r}));let T=S(c);T.onerror=t=>{y(t.message)},x+=1;const N=(t,r)=>{l[t]=r},I=(t,r)=>{d[t]=r},_=({id:t,action:r,payload:e})=>new Promise(((n,o)=>{L(`[${a}]: Start ${t}, action=${r}`);const i=`${r}-${t}`;N(i,n),I(i,o),R(T,{workerId:a,jobId:t,action:r,payload:e})})),j=(t,r)=>_(h({id:r,action:"loadLanguage",payload:{langs:t,options:{langPath:c.langPath,dataPath:c.dataPath,cachePath:c.cachePath,cacheMethod:c.cacheMethod,gzip:c.gzip,lstmOnly:[v.LSTM_ONLY,v.TESSERACT_LSTM_COMBINED].includes(f)&&!c.legacyLang}}})),P=(t,r,e,n)=>_(h({id:n,action:"initialize",payload:{langs:t,oem:r,config:e}}));A(T,(({workerId:t,jobId:r,status:e,action:n,data:a})=>{const c=`${n}-${r}`;if("resolve"===e){L(`[${t}]: Complete ${r}`);let e=a;"recognize"===n?e=(t=>{const r=[],e=[],n=[],a=[],o=[];return t.blocks&&t.blocks.forEach((i=>{i.paragraphs.forEach((r=>{r.lines.forEach((e=>{e.words.forEach((n=>{n.symbols.forEach((a=>{o.push({...a,page:t,block:i,paragraph:r,line:e,word:n})})),a.push({...n,page:t,block:i,paragraph:r,line:e})})),n.push({...e,page:t,block:i,paragraph:r})})),e.push({...r,page:t,block:i})})),r.push({...i,page:t})})),{...t,blocks:r,paragraphs:e,lines:n,words:a,symbols:o}})(a):"getPDF"===n&&(e=Array.from({...a,length:Object.keys(a).length})),l[c]({jobId:r,data:e})}else if("reject"===e){if(d[c](a),"load"===n&&y(a),!i)throw Error(a);i(a)}else"progress"===e&&o({...a,userJobId:r})}));const M={id:a,worker:T,setResolve:N,setReject:I,load:()=>console.warn("`load` is depreciated and should be removed from code (workers now come pre-loaded)"),writeText:(t,r,e)=>_(h({id:e,action:"FS",payload:{method:"writeFile",args:[t,r]}})),readText:(t,r)=>_(h({id:r,action:"FS",payload:{method:"readFile",args:[t,{encoding:"utf8"}]}})),removeFile:(t,r)=>_(h({id:r,action:"FS",payload:{method:"unlink",args:[t]}})),FS:(t,r,e)=>_(h({id:e,action:"FS",payload:{method:t,args:r}})),loadLanguage:()=>console.warn("`loadLanguage` is depreciated and should be removed from code (workers now come with language pre-loaded)"),initialize:()=>console.warn("`initialize` is depreciated and should be removed from code (workers now come pre-initialized)"),reinitialize:(t="eng",r,e,n)=>{if(w&&[v.TESSERACT_ONLY,v.TESSERACT_LSTM_COMBINED].includes(r))throw Error("Legacy model requested but code missing.");const a=r||f;f=a;const o=e||p;p=o;const i=("string"==typeof t?t.split("+"):t).filter((t=>!u.includes(t)));return u.push(...i),i.length>0?j(i,n).then((()=>P(t,a,o,n))):P(t,a,o,n)},setParameters:(t={},r)=>_(h({id:r,action:"setParameters",payload:{params:t}})),recognize:async(t,r={},e={blocks:!0,text:!0,hocr:!0,tsv:!0},n)=>_(h({id:n,action:"recognize",payload:{image:await O(t),options:r,output:e}})),getPDF:(t="Tesseract OCR Result",r=!1,e)=>(console.log("`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead."),_(h({id:e,action:"getPDF",payload:{title:t,textonly:r}}))),detect:async(t,r)=>{if(w)throw Error("`worker.detect` requires Legacy model, which was not loaded.");return _(h({id:r,action:"detect",payload:{image:await O(t)}}))},terminate:async()=>(null!==T&&(E(T),T=null),Promise.resolve())};return _(h({id:undefined,action:"load",payload:{options:{lstmOnly:w,corePath:c.corePath,logging:c.logging}}})).then((()=>j(t))).then((()=>P(t,r,n))).then((()=>m(M))).catch((()=>{})),b},N={recognize:async(t,r,e)=>{const n=await T(r,1,e);return n.recognize(t).finally((async()=>{await n.terminate()}))},detect:async(t,r)=>{const e=await T("osd",0,r);return e.detect(t).finally((async()=>{await e.terminate()}))}};const{setLogging:I}=u;var _={languages:{AFR:"afr",AMH:"amh",ARA:"ara",ASM:"asm",AZE:"aze",AZE_CYRL:"aze_cyrl",BEL:"bel",BEN:"ben",BOD:"bod",BOS:"bos",BUL:"bul",CAT:"cat",CEB:"ceb",CES:"ces",CHI_SIM:"chi_sim",CHI_TRA:"chi_tra",CHR:"chr",CYM:"cym",DAN:"dan",DEU:"deu",DZO:"dzo",ELL:"ell",ENG:"eng",ENM:"enm",EPO:"epo",EST:"est",EUS:"eus",FAS:"fas",FIN:"fin",FRA:"fra",FRK:"frk",FRM:"frm",GLE:"gle",GLG:"glg",GRC:"grc",GUJ:"guj",HAT:"hat",HEB:"heb",HIN:"hin",HRV:"hrv",HUN:"hun",IKU:"iku",IND:"ind",ISL:"isl",ITA:"ita",ITA_OLD:"ita_old",JAV:"jav",JPN:"jpn",KAN:"kan",KAT:"kat",KAT_OLD:"kat_old",KAZ:"kaz",KHM:"khm",KIR:"kir",KOR:"kor",KUR:"kur",LAO:"lao",LAT:"lat",LAV:"lav",LIT:"lit",MAL:"mal",MAR:"mar",MKD:"mkd",MLT:"mlt",MSA:"msa",MYA:"mya",NEP:"nep",NLD:"nld",NOR:"nor",ORI:"ori",PAN:"pan",POL:"pol",POR:"por",PUS:"pus",RON:"ron",RUS:"rus",SAN:"san",SIN:"sin",SLK:"slk",SLV:"slv",SPA:"spa",SPA_OLD:"spa_old",SQI:"sqi",SRP:"srp",SRP_LATN:"srp_latn",SWA:"swa",SWE:"swe",SYR:"syr",TAM:"tam",TEL:"tel",TGK:"tgk",TGL:"tgl",THA:"tha",TIR:"tir",TUR:"tur",UIG:"uig",UKR:"ukr",URD:"urd",UZB:"uzb",UZB_CYRL:"uzb_cyrl",VIE:"vie",YID:"yid"},OEM:v,PSM:{OSD_ONLY:"0",AUTO_OSD:"1",AUTO_ONLY:"2",AUTO:"3",SINGLE_COLUMN:"4",SINGLE_BLOCK_VERT_TEXT:"5",SINGLE_BLOCK:"6",SINGLE_LINE:"7",SINGLE_WORD:"8",CIRCLE_WORD:"9",SINGLE_CHAR:"10",SPARSE_TEXT:"11",SPARSE_TEXT_OSD:"12",RAW_LINE:"13"},createScheduler:()=>{const t=s("Scheduler",p),r={},e={};let n=[];p+=1;const a=()=>Object.keys(r).length,o=()=>{if(0!==n.length){const t=Object.keys(r);for(let a=0;a<t.length;a+=1)if(void 0===e[t[a]]){n[0](r[t[a]]);break}}};return{addWorker:e=>(r[e.id]=e,f(`[${t}]: Add ${e.id}`),f(`[${t}]: Number of workers=${a()}`),o(),e.id),addJob:async(r,...i)=>{if(0===a())throw Error(`[${t}]: You need to have at least one worker before adding jobs`);return((r,a)=>new Promise(((i,c)=>{const s=h({action:r,payload:a});n.push((async t=>{n.shift(),e[t.id]=s;try{i(await t[r].apply(void 0,[...a,s.id]))}catch(t){c(t)}finally{delete e[t.id],o()}})),f(`[${t}]: Add ${s.id} to JobQueue`),f(`[${t}]: JobQueue length=${n.length}`),o()})))(r,i)},terminate:async()=>{Object.keys(r).forEach((async t=>{await r[t].terminate()})),n=[]},getQueueLen:()=>n.length,getNumWorkers:a}},createWorker:T,setLogging:I,...N};const j=class{constructor(e){t(this,e),this.symbol=r(this,"symbol",7),this.streamIsActive=r(this,"streamIsActive",7),this.canRecognize=r(this,"canRecognize",7),this.frame=r(this,"frame",7),this.devices=[],this.stream=null,this.cropX=1,this.cropY=1,this.zoom=0}async ocrHandler(){const{text:t,frame:r}=await this.readBarcodeFromCanvas();this.symbol.emit({text:t,format:"OCR"}),this.frame.emit(r),this.stopStream()}async connectedCallback(){this.worker=await _.createWorker("eng")}async componentDidLoad(){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d",{willReadFrequently:!0}),this.videoContainer.style.setProperty("--crop-x",""+50*(1-this.cropX)),this.videoContainer.style.setProperty("--crop-y",""+50*(1-this.cropY)),await this.startStream()}async readBarcodeFromCanvas(){await this.updateVideoZoom(),this.drawInCanvas();const t=this.canvas.toDataURL("image/png"),{data:{text:r}}=await this.worker.recognize(t);return{text:r,frame:t}}drawInCanvas(){const t=Math.min(this.video.videoWidth,this.video.videoHeight),r=t*this.cropX,e=t*this.cropY;this.context.drawImage(this.video,this.video.videoWidth/2-r/2,this.video.videoHeight/2-e/2,r,e,0,0,r,e)}async updateStream(t){this.stream&&this.stream.getTracks().forEach((t=>t.stop()));try{this.stream=await navigator.mediaDevices.getUserMedia(t),this.video.srcObject=this.stream,this.video.setAttribute("playsinline","true"),await this.video.play()}catch(t){console.error(t)}}async getTrackSettings(t){try{return(await navigator.mediaDevices.getUserMedia(t)).getVideoTracks()[0].getSettings()}catch(t){console.error(t)}}async getMedia(t){t.video.width={min:1080,ideal:1600,max:1920};try{await this.updateStream(t);const r=await navigator.mediaDevices.enumerateDevices();if(this.devices=r.filter((t=>"videoinput"===t.kind.toLowerCase()&&t.label.toLowerCase().includes("back"))),0===this.devices.length)return;1===this.devices.length&&(t.video.deviceId={exact:this.devices[0].deviceId},await this.updateStream(t));let e=this.devices.length-1;const n=this.devices.map((t=>{const r=t.label.match(/\b([0-9]+)MP?\b/i);return null!=r?parseInt(r[1],10):NaN}));n.some((t=>isNaN(t)))||(e=n.lastIndexOf(Math.max(...n)));const a=this.devices[e];if(a)return t.video.deviceId={exact:a.deviceId},void await this.updateStream(t);const o=await this.getTrackSettings(t);o.focusDistance&&(t.video.advanced=[{focusMode:"continuous",focusDistance:o.focusDistance}],await this.updateStream(t))}catch(t){console.error(t)}}async updateVideoZoom(){const[t]=this.stream.getVideoTracks();if(t.getCapabilities&&"function"==typeof t.applyConstraints){const r=t.getCapabilities();if("zoom"in t.getSettings()){const e=r.zoom.min,n=r.zoom.max;await t.applyConstraints({advanced:[{zoom:e+(n-e)*this.zoom}]})}}}async startStream(){const t={audio:!1,video:{aspectRatio:{ideal:1},facingMode:"environment"}};navigator.mediaDevices.getSupportedConstraints().zoom&&(t.video.zoom=!0),await this.getMedia(t),await this.updateVideoZoom(),a.to(this.videoContainer,{duration:.2,opacity:1,onComplete:()=>{this.streamIsActive.emit(!0);const t=Math.min(this.video.videoWidth,this.video.videoHeight),r=t*this.cropY;this.canvas.width=t*this.cropX,this.canvas.height=r,this.canRecognize.emit(!0)}})}stopStream(){a.to(this.videoContainer,{duration:.2,opacity:0,onComplete:async()=>{this.stream.getTracks().forEach((t=>t.stop())),this.video.srcObject=null,this.context.clearRect(0,0,this.context.canvas.width,this.context.canvas.height),await this.worker.terminate(),this.canRecognize.emit(!1)}})}disconnectedCallback(){this.stopStream()}render(){return e(n,null,e("div",{class:"video-container",ref:t=>this.videoContainer=t},e("div",{class:"video-corners"}),e("video",{crossOrigin:"Anonymous",autoplay:!0,playsinline:!0,ref:t=>this.video=t})))}};j.style=':host{--twintag-scanner-bg-select-cameras:white;--twintag-scanner-text-select-cameras:black;--twintag-scanner-radius-select-cameras:6px 0 0 0;--twintag-scanner-min-height:min-content;--twintag-scanner-corners-color:white;--twintag-scanner-corners-width:4px;--twintag-scanner-corners-length:36px;--twintag-scanner-corners-offset:24px;display:grid;place-items:center;position:relative;width:100%}:host .icon-container{display:grid;place-items:center;position:absolute;inset:0;z-index:-2222}:host .icon-container .check-icon{opacity:0;z-index:2222}:host .video-container{--crop:0;--crop-x:var(--crop);--crop-y:var(--crop);display:flex;align-items:center;justify-content:center;position:relative;width:100%;height:100%;opacity:0;overflow:hidden;z-index:1}:host .video-container::after{content:"";position:absolute;width:100%;height:100%;opacity:inherit;background:rgba(0, 0, 0, 0.5);-webkit-clip-path:polygon(0% 0%, 0% 100%, calc(var(--crop-x) * 1%) 100%, calc(var(--crop-x) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) 100%, 100% 100%, 100% 0%);clip-path:polygon(0% 0%, 0% 100%, calc(var(--crop-x) * 1%) 100%, calc(var(--crop-x) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(var(--crop-y) * 1%), calc(calc(100 - var(--crop-x)) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) calc(calc(100 - var(--crop-y)) * 1%), calc(var(--crop-x) * 1%) 100%, 100% 100%, 100% 0%)}:host .video-container:before{display:block;content:"";width:100%;padding-top:100%}:host .video-container .video-corners{position:absolute;width:calc((1 - var(--crop-x) / 50) * 100% + var(--twintag-scanner-corners-offset));height:calc((1 - var(--crop-y) / 50) * 100% + var(--twintag-scanner-corners-offset));opacity:inherit;background:linear-gradient(to right, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 0, linear-gradient(to right, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 100%, linear-gradient(to left, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 0, linear-gradient(to left, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 100%, linear-gradient(to bottom, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 0, linear-gradient(to bottom, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 0, linear-gradient(to top, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 0 100%, linear-gradient(to top, var(--twintag-scanner-corners-color) var(--twintag-scanner-corners-width), transparent var(--twintag-scanner-corners-width)) 100% 100%;background-size:var(--twintag-scanner-corners-length) var(--twintag-scanner-corners-length);background-repeat:no-repeat;z-index:2222}:host .video-container video{position:absolute;width:100% !important;object-fit:cover;object-position:center;aspect-ratio:1/1 !important;min-height:var(--twintag-scanner-min-height)}';export{j as twintag_ocr_scanner}