alphavalid-sdk 0.0.25 → 0.1.0
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.
- package/README.md +73 -107
- package/bin/alphavalid.js +39 -0
- package/dist/__vite-browser-external-C7ivxuo1.mjs +18 -0
- package/dist/alphavalid.es.js +6539 -4893
- package/dist/alphavalid.umd.js +271 -223
- package/dist/core/camera.d.ts.map +1 -1
- package/dist/core/feedback.d.ts +102 -1
- package/dist/core/feedback.d.ts.map +1 -1
- package/dist/index.d.ts +100 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/setupModels-RA6BN3uf.mjs +19 -0
- package/dist/setupModels.d.ts +2 -0
- package/dist/setupModels.d.ts.map +1 -0
- package/dist/types/sdk.d.ts +346 -88
- package/dist/types/sdk.d.ts.map +1 -1
- package/dist/ui/baseStyles.d.ts +2 -0
- package/dist/ui/baseStyles.d.ts.map +1 -0
- package/dist/ui/captureButtonCoxinha.d.ts +13 -0
- package/dist/ui/captureButtonCoxinha.d.ts.map +1 -0
- package/dist/ui/containerStyles.d.ts +1 -0
- package/dist/ui/containerStyles.d.ts.map +1 -0
- package/dist/ui/loader.d.ts +15 -0
- package/dist/ui/loader.d.ts.map +1 -0
- package/dist/ui/overlay.d.ts +186 -1
- package/dist/ui/overlay.d.ts.map +1 -1
- package/dist/ui/overlayCoxinhaMobile.d.ts +10 -0
- package/dist/ui/overlayCoxinhaMobile.d.ts.map +1 -0
- package/dist/ui/userPreviewCoxinha.d.ts +20 -0
- package/dist/ui/userPreviewCoxinha.d.ts.map +1 -0
- package/dist/utils/canvas.d.ts +27 -0
- package/dist/utils/canvas.d.ts.map +1 -0
- package/dist/vision/faceDetector.d.ts.map +1 -1
- package/package.json +9 -2
- package/scripts/copy-models.cjs +17 -62
package/dist/alphavalid.umd.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AlphaValid={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);function n(e,t){if(!(e instanceof HTMLElement))throw Error(`${t} must be an HTMLElement`)}function r(e){let t=e,n=t?.name;return n===`NotAllowedError`||n===`SecurityError`?{code:`CAMERA_PERMISSION_DENIED`,message:`Permissão de câmera negada pelo usuário.`,cause:e}:n===`NotFoundError`||n===`DevicesNotFoundError`?{code:`CAMERA_NOT_FOUND`,message:`Nenhuma câmera disponível no dispositivo.`,cause:e}:n===`NotReadableError`||n===`TrackStartError`?{code:`CAMERA_NOT_READABLE`,message:`Não foi possível acessar a câmera (pode estar em uso por outro app).`,cause:e}:n===`OverconstrainedError`||n===`ConstraintNotSatisfiedError`?{code:`CAMERA_OVERCONSTRAINED`,message:`Restrições de câmera não suportadas para este dispositivo.`,cause:e}:n===`NotSupportedError`?{code:`CAMERA_NOT_SUPPORTED`,message:`Navegador/dispositivo não suporta captura de câmera.`,cause:e}:{code:`CAMERA_UNKNOWN`,message:t?.message||`Erro desconhecido ao abrir a câmera.`,cause:e}}async function i(e){let t;try{if(!navigator.mediaDevices?.getUserMedia)throw{name:`NotSupportedError`};t=await navigator.mediaDevices.getUserMedia({video:{facingMode:`user`}})}catch(e){throw r(e)}let n=document.createElement(`video`);return n.autoplay=!0,n.playsInline=!0,n.muted=!0,n.srcObject=t,n.style.width=`100%`,n.style.height=`100%`,n.style.objectFit=`cover`,e.appendChild(n),await new Promise((e,t)=>{let r=()=>{n.removeEventListener(`loadedmetadata`,r),e()},i=()=>{n.removeEventListener(`error`,i),t(Error(`Failed to load camera stream into video element`))};n.addEventListener(`loadedmetadata`,r),n.addEventListener(`error`,i)}),{video:n,stream:t,stop:()=>{t.getTracks().forEach(e=>e.stop());try{n.srcObject=null}catch{}n.parentElement&&n.parentElement.removeChild(n)}}}async function a(e,t=.9){let n=document.createElement(`canvas`);return n.width=e.videoWidth,n.height=e.videoHeight,n.getContext(`2d`)?.drawImage(e,0,0),await new Promise((e,r)=>{n.toBlob(t=>{if(!t)return r(Error(`Failed to capture image blob`));e(t)},`image/jpeg`,t)})}function o(e,t=.72){let n=document.createElement(`canvas`),r=n.getContext(`2d`);n.style.position=`absolute`,n.style.left=`0`,n.style.top=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.pointerEvents=`none`,getComputedStyle(e).position===`static`&&(e.style.position=`relative`),e.appendChild(n);let i=()=>{let t=e.getBoundingClientRect(),i=Math.max(1,Math.round(window.devicePixelRatio||1));n.width=Math.max(1,Math.round(t.width*i)),n.height=Math.max(1,Math.round(t.height*i)),n.style.width=`${Math.max(1,Math.round(t.width))}px`,n.style.height=`${Math.max(1,Math.round(t.height))}px`,r&&r.setTransform(i,0,0,i,0,0)};return{canvas:n,dispose:()=>{n.parentElement&&n.parentElement.removeChild(n)},render:e=>{if(!r)return;i();let a=n.width,o=n.height;r.clearRect(0,0,a,o),r.fillStyle=`rgba(0,0,0,0.52)`,r.fillRect(0,0,a,o);let s=Math.min(a,o)*t*.5,c=a/2,l=o/2;if(r.globalCompositeOperation=`destination-out`,r.beginPath(),r.arc(c,l,s,0,Math.PI*2),r.fill(),r.globalCompositeOperation=`source-over`,r.lineWidth=Math.max(3,Math.round(Math.min(a,o)*.01)),r.strokeStyle=e.valid?`rgba(46, 204, 113, 0.98)`:`rgba(255,255,255,0.92)`,r.beginPath(),r.arc(c,l,s,0,Math.PI*2),r.stroke(),e.box&&(r.lineWidth=2,r.strokeStyle=`rgba(52, 152, 219, 0.85)`,r.strokeRect(e.box.x*a,e.box.y*o,e.box.width*a,e.box.height*o)),e.landmarks){let t=[...e.landmarks.leftEye??[],...e.landmarks.rightEye??[]];if(t.length>0){let e=Math.max(2,Math.round(Math.min(a,o)*.006));r.save(),r.fillStyle=`rgba(0, 255, 255, 0.9)`;for(let n of t){let t=n.x*a,i=n.y*o;r.beginPath(),r.arc(t,i,e,0,Math.PI*2),r.fill()}r.restore()}let n=[e.landmarks.leftEyeCenter,e.landmarks.rightEyeCenter].filter(Boolean);if(n.length>0){let e=Math.max(4,Math.round(Math.min(a,o)*.012));r.save(),r.fillStyle=`rgba(255, 64, 129, 0.95)`;for(let t of n)r.beginPath(),r.arc(t.x*a,t.y*o,e,0,Math.PI*2),r.fill();r.restore()}}if(e.message){let t=Math.max(52,Math.round(o*.12)),n=o-t-16;r.fillStyle=`rgba(0,0,0,0.62)`,r.beginPath();let i=a-32,s=t;r.moveTo(30,n),r.arcTo(16+i,n,16+i,n+s,14),r.arcTo(16+i,n+s,16,n+s,14),r.arcTo(16,n+s,16,n,14),r.arcTo(16,n,16+i,n,14),r.closePath(),r.fill(),r.fillStyle=`white`,r.font=`600 ${Math.max(14,Math.round(Math.min(a,o)*.045))}px system-ui, -apple-system, Segoe UI, Roboto, Arial`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(e.message,a/2,n+s/2)}}}}var s=t(((e,t)=>{t.exports={}})),c=function(e,t){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function l(e,t){function n(){this.constructor=e}c(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function u(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(o,s)}c((r=r.apply(e,t||[])).next())}))}function d(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw TypeError(`Generator is already executing.`);for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){o=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(a[0]===6&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}var f=function(){function e(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return e.prototype.setPlatform=function(e,t){this.platform!=null&&console.warn(`Platform `+this.platformName+` has already been set. Overwriting the platform with `+t+`.`),this.platformName=e,this.platform=t},e.prototype.registerFlag=function(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){var r=this.urlFlags[e];console.warn(`Setting feature override from URL `+e+`: `+r+`.`),this.set(e,r)}},e.prototype.get=function(e){return e in this.flags||(this.flags[e]=this.evaluateFlag(e)),this.flags[e]},e.prototype.getNumber=function(e){return this.get(e)},e.prototype.getBool=function(e){return this.get(e)},e.prototype.getFlags=function(){return this.flags},Object.defineProperty(e.prototype,`features`,{get:function(){return this.flags},enumerable:!0,configurable:!0}),e.prototype.set=function(e,t){if(this.flagRegistry[e]==null)throw Error(`Cannot set flag `+e+` as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)},e.prototype.evaluateFlag=function(e){if(this.flagRegistry[e]==null)throw Error(`Cannot evaluate flag '`+e+`': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()},e.prototype.setFlags=function(e){this.flags=Object.assign({},e)},e.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},e.prototype.populateURLFlags=function(){var e=this;if(this.global!==void 0&&this.global.location!==void 0&&this.global.location.search!==void 0){var t,n,r=(t=this.global.location.search,n={},t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return p(n,t[0],t[1]),t.join(`=`)})),n);`tfjsflags`in r&&r.tfjsflags.split(`,`).forEach((function(t){var n=t.split(`:`),r=n[0],i=n[1];e.urlFlags[r]=function(e,t){if((t=t.toLowerCase())===`true`||t===`false`)return t===`true`;if(``+ +t===t)return+t;throw Error(`Could not parse value flag value `+t+` for flag `+e+`.`)}(r,i)}))}},e}();function p(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||``)}function m(){return h}var h=null,g=new Map,_=new Map;function v(e,t){var n=C(e,t);return g.get(n)}function y(e){return _.get(e)}function b(e){for(var t=g.entries(),n=[];;){var r=t.next(),i=r.done,a=r.value;if(i)break;var o=a[0],s=a[1];o.split(`_`)[0]===e&&n.push(s)}return n}function x(e){var t=e.kernelName,n=e.backendName,r=C(t,n);if(g.has(r))throw Error(`The kernel '`+t+`' for backend '`+n+`' is already registered`);g.set(r,e)}function S(e){var t=e.kernelName;_.has(t)&&console.warn(`Overriding the gradient for '`+t+`'`),_.set(t,e)}function C(e,t){return t+`_`+e}function w(e){for(var t=e.length,n=0,r=0;t>0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function T(e,t,n){return Math.max(e,Math.min(t,n))}function E(e){return e%2==0?e:e+1}function D(e){for(var t=0,n=0;n<e.length;n++)t+=e[n];return t}function O(e,t){if(!e)throw Error(typeof t==`string`?t:t())}function k(e,t,n){n===void 0&&(n=``),O(N(e,t),(function(){return n+` Shapes `+e+` and `+t+` must match`}))}function A(e){O(e!=null,(function(){return`The input to the tensor constructor must be a non-null value.`}))}function j(e,t,n){if(t===void 0&&(t=[]),n===void 0&&(n=!1),t??=[],Array.isArray(e)||le(e)&&!n)for(var r=0;r<e.length;++r)j(e[r],t,n);else t.push(e);return t}function M(e){if(e.length===0)return 1;for(var t=e[0],n=1;n<e.length;n++)t*=e[n];return t}function N(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function P(e){return e%1==0}function F(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;var t=Math.exp(2*e);return(t-1)/(t+1)}function I(e){var t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ee(e,t){return t<=e.length?e:e+` `.repeat(t-e.length)}function te(e,t,n){return t===void 0&&(t=function(e){return 0}),new Promise((function(r,i){var a=0,o=function(){if(e())r();else{a++;var s=t(a);n!=null&&a>=n?i():setTimeout(o,s)}};o()}))}function ne(e,t){for(var n=1,r=-1,i=0;i<e.length;++i)if(e[i]>=0)n*=e[i];else if(e[i]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim `+r+` and dim `+i);r=i}else if(e[i]<0)throw Error(`Shapes can not be < 0. Found `+e[i]+` at dim `+i);if(r===-1){if(t>0&&t!==n)throw Error(`Size(`+t+`) must match the product of shape `+e);return e}if(n===0)throw Error(`Cannot infer the missing size in [`+e+`] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got `+t+` / `+n);var a=e.slice();return a[r]=t/n,a}function L(e,t){var n=t.length;return O((e=e==null?t.map((function(e,t){return t})):[].concat(e)).every((function(e){return e>=-n&&e<n})),(function(){return`All values in axis param must be in range [-`+n+`, `+n+`) but got axis `+e})),O(e.every((function(e){return P(e)})),(function(){return`All values in axis param must be integers but got axis `+e})),e.map((function(e){return e<0?n+e:e}))}function re(e,t){for(var n=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||i?null:L(t,e).sort(),o=0,s=0;s<e.length;++s){if(a!=null){if(a[o]===s&&e[s]!==1)throw Error(`Can't squeeze axis `+s+` since its dim '`+e[s]+`' is not 1`);(a[o]==null||a[o]>s)&&e[s]===1&&(n.push(e[s]),r.push(s)),a[o]<=s&&o++}e[s]!==1&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function ie(e,t){var n=null;if(e==null||e===`float32`)n=new Float32Array(t);else if(e===`int32`)n=new Int32Array(t);else{if(e!==`bool`)throw Error(`Unknown data type `+e);n=new Uint8Array(t)}return n}function ae(e,t){var n=null;if(e==null||e===`float32`)n=new Float32Array(t);else if(e===`int32`)n=new Int32Array(t);else if(e===`bool`)n=new Uint8Array(t);else{if(e!==`string`)throw Error(`Unknown data type `+e);n=Array(t)}return n}function oe(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type `+t+` being uploaded contains `+r+`.`)}}function se(e){return e===`bool`||e===`complex64`||e===`float32`||e===`int32`||e===`string`}function ce(e,t){return t!==`complex64`&&(t!==`float32`||e===`complex64`)&&(t!==`int32`||e===`float32`||e===`complex64`)&&(t!==`bool`||e!==`bool`)}function le(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function ue(e){if(e===`float32`||e===`int32`)return 4;if(e===`complex64`)return 8;if(e===`bool`)return 1;throw Error(`Unknown dtype `+e)}function de(e){if(e==null)return 0;var t=0;return e.forEach((function(e){return t+=e.length})),t}function fe(e){return typeof e==`string`||e instanceof String}function pe(e){return typeof e==`boolean`}function me(e){return typeof e==`number`}function he(e){return Array.isArray(e)?he(e[0]):e instanceof Float32Array?`float32`:e instanceof Int32Array||e instanceof Uint8Array?`int32`:me(e)?`float32`:fe(e)?`string`:pe(e)?`bool`:`float32`}function ge(e){return!!(e&&e.constructor&&e.call&&e.apply)}function _e(e,t){for(var n=t;n<e;++n)if(e%n==0)return n;return e}function ve(e){var t=e.length;if(t<2)return[];var n=Array(t-1);n[t-2]=e[t-1];for(var r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function ye(e,t,n){if(t===`string`)throw Error(`Cannot convert a string[] to a TypedArray`);if(Array.isArray(e)&&(e=j(e)),n&&oe(e,t),function(e,t){return e instanceof Float32Array&&t===`float32`||e instanceof Int32Array&&t===`int32`||e instanceof Uint8Array&&t===`bool`}(e,t))return e;if(t==null||t===`float32`||t===`complex64`)return new Float32Array(e);if(t===`int32`)return new Int32Array(e);if(t===`bool`){for(var r=new Uint8Array(e.length),i=0;i<r.length;++i)Math.round(e[i])!==0&&(r[i]=1);return r}throw Error(`Unknown data type `+t)}function be(e,t){if(e.length===0)return t[0];var n=e.reduce((function(e,t){return e*t}));if(n===0)return[];if(n!==t.length)throw Error(`[`+e+`] does not match the input size.`);return function e(t,n,r){var i=[];if(n.length===1)for(var a=n[0],o=0;o<a;o++)i[o]=r[t+o];else{a=n[0];var s=n.slice(1),c=s.reduce((function(e,t){return e*t}));for(o=0;o<a;o++)i[o]=e(t+o*c,s,r)}return i}(0,e,t)}function xe(e,t){for(var n=Se(e,t),r=0;r<n.length;r++)n[r]=1;return n}function Se(e,t){if(t==null||t===`float32`||t===`complex64`)return new Float32Array(e);if(t===`int32`)return new Int32Array(e);if(t===`bool`)return new Uint8Array(e);throw Error(`Unknown data type `+t)}function Ce(){return m().platform.now()}function we(e){e.forEach((function(t){O(Number.isInteger(t)&&t>=0,(function(){return`Tensor must have a shape comprised of positive integers but got shape [`+e+`].`}))}))}function Te(e,t){return t===void 0&&(t=`utf-8`),t||=`utf-8`,m().platform.encode(e,t)}function Ee(e,t){return t===void 0&&(t=`utf-8`),t||=`utf-8`,m().platform.decode(e,t)}function De(e,t,n){if(t===0)return 0;if(t===1)return e[0];for(var r=e[e.length-1],i=0;i<e.length-1;++i)r+=n[i]*e[i];return r}function Oe(e,t,n){if(t===0)return[];if(t===1)return[e];for(var r=Array(t),i=0;i<r.length-1;++i)r[i]=Math.floor(e/n[i]),e-=r[i]*n[i];return r[r.length-1]=e,r}Object.freeze({shuffle:w,clamp:T,nearestLargerEven:E,sum:D,randUniform:function(e,t){var n=Math.random();return t*n+(1-n)*e},distSquared:function(e,t){for(var n=0,r=0;r<e.length;r++){var i=Number(e[r])-Number(t[r]);n+=i*i}return n},assert:O,assertShapesMatch:k,assertNonNull:A,flatten:j,sizeFromShape:M,isScalarShape:function(e){return e.length===0},arraysEqual:N,isInt:P,tanh:F,sizeToSquarishShape:I,createShuffledIndices:function(e){for(var t=new Uint32Array(e),n=0;n<e;++n)t[n]=n;return w(t),t},rightPad:ee,repeatedTry:te,inferFromImplicitShape:ne,parseAxisParam:L,squeezeShape:re,getTypedArrayFromDType:ie,getArrayFromDType:ae,checkConversionForErrors:oe,isValidDtype:se,hasEncodingLoss:ce,isTypedArray:le,bytesPerElement:ue,bytesFromStringArray:de,isString:fe,isBoolean:pe,isNumber:me,inferDtype:he,isFunction:ge,nearestDivisor:_e,computeStrides:ve,toTypedArray:ye,toNestedArray:be,makeOnesTypedArray:xe,makeZerosTypedArray:Se,now:Ce,assertNonNegativeIntegerDimensions:we,fetch:function(e,t){return m().platform.fetch(e,t)},encodeString:Te,decodeString:Ee,locToIndex:De,indexToLoc:Oe});var ke=function(){function e(e,t){this.backendTimer=e,this.logger=t,t??(this.logger=new Ae)}return e.prototype.profileKernel=function(e,t,n){var r,i=this,a=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){(function(e,t,n){if(t!==`float32`)return!1;for(var r=0;r<e.length;r++){var i=e[r];if(isNaN(i)||!isFinite(i))return console.warn(`Found `+i+` in the result of '`+n+`'`),!0}})(r,n.dtype,e),a.then((function(a){var o=``;a.getExtraProfileInfo!=null&&(o=a.getExtraProfileInfo()),i.logger.logKernelProfile(e,n,r,a.kernelMs,t,o)}))}))})),r},e}(),Ae=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,n,r,i,a){var o=typeof r==`number`?ee(r+`ms`,9):r.error,s=ee(e,25),c=t.rank,l=t.size,u=ee(t.shape.toString(),14),d=``;for(var f in i){var p=i[f].shape||t.shape,m=p.length;d+=f+`: `+m+`D `+(m>0?p:``)+` `}console.log(`%c`+s+` %c`+o+` %c`+c+`D `+u+` %c`+l+` %c`+d+` %c`+a,`font-weight:bold`,`color:red`,`color:blue`,`color: orange`,`color: green`,`color: steelblue`)},e}(),je=20,Me=3,Ne=7;function Pe(e,t,n,r){var i=ve(t),a=function(e,t,n,r){var i=M(t),a=r[r.length-1],o=Array(a).fill(0),s=t.length,c=n===`complex64`?Le(e):e;if(s>1)for(var l=0;l<i/a;l++)for(var u=l*a,d=0;d<a;d++)o[d]=Math.max(o[d],Fe(c[u+d],0,n).length);return o}(e,t,n,i),o=t.length,s=function e(t,n,r,i,a,o){o===void 0&&(o=!0);var s=r===`complex64`?2:1,c=n[0],l=n.length;if(l===0)return r===`complex64`?[Fe(Le(t)[0],0,r)]:r===`bool`?[Ie(t[0])]:[t[0].toString()];if(l===1){if(c>je){var u=Me*s,d=Array.from(t.slice(0,u)),f=Array.from(t.slice((c-Me)*s,c*s));return r===`complex64`&&(d=Le(d),f=Le(f)),[`[`+d.map((function(e,t){return Fe(e,a[t],r)})).join(`, `)+`, ..., `+f.map((function(e,t){return Fe(e,a[c-Me+t],r)})).join(`, `)+`]`]}return[`[`+(r===`complex64`?Le(t):Array.from(t)).map((function(e,t){return Fe(e,a[t],r)})).join(`, `)+`]`]}var p=n.slice(1),m=i.slice(1),h=i[0]*s,g=[];if(c>je){for(var _=0;_<Me;_++){var v=(y=_*h)+h;g.push.apply(g,e(t.slice(y,v),p,r,m,a,!1))}for(g.push(`...`),_=c-Me;_<c;_++)v=(y=_*h)+h,g.push.apply(g,e(t.slice(y,v),p,r,m,a,_===c-1))}else for(_=0;_<c;_++){var y;v=(y=_*h)+h,g.push.apply(g,e(t.slice(y,v),p,r,m,a,_===c-1))}var b=l===2?`,`:``;for(g[0]=`[`+g[0]+b,_=1;_<g.length-1;_++)g[_]=` `+g[_]+b;var x=`,
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AlphaValid={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(e&&(t=e(e=0)),t),c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));function f(e,t){if(!(e instanceof HTMLElement))throw Error(`${t} must be an HTMLElement`)}function p(e){let t=e,n=t?.name;return n===`NotAllowedError`||n===`SecurityError`?{code:`CAMERA_PERMISSION_DENIED`,message:`Permissão de câmera negada pelo usuário.`,cause:e}:n===`NotFoundError`||n===`DevicesNotFoundError`?{code:`CAMERA_NOT_FOUND`,message:`Nenhuma câmera disponível no dispositivo.`,cause:e}:n===`NotReadableError`||n===`TrackStartError`?{code:`CAMERA_NOT_READABLE`,message:`Não foi possível acessar a câmera (pode estar em uso por outro app).`,cause:e}:n===`OverconstrainedError`||n===`ConstraintNotSatisfiedError`?{code:`CAMERA_OVERCONSTRAINED`,message:`Restrições de câmera não suportadas para este dispositivo.`,cause:e}:n===`NotSupportedError`?{code:`CAMERA_NOT_SUPPORTED`,message:`Navegador/dispositivo não suporta captura de câmera.`,cause:e}:{code:`CAMERA_UNKNOWN`,message:t?.message||`Erro desconhecido ao abrir a câmera.`,cause:e}}async function m(e){let t;try{if(!navigator.mediaDevices?.getUserMedia)throw{name:`NotSupportedError`};t=await navigator.mediaDevices.getUserMedia({video:{facingMode:`user`}})}catch(e){throw p(e)}let n=document.createElement(`video`);return n.autoplay=!0,n.playsInline=!0,n.muted=!0,n.srcObject=t,n.style.width=`100%`,n.style.height=`100%`,n.style.objectFit=`cover`,n.style.transform=`scaleX(-1)`,n.style.transformOrigin=`center`,e.appendChild(n),await new Promise((e,t)=>{let r=()=>{n.removeEventListener(`loadedmetadata`,r),e()},i=()=>{n.removeEventListener(`error`,i),t(Error(`Failed to load camera stream into video element`))};n.addEventListener(`loadedmetadata`,r),n.addEventListener(`error`,i)}),{video:n,stream:t,stop:()=>{t.getTracks().forEach(e=>e.stop());try{n.srcObject=null}catch{}n.parentElement&&n.parentElement.removeChild(n)}}}async function h(e,t=.9){let n=document.createElement(`canvas`);return n.width=e.videoWidth,n.height=e.videoHeight,n.getContext(`2d`)?.drawImage(e,0,0),await new Promise((e,r)=>{n.toBlob(t=>{if(!t)return r(Error(`Failed to capture image blob`));e(t)},`image/jpeg`,t)})}function g(e,t,n){return Math.max(t,Math.min(n,e))}function _(e){return g(e,0,1)}function v(e,t,n){let r=t.getBoundingClientRect(),i=window.devicePixelRatio||1,a=Math.max(1,Math.round(r.width)),o=Math.max(1,Math.round(r.height));e.style.width=`${a}px`,e.style.height=`${o}px`;let s=Math.max(1,Math.round(a*i)),c=Math.max(1,Math.round(o*i));return e.width!==s&&(e.width=s),e.height!==c&&(e.height=c),n&&n.setTransform(i,0,0,i,0,0),{w:a,h:o}}function y(e,t,n,r,i){if(!n||!(n.videoWidth>0)||!(n.videoHeight>0)){let n=!!i;return{mapPt:r=>({x:(n?1-r.x:r.x)*e,y:r.y*t}),mapRect:r=>({x:(n?1-(r.x+r.width):r.x)*e,y:r.y*t,width:r.width*e,height:r.height*t})}}let a=n.videoWidth,o=n.videoHeight,s=r??`cover`,c=typeof i==`boolean`?i:!1,l=e,u=t;if(s===`fill`)l=e,u=t;else if(s===`contain`||s===`scale-down`){let n=Math.min(e/a,t/o);l=a*n,u=o*n}else if(s===`none`)l=Math.min(e,a),u=Math.min(t,o);else{let n=Math.max(e/a,t/o);l=a*n,u=o*n}let d=(e-l)/2,f=(t-u)/2,p=e=>({x:d+(c?1-e.x:e.x)*l,y:f+e.y*u});return{mapPt:p,mapRect:e=>{let t=p({x:e.x,y:e.y}),n=p({x:e.x+e.width,y:e.y+e.height}),r=Math.min(t.x,n.x),i=Math.min(t.y,n.y),a=Math.max(t.x,n.x),o=Math.max(t.y,n.y);return{x:r,y:i,width:a-r,height:o-i}}}}function b(e,t=.72){let n=document.createElement(`canvas`),r=n.getContext(`2d`);n.style.position=`absolute`,n.style.left=`0`,n.style.top=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.pointerEvents=`none`,n.style.zIndex=`10`,getComputedStyle(e).position===`static`&&(e.style.position=`relative`),e.appendChild(n);let i=(e,t,n,r,i)=>{if(!n||!(n.videoWidth>0)||!(n.videoHeight>0)){let n=!!i;return{mapPt:r=>({x:(n?1-r.x:r.x)*e,y:r.y*t}),mapRect:r=>({x:(n?1-(r.x+r.width):r.x)*e,y:r.y*t,width:r.width*e,height:r.height*t})}}let a=n.videoWidth,o=n.videoHeight,s=r??(()=>{try{return getComputedStyle(n).objectFit||`cover`}catch{return`cover`}})(),c=typeof i==`boolean`?i:(()=>{try{let e=getComputedStyle(n).transform;return typeof e==`string`&&e.includes(`-1`)}catch{return!1}})(),l=e,u=t;if(s===`fill`)l=e,u=t;else if(s===`contain`||s===`scale-down`){let n=Math.min(e/a,t/o);l=a*n,u=o*n}else if(s===`none`)l=Math.min(e,a),u=Math.min(t,o);else{let n=Math.max(e/a,t/o);l=a*n,u=o*n}let d=(e-l)/2,f=(t-u)/2,p=e=>({x:d+(c?1-e.x:e.x)*l,y:f+e.y*u});return{mapPt:p,mapRect:e=>{let t=p({x:e.x,y:e.y}),n=p({x:e.x+e.width,y:e.y+e.height}),r=Math.min(t.x,n.x),i=Math.min(t.y,n.y),a=Math.max(t.x,n.x),o=Math.max(t.y,n.y);return{x:r,y:i,width:a-r,height:o-i}}}},a=performance.now(),o=(e,t,n,i,o)=>{if(!r)return;let s=(performance.now()-a)/1e3,c=Math.min(e,t),l=Math.max(34,Math.round(c*.1)),u=Math.max(3,Math.round(c*.008)),d=.35+.55*(.5+.5*Math.sin(s*2.2)),f=Math.max(0,Math.min(1,i))*d,p=(.5+.5*Math.sin(s*2.2+1.4))*(l*.18),m=e/2,h=t/2,g=0,_=0;n===`left`&&(g=-p),n===`right`&&(g=p),n===`up`&&(_=-p),n===`down`&&(_=p);let v=m+g,y=h+_;r.save(),r.globalAlpha=f,r.lineJoin=`round`,r.lineCap=`round`,r.strokeStyle=`rgba(91, 140, 255, 0.35)`,r.lineWidth=u+6;let b=()=>{if(r.beginPath(),n===`left`||n===`right`){let e=l,t=n===`left`?-1:1;r.moveTo(v-e*.35*t,y-e*.33),r.lineTo(v+e*.35*t,y),r.lineTo(v-e*.35*t,y+e*.33)}else{let e=l,t=n===`up`?-1:1;r.moveTo(v-e*.33,y-e*.35*t),r.lineTo(v,y+e*.35*t),r.lineTo(v+e*.33,y-e*.35*t)}};b(),r.stroke(),r.strokeStyle=`rgba(255,255,255,0.92)`,r.lineWidth=u,b(),r.stroke(),o&&(r.font=`700 ${Math.max(12,Math.round(c*.035))}px system-ui, -apple-system, Segoe UI, Roboto, Arial`,r.fillStyle=`rgba(255,255,255,${Math.min(.95,f+.15)})`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(o,m,y+l*.52)),r.restore()},s=(e,t,n,i)=>{if(!r)return;let o=(performance.now()-a)/1e3,s=Math.min(e,t),c=e/2,l=t/2,u=.5+.5*Math.sin(o*2.2),d=Math.max(0,Math.min(1,n))*(.25+.55*u),f=Math.max(22,s*(.09+.03*u));r.save(),r.globalAlpha=d,r.strokeStyle=`rgba(91, 140, 255, 0.9)`,r.lineWidth=Math.max(3,Math.round(s*.008)),r.beginPath(),r.arc(c,l,f,0,Math.PI*2),r.stroke(),i&&(r.font=`700 ${Math.max(12,Math.round(s*.035))}px system-ui, -apple-system, Segoe UI, Roboto, Arial`,r.fillStyle=`rgba(255,255,255,${Math.min(.95,d+.15)})`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(i,c,l+f+6)),r.restore()},c=a=>{if(!r){console.warn(`Overlay: ctx is null (canvas context not available)`);return}n.width=e.offsetWidth,n.height=e.offsetHeight,console.log(`[Overlay] draw`,{w:n.width,h:n.height,containerW:e.offsetWidth,containerH:e.offsetHeight});let{w:c,h:l}=v(n,e,r),u=i(c,l,a.video,a.videoObjectFit,a.mirrored),d=(e,t,n=4)=>{let i=u.mapPt(e);r.save(),r.fillStyle=t,r.beginPath(),r.arc(i.x,i.y,n,0,Math.PI*2),r.fill(),r.restore()},f=(e,t,n)=>{r.save(),r.font=`12px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,r.textAlign=`left`,r.textBaseline=`bottom`,r.fillStyle=`rgba(0,0,0,0.55)`;let i=r.measureText(n).width;r.fillRect(e+6,t-14-6,i+8,18),r.fillStyle=`rgba(255,255,255,0.90)`,r.fillText(n,e+6+4,t-6),r.restore()};r.clearRect(0,0,c,l),r.fillStyle=`rgba(0,0,0,0.52)`,r.fillRect(0,0,c,l);let p=Math.min(c,l)*t*.5,m=c/2,h=l/2;if(a.hint){let e=typeof a.hint.intensity==`number`?a.hint.intensity:1;a.hint.type===`arrow`?o(c,l,a.hint.direction,e,a.hint.label):a.hint.type===`pulse`&&s(c,l,e,a.hint.label)}if(r.globalCompositeOperation=`destination-out`,r.beginPath(),r.arc(m,h,p,0,Math.PI*2),r.fill(),r.globalCompositeOperation=`source-over`,r.lineWidth=Math.max(3,Math.round(Math.min(c,l)*.01)),r.strokeStyle=a.valid?`rgba(46, 204, 113, 0.98)`:`rgba(255,255,255,0.92)`,r.beginPath(),r.arc(m,h,p,0,Math.PI*2),r.stroke(),a.box){let e=u.mapRect(a.box);r.lineWidth=2,r.strokeStyle=`rgba(52, 152, 219, 0.85)`,r.strokeRect(e.x,e.y,e.width,e.height)}let g=a.landmarkDraw?.eyes!==!1,_=a.landmarkDraw?.mouth!==!1,y=a.landmarkDraw?.nose!==!1,b=a.landmarkDraw?.jaw!==!1,x=a.landmarkDraw?.mouthJaw!==!1;if(a.landmarks){if(g){let e=[...a.landmarks.leftEye??[],...a.landmarks.rightEye??[]];if(e.length>0){let t=Math.max(2,Math.round(Math.min(c,l)*.006));r.save(),r.fillStyle=`rgba(0, 255, 255, 0.9)`;for(let n of e){let e=u.mapPt(n);r.beginPath(),r.arc(e.x,e.y,t,0,Math.PI*2),r.fill()}r.restore()}let t=[a.landmarks.leftEyeCenter,a.landmarks.rightEyeCenter].filter(Boolean);if(t.length>0){let e=Math.max(4,Math.round(Math.min(c,l)*.012));r.save(),r.fillStyle=`rgba(255, 64, 129, 0.95)`;for(let n of t){let t=u.mapPt(n);r.beginPath(),r.arc(t.x,t.y,e,0,Math.PI*2),r.fill()}r.restore()}}if(y){let e=a.landmarks.nosePoints??[];if(e.length>=2){r.save(),r.strokeStyle=`rgba(156, 39, 176, 0.9)`,r.lineWidth=Math.max(2,Math.round(Math.min(c,l)*.0035));let t=u.mapPt(e[0]);r.beginPath(),r.moveTo(t.x,t.y);for(let t=1;t<e.length;t++){let n=u.mapPt(e[t]);r.lineTo(n.x,n.y)}r.stroke(),r.restore()}}if(_){let e=a.landmarks.mouthPoints??[];if(e.length>=3){r.save(),r.strokeStyle=`rgba(76, 175, 80, 0.9)`,r.lineWidth=Math.max(2,Math.round(Math.min(c,l)*.0035));let t=u.mapPt(e[0]);r.beginPath(),r.moveTo(t.x,t.y);for(let t=1;t<e.length;t++){let n=u.mapPt(e[t]);r.lineTo(n.x,n.y)}r.closePath(),r.stroke(),r.restore(),r.save();let n=Math.max(2,Math.round(Math.min(c,l)*.004));for(let t=0;t<e.length;t++){let i=u.mapPt(e[t]);r.fillStyle=`rgba(76, 175, 80, 0.95)`,r.beginPath(),r.arc(i.x,i.y,n,0,Math.PI*2),r.fill(),(t===0||t===Math.floor(e.length/2)||t===e.length-1)&&(r.fillStyle=`rgba(0,0,0,0.55)`,r.fillRect(i.x+4,i.y-12,18,14),r.fillStyle=`rgba(255,255,255,0.9)`,r.font=`11px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,r.fillText(String(t),i.x+6,i.y-10))}r.restore()}}if(b){let e=a.landmarks.jawPoints??[];if(e.length>=2){r.save(),r.strokeStyle=`rgba(255, 193, 7, 0.95)`,r.lineWidth=Math.max(2,Math.round(Math.min(c,l)*.004));let t=u.mapPt(e[0]);r.beginPath(),r.moveTo(t.x,t.y);for(let t=1;t<e.length;t++){let n=u.mapPt(e[t]);r.lineTo(n.x,n.y)}r.stroke(),r.restore()}}if(y){let e=a.landmarks.noseTip;if(e){r.save();let t=Math.max(4,Math.round(Math.min(c,l)*.01)),n=u.mapPt(e);r.fillStyle=`rgba(156, 39, 176, 0.95)`,r.beginPath(),r.arc(n.x,n.y,t,0,Math.PI*2),r.fill(),r.restore()}}if(x){let e=a.landmarks.mouthLeft,t=a.landmarks.mouthRight,n=a.landmarks.jawLeft,i=a.landmarks.jawRight;if(a.landmarks.mouthJawLeftDist,a.landmarks.mouthJawRightDist,e&&t){let n=u.mapPt(e),i=u.mapPt(t),o=Math.hypot(i.x-n.x,i.y-n.y),s=a.landmarks.leftEyeCenter,c=a.landmarks.rightEyeCenter,l=s&&c?Math.hypot(u.mapPt(s).x-u.mapPt(c).x,u.mapPt(s).y-u.mapPt(c).y):null,p=l&&l>1e-6?o/l:null;r.save(),r.strokeStyle=`rgba(76, 175, 80, 0.85)`,r.lineWidth=3,r.setLineDash([6,4]),r.beginPath(),r.moveTo(n.x,n.y),r.lineTo(i.x,i.y),r.stroke(),r.setLineDash([]),r.restore(),d(e,`rgba(76, 175, 80, 0.95)`,5),d(t,`rgba(76, 175, 80, 0.95)`,5);let m=(n.x+i.x)/2,h=(n.y+i.y)/2;r.save(),r.fillStyle=`rgba(76, 175, 80, 0.95)`,r.beginPath(),r.arc(m,h,3,0,Math.PI*2),r.fill(),r.restore(),f(m,h,`mouthWidth: ${p==null?Math.round(o)+`px`:p.toFixed(2)+`xEye`}`)}let o;if(n&&i){let e=u.mapPt(n),t=u.mapPt(i);r.save(),r.strokeStyle=`rgba(255, 193, 7, 0.85)`,r.lineWidth=3,r.beginPath(),r.moveTo(e.x,e.y),r.lineTo(t.x,t.y),r.stroke(),r.restore(),o={x:(n.x+i.x)/2,y:(n.y+i.y)/2},d(o,`rgba(255, 193, 7, 0.95)`,5)}if(o&&(e||t)){let a=u.mapPt(o),s=(e,t,n)=>{let i=u.mapPt(e),o=Math.hypot(i.x-a.x,i.y-a.y);r.save(),r.strokeStyle=n,r.lineWidth=2,r.setLineDash([4,4]),r.beginPath(),r.moveTo(i.x,i.y),r.lineTo(a.x,a.y),r.stroke(),r.setLineDash([]),r.restore(),d(e,n.replace(`0.55`,`0.95`),4),f(i.x,i.y,`${t}: ${Math.round(o)}px`)};e&&s(e,`mouth->jawMid L`,`rgba(255, 64, 129, 0.70)`),t&&s(t,`mouth->jawMid R`,`rgba(33, 150, 243, 0.70)`);let p=[e,t].filter(Boolean);if(p.length>0){let e=p.reduce((e,t)=>({x:e.x+t.x/p.length,y:e.y+t.y/p.length}),{x:0,y:0}),t=u.mapPt(e),r=a.y-t.y,o=r>=0?1:-1,s=n&&i?Math.hypot(u.mapPt(n).x-u.mapPt(i).x,u.mapPt(n).y-u.mapPt(i).y):Math.min(c,l),d=s>0?Math.max(-1,Math.min(1,r/(s*.18))):o;f(a.x,a.y,`mouthAvg vs jawMid: ${o} (norm ${d.toFixed(2)})`)}}}if(g){let e=a.landmarks.leftEyeCenter,t=a.landmarks.rightEyeCenter;if(e&&t){let n=u.mapPt(e),i=u.mapPt(t);r.save(),r.strokeStyle=`rgba(33, 150, 243, 0.55)`,r.lineWidth=2,r.setLineDash([6,6]),r.beginPath(),r.moveTo(n.x,n.y),r.lineTo(i.x,i.y),r.stroke(),r.setLineDash([]),r.restore();let a=Math.hypot(e.x-t.x,e.y-t.y);f((n.x+i.x)/2,(n.y+i.y)/2,`eyeDist(norm): ${a.toFixed(3)}`)}}}if(a.debug&&a.debug.extra?.showOverlayTableCanvas){let e=Math.min(520,Math.round(c*.62)),t=[];typeof a.debug.status==`string`&&t.push(`Status: ${a.debug.status}`),typeof a.debug.ready==`boolean`&&t.push(`Ready: ${a.debug.ready}`),typeof a.debug.feedbackCode==`string`&&t.push(`Feedback: ${a.debug.feedbackCode}`),typeof a.debug.challenge==`string`&&t.push(`Challenge: ${a.debug.challenge}`);let n=typeof a.debug.faces==`number`?a.debug.faces:void 0,i=typeof a.debug.eyeL==`number`?a.debug.eyeL:void 0,o=typeof a.debug.eyeR==`number`?a.debug.eyeR:void 0;(n!=null||i!=null||o!=null)&&t.push(`Debug: faces=${n??`-`} | eyeL=${i==null?`-`:i.toFixed(2)} | eyeR=${o==null?`-`:o.toFixed(2)}`);let s=typeof a.debug.blinkCount==`number`?a.debug.blinkCount:void 0,u=typeof a.debug.blinkClosedNow==`boolean`?a.debug.blinkClosedNow:void 0,d=typeof a.debug.blinkClosedThreshold==`number`?a.debug.blinkClosedThreshold:void 0;(s!=null||u!=null||d!=null)&&t.push(`Blink: count=${s??`-`} | closedNow=${u??`-`} | thr=${d==null?`-`:d.toFixed(2)}`);let f=a.debug.mouthVsJawMidRaw,p=a.debug.mouthVsJawMidClamped;(typeof p==`number`||typeof f==`number`)&&t.push(`mouthAvg vs jawMid: ${typeof p==`number`?p.toFixed(2):`-`} (raw ${typeof f==`number`?f.toFixed(3):`-`})`);let m=a.debug.faceH;if(typeof m==`number`&&t.push(`faceH: ${m.toFixed(3)}`),typeof a.debug.stepPassed==`boolean`&&t.push(`stepPassed(${a.debug.currentStep??`-`}) = ${a.debug.stepPassed}`),a.debug.debugDraw?.cheese!==!1){let e=a.debug.mouthSmileRatio,n=a.debug.cheeseBaseline,r=a.debug.cheeseTarget;(typeof e==`number`||typeof n==`number`||typeof r==`number`)&&t.push(`Cheese: ratio=${typeof e==`number`?e.toFixed(3):`-`} | base=${typeof n==`number`?n.toFixed(3):`-`} | target=${typeof r==`number`?r.toFixed(3):`-`}`)}let h=24+t.length*16,g=l-h-88;r.save(),r.fillStyle=`rgba(0,0,0,0.60)`,r.strokeStyle=`rgba(255,255,255,0.12)`,r.lineWidth=1,r.beginPath(),r.roundRect?.(12,g,e,h,10),r.roundRect||r.rect(12,g,e,h),r.fill(),r.stroke(),r.fillStyle=`rgba(255,255,255,0.88)`,r.font=`12px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,r.textAlign=`left`,r.textBaseline=`top`;for(let e=0;e<t.length;e++)r.fillText(t[e],24,g+12+e*16);r.restore()}if(a.message){let e=Math.max(52,Math.round(l*.12)),t=l-e-16;r.fillStyle=`rgba(0,0,0,0.62)`,r.beginPath();let n=c-32,i=e;r.moveTo(30,t),r.arcTo(16+n,t,16+n,t+i,14),r.arcTo(16+n,t+i,16,t+i,14),r.arcTo(16,t+i,16,t,14),r.arcTo(16,t,16+n,t,14),r.closePath(),r.fill(),r.fillStyle=`white`,r.font=`600 ${Math.max(14,Math.round(Math.min(c,l)*.045))}px system-ui, -apple-system, Segoe UI, Roboto, Arial`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(a.message,c/2,t+i/2)}if(a.landmarks){let e=a.landmarks.mouthUpper,t=a.landmarks.mouthLower;if(e&&t){let n=u.mapPt(e),i=u.mapPt(t);r.save(),r.strokeStyle=`rgba(255, 87, 34, 0.85)`,r.lineWidth=3,r.setLineDash([6,4]),r.beginPath(),r.moveTo(n.x,n.y),r.lineTo(i.x,i.y),r.stroke(),r.setLineDash([]),r.restore(),d(e,`rgba(255, 87, 34, 1)`,7),d(t,`rgba(255, 87, 34, 1)`,7);let o=(n.x+i.x)/2,s=(n.y+i.y)/2;r.save(),r.fillStyle=`rgba(255, 87, 34, 0.95)`,r.beginPath(),r.arc(o,s,4,0,Math.PI*2),r.fill(),r.restore();let c=a.landmarks.mouthOpenNorm;f(o,s,`mouthOpen: ${c==null?Math.round(Math.abs(n.y-i.y))+`px`:c.toFixed(2)+`xEye`}`)}let n=a.landmarks.jawTopL,i=a.landmarks.jawTopR,o=a.landmarks.leftEyeCenter,s=a.landmarks.rightEyeCenter;if(n&&o){let e=u.mapPt(n),t=u.mapPt(o);r.save(),r.strokeStyle=`rgba(255, 0, 0, 0.85)`,r.lineWidth=3,r.setLineDash([5,4]),r.beginPath(),r.moveTo(e.x,e.y),r.lineTo(t.x,t.y),r.stroke(),r.setLineDash([]),r.restore(),d(n,`rgba(255,0,0,1)`,8);let i=a.debug?.jawEyeDistL;i??=Math.hypot(n.x-o.x,n.y-o.y),f((e.x+t.x)/2,(e.y+t.y)/2,`jawTopL→eyeL: ${i==null?`-`:i.toFixed(3)}`)}if(i&&s){let e=u.mapPt(i),t=u.mapPt(s);r.save(),r.strokeStyle=`rgba(0, 0, 255, 0.85)`,r.lineWidth=3,r.setLineDash([5,4]),r.beginPath(),r.moveTo(e.x,e.y),r.lineTo(t.x,t.y),r.stroke(),r.setLineDash([]),r.restore(),d(i,`rgba(0,0,255,1)`,8);let n=a.debug?.jawEyeDistR;n??=Math.hypot(i.x-s.x,i.y-s.y),f((e.x+t.x)/2,(e.y+t.y)/2,`jawTopR→eyeR: ${n==null?`-`:n.toFixed(3)}`)}}};return{canvas:n,dispose:()=>{n.parentElement&&n.parentElement.removeChild(n)},render:e=>c(e)}}var x=c(((e,t)=>{t.exports={}})),S=function(e,t){return(S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function C(e,t){function n(){this.constructor=e}S(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function w(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(o,s)}c((r=r.apply(e,t||[])).next())}))}function T(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw TypeError(`Generator is already executing.`);for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){o=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(a[0]===6&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}var E=function(){function e(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return e.prototype.setPlatform=function(e,t){this.platform!=null&&console.warn(`Platform `+this.platformName+` has already been set. Overwriting the platform with `+t+`.`),this.platformName=e,this.platform=t},e.prototype.registerFlag=function(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){var r=this.urlFlags[e];console.warn(`Setting feature override from URL `+e+`: `+r+`.`),this.set(e,r)}},e.prototype.get=function(e){return e in this.flags||(this.flags[e]=this.evaluateFlag(e)),this.flags[e]},e.prototype.getNumber=function(e){return this.get(e)},e.prototype.getBool=function(e){return this.get(e)},e.prototype.getFlags=function(){return this.flags},Object.defineProperty(e.prototype,`features`,{get:function(){return this.flags},enumerable:!0,configurable:!0}),e.prototype.set=function(e,t){if(this.flagRegistry[e]==null)throw Error(`Cannot set flag `+e+` as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)},e.prototype.evaluateFlag=function(e){if(this.flagRegistry[e]==null)throw Error(`Cannot evaluate flag '`+e+`': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()},e.prototype.setFlags=function(e){this.flags=Object.assign({},e)},e.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},e.prototype.populateURLFlags=function(){var e=this;if(this.global!==void 0&&this.global.location!==void 0&&this.global.location.search!==void 0){var t,n,r=(t=this.global.location.search,n={},t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return D(n,t[0],t[1]),t.join(`=`)})),n);`tfjsflags`in r&&r.tfjsflags.split(`,`).forEach((function(t){var n=t.split(`:`),r=n[0],i=n[1];e.urlFlags[r]=function(e,t){if((t=t.toLowerCase())===`true`||t===`false`)return t===`true`;if(``+ +t===t)return+t;throw Error(`Could not parse value flag value `+t+` for flag `+e+`.`)}(r,i)}))}},e}();function D(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||``)}function O(){return k}var k=null,A=new Map,j=new Map;function M(e,t){var n=te(e,t);return A.get(n)}function N(e){return j.get(e)}function P(e){for(var t=A.entries(),n=[];;){var r=t.next(),i=r.done,a=r.value;if(i)break;var o=a[0],s=a[1];o.split(`_`)[0]===e&&n.push(s)}return n}function F(e){var t=e.kernelName,n=e.backendName,r=te(t,n);if(A.has(r))throw Error(`The kernel '`+t+`' for backend '`+n+`' is already registered`);A.set(r,e)}function ee(e){var t=e.kernelName;j.has(t)&&console.warn(`Overriding the gradient for '`+t+`'`),j.set(t,e)}function te(e,t){return t+`_`+e}function ne(e){for(var t=e.length,n=0,r=0;t>0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function re(e,t,n){return Math.max(e,Math.min(t,n))}function ie(e){return e%2==0?e:e+1}function ae(e){for(var t=0,n=0;n<e.length;n++)t+=e[n];return t}function I(e,t){if(!e)throw Error(typeof t==`string`?t:t())}function L(e,t,n){n===void 0&&(n=``),I(z(e,t),(function(){return n+` Shapes `+e+` and `+t+` must match`}))}function oe(e){I(e!=null,(function(){return`The input to the tensor constructor must be a non-null value.`}))}function se(e,t,n){if(t===void 0&&(t=[]),n===void 0&&(n=!1),t??=[],Array.isArray(e)||xe(e)&&!n)for(var r=0;r<e.length;++r)se(e[r],t,n);else t.push(e);return t}function R(e){if(e.length===0)return 1;for(var t=e[0],n=1;n<e.length;n++)t*=e[n];return t}function z(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function ce(e){return e%1==0}function le(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;var t=Math.exp(2*e);return(t-1)/(t+1)}function ue(e){var t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function de(e,t){return t<=e.length?e:e+` `.repeat(t-e.length)}function fe(e,t,n){return t===void 0&&(t=function(e){return 0}),new Promise((function(r,i){var a=0,o=function(){if(e())r();else{a++;var s=t(a);n!=null&&a>=n?i():setTimeout(o,s)}};o()}))}function pe(e,t){for(var n=1,r=-1,i=0;i<e.length;++i)if(e[i]>=0)n*=e[i];else if(e[i]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim `+r+` and dim `+i);r=i}else if(e[i]<0)throw Error(`Shapes can not be < 0. Found `+e[i]+` at dim `+i);if(r===-1){if(t>0&&t!==n)throw Error(`Size(`+t+`) must match the product of shape `+e);return e}if(n===0)throw Error(`Cannot infer the missing size in [`+e+`] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got `+t+` / `+n);var a=e.slice();return a[r]=t/n,a}function me(e,t){var n=t.length;return I((e=e==null?t.map((function(e,t){return t})):[].concat(e)).every((function(e){return e>=-n&&e<n})),(function(){return`All values in axis param must be in range [-`+n+`, `+n+`) but got axis `+e})),I(e.every((function(e){return ce(e)})),(function(){return`All values in axis param must be integers but got axis `+e})),e.map((function(e){return e<0?n+e:e}))}function he(e,t){for(var n=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||i?null:me(t,e).sort(),o=0,s=0;s<e.length;++s){if(a!=null){if(a[o]===s&&e[s]!==1)throw Error(`Can't squeeze axis `+s+` since its dim '`+e[s]+`' is not 1`);(a[o]==null||a[o]>s)&&e[s]===1&&(n.push(e[s]),r.push(s)),a[o]<=s&&o++}e[s]!==1&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function ge(e,t){var n=null;if(e==null||e===`float32`)n=new Float32Array(t);else if(e===`int32`)n=new Int32Array(t);else{if(e!==`bool`)throw Error(`Unknown data type `+e);n=new Uint8Array(t)}return n}function _e(e,t){var n=null;if(e==null||e===`float32`)n=new Float32Array(t);else if(e===`int32`)n=new Int32Array(t);else if(e===`bool`)n=new Uint8Array(t);else{if(e!==`string`)throw Error(`Unknown data type `+e);n=Array(t)}return n}function ve(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type `+t+` being uploaded contains `+r+`.`)}}function ye(e){return e===`bool`||e===`complex64`||e===`float32`||e===`int32`||e===`string`}function be(e,t){return t!==`complex64`&&(t!==`float32`||e===`complex64`)&&(t!==`int32`||e===`float32`||e===`complex64`)&&(t!==`bool`||e!==`bool`)}function xe(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Se(e){if(e===`float32`||e===`int32`)return 4;if(e===`complex64`)return 8;if(e===`bool`)return 1;throw Error(`Unknown dtype `+e)}function Ce(e){if(e==null)return 0;var t=0;return e.forEach((function(e){return t+=e.length})),t}function we(e){return typeof e==`string`||e instanceof String}function Te(e){return typeof e==`boolean`}function Ee(e){return typeof e==`number`}function De(e){return Array.isArray(e)?De(e[0]):e instanceof Float32Array?`float32`:e instanceof Int32Array||e instanceof Uint8Array?`int32`:Ee(e)?`float32`:we(e)?`string`:Te(e)?`bool`:`float32`}function Oe(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ke(e,t){for(var n=t;n<e;++n)if(e%n==0)return n;return e}function Ae(e){var t=e.length;if(t<2)return[];var n=Array(t-1);n[t-2]=e[t-1];for(var r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function je(e,t,n){if(t===`string`)throw Error(`Cannot convert a string[] to a TypedArray`);if(Array.isArray(e)&&(e=se(e)),n&&ve(e,t),function(e,t){return e instanceof Float32Array&&t===`float32`||e instanceof Int32Array&&t===`int32`||e instanceof Uint8Array&&t===`bool`}(e,t))return e;if(t==null||t===`float32`||t===`complex64`)return new Float32Array(e);if(t===`int32`)return new Int32Array(e);if(t===`bool`){for(var r=new Uint8Array(e.length),i=0;i<r.length;++i)Math.round(e[i])!==0&&(r[i]=1);return r}throw Error(`Unknown data type `+t)}function Me(e,t){if(e.length===0)return t[0];var n=e.reduce((function(e,t){return e*t}));if(n===0)return[];if(n!==t.length)throw Error(`[`+e+`] does not match the input size.`);return function e(t,n,r){var i=[];if(n.length===1)for(var a=n[0],o=0;o<a;o++)i[o]=r[t+o];else{a=n[0];var s=n.slice(1),c=s.reduce((function(e,t){return e*t}));for(o=0;o<a;o++)i[o]=e(t+o*c,s,r)}return i}(0,e,t)}function Ne(e,t){for(var n=Pe(e,t),r=0;r<n.length;r++)n[r]=1;return n}function Pe(e,t){if(t==null||t===`float32`||t===`complex64`)return new Float32Array(e);if(t===`int32`)return new Int32Array(e);if(t===`bool`)return new Uint8Array(e);throw Error(`Unknown data type `+t)}function Fe(){return O().platform.now()}function Ie(e){e.forEach((function(t){I(Number.isInteger(t)&&t>=0,(function(){return`Tensor must have a shape comprised of positive integers but got shape [`+e+`].`}))}))}function Le(e,t){return t===void 0&&(t=`utf-8`),t||=`utf-8`,O().platform.encode(e,t)}function Re(e,t){return t===void 0&&(t=`utf-8`),t||=`utf-8`,O().platform.decode(e,t)}function ze(e,t,n){if(t===0)return 0;if(t===1)return e[0];for(var r=e[e.length-1],i=0;i<e.length-1;++i)r+=n[i]*e[i];return r}function Be(e,t,n){if(t===0)return[];if(t===1)return[e];for(var r=Array(t),i=0;i<r.length-1;++i)r[i]=Math.floor(e/n[i]),e-=r[i]*n[i];return r[r.length-1]=e,r}Object.freeze({shuffle:ne,clamp:re,nearestLargerEven:ie,sum:ae,randUniform:function(e,t){var n=Math.random();return t*n+(1-n)*e},distSquared:function(e,t){for(var n=0,r=0;r<e.length;r++){var i=Number(e[r])-Number(t[r]);n+=i*i}return n},assert:I,assertShapesMatch:L,assertNonNull:oe,flatten:se,sizeFromShape:R,isScalarShape:function(e){return e.length===0},arraysEqual:z,isInt:ce,tanh:le,sizeToSquarishShape:ue,createShuffledIndices:function(e){for(var t=new Uint32Array(e),n=0;n<e;++n)t[n]=n;return ne(t),t},rightPad:de,repeatedTry:fe,inferFromImplicitShape:pe,parseAxisParam:me,squeezeShape:he,getTypedArrayFromDType:ge,getArrayFromDType:_e,checkConversionForErrors:ve,isValidDtype:ye,hasEncodingLoss:be,isTypedArray:xe,bytesPerElement:Se,bytesFromStringArray:Ce,isString:we,isBoolean:Te,isNumber:Ee,inferDtype:De,isFunction:Oe,nearestDivisor:ke,computeStrides:Ae,toTypedArray:je,toNestedArray:Me,makeOnesTypedArray:Ne,makeZerosTypedArray:Pe,now:Fe,assertNonNegativeIntegerDimensions:Ie,fetch:function(e,t){return O().platform.fetch(e,t)},encodeString:Le,decodeString:Re,locToIndex:ze,indexToLoc:Be});var Ve=function(){function e(e,t){this.backendTimer=e,this.logger=t,t??(this.logger=new He)}return e.prototype.profileKernel=function(e,t,n){var r,i=this,a=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){(function(e,t,n){if(t!==`float32`)return!1;for(var r=0;r<e.length;r++){var i=e[r];if(isNaN(i)||!isFinite(i))return console.warn(`Found `+i+` in the result of '`+n+`'`),!0}})(r,n.dtype,e),a.then((function(a){var o=``;a.getExtraProfileInfo!=null&&(o=a.getExtraProfileInfo()),i.logger.logKernelProfile(e,n,r,a.kernelMs,t,o)}))}))})),r},e}(),He=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,n,r,i,a){var o=typeof r==`number`?de(r+`ms`,9):r.error,s=de(e,25),c=t.rank,l=t.size,u=de(t.shape.toString(),14),d=``;for(var f in i){var p=i[f].shape||t.shape,m=p.length;d+=f+`: `+m+`D `+(m>0?p:``)+` `}console.log(`%c`+s+` %c`+o+` %c`+c+`D `+u+` %c`+l+` %c`+d+` %c`+a,`font-weight:bold`,`color:red`,`color:blue`,`color: orange`,`color: green`,`color: steelblue`)},e}(),Ue=20,We=3,Ge=7;function Ke(e,t,n,r){var i=Ae(t),a=function(e,t,n,r){var i=R(t),a=r[r.length-1],o=Array(a).fill(0),s=t.length,c=n===`complex64`?Ye(e):e;if(s>1)for(var l=0;l<i/a;l++)for(var u=l*a,d=0;d<a;d++)o[d]=Math.max(o[d],qe(c[u+d],0,n).length);return o}(e,t,n,i),o=t.length,s=function e(t,n,r,i,a,o){o===void 0&&(o=!0);var s=r===`complex64`?2:1,c=n[0],l=n.length;if(l===0)return r===`complex64`?[qe(Ye(t)[0],0,r)]:r===`bool`?[Je(t[0])]:[t[0].toString()];if(l===1){if(c>Ue){var u=We*s,d=Array.from(t.slice(0,u)),f=Array.from(t.slice((c-We)*s,c*s));return r===`complex64`&&(d=Ye(d),f=Ye(f)),[`[`+d.map((function(e,t){return qe(e,a[t],r)})).join(`, `)+`, ..., `+f.map((function(e,t){return qe(e,a[c-We+t],r)})).join(`, `)+`]`]}return[`[`+(r===`complex64`?Ye(t):Array.from(t)).map((function(e,t){return qe(e,a[t],r)})).join(`, `)+`]`]}var p=n.slice(1),m=i.slice(1),h=i[0]*s,g=[];if(c>Ue){for(var _=0;_<We;_++){var v=(y=_*h)+h;g.push.apply(g,e(t.slice(y,v),p,r,m,a,!1))}for(g.push(`...`),_=c-We;_<c;_++)v=(y=_*h)+h,g.push.apply(g,e(t.slice(y,v),p,r,m,a,_===c-1))}else for(_=0;_<c;_++){var y;v=(y=_*h)+h,g.push.apply(g,e(t.slice(y,v),p,r,m,a,_===c-1))}var b=l===2?`,`:``;for(g[0]=`[`+g[0]+b,_=1;_<g.length-1;_++)g[_]=` `+g[_]+b;var x=`,
|
|
2
2
|
`;for(_=2;_<l;_++)x+=`
|
|
3
3
|
`;return g[g.length-1]=` `+g[g.length-1]+`]`+(o?``:x),g}(e,t,n,i,a),c=[`Tensor`];return r&&(c.push(` dtype: `+n),c.push(` rank: `+o),c.push(` shape: [`+t+`]`),c.push(` values:`)),c.push(s.map((function(e){return` `+e})).join(`
|
|
4
4
|
`)),c.join(`
|
|
5
|
-
`)}function Fe(e,t,n){return ee(Array.isArray(e)?parseFloat(e[0].toFixed(Ne))+` + `+parseFloat(e[1].toFixed(Ne))+`j`:fe(e)?`'`+e+`'`:n===`bool`?Ie(e):parseFloat(e.toFixed(Ne)).toString(),t)}function Ie(e){return e===0?`false`:`true`}function Le(e){for(var t=[],n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Re=function(){function e(e,t,n){var r=this;if(this.dtype=t,this.shape=e.slice(),this.size=M(e),n!=null){var i=n.length;O(i===this.size,(function(){return`Length of values '`+i+`' does not match the size inferred by the shape '`+r.size+`'.`}))}if(t===`complex64`)throw Error(`complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).`);this.values=n||ae(t,this.size),this.strides=ve(e)}return e.prototype.set=function(e){for(var t=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];n.length===0&&(n=[0]),O(n.length===this.rank,(function(){return`The number of provided coordinates (`+n.length+`) must match the rank (`+t.rank+`)`}));var i=this.locToIndex(n);this.values[i]=e},e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];e.length===0&&(e=[0]);for(var n=0,r=0,i=e;r<i.length;r++){var a=i[r];if(a<0||a>=this.shape[n]){var o=`Requested out of range element at `+e+`. Buffer shape=`+this.shape;throw Error(o)}n++}for(var s=e[e.length-1],c=0;c<e.length-1;++c)s+=this.strides[c]*e[c];return this.values[s]},e.prototype.locToIndex=function(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];for(var t=e[e.length-1],n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t},e.prototype.indexToLoc=function(e){if(this.rank===0)return[];if(this.rank===1)return[e];for(var t=Array(this.shape.length),n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t},Object.defineProperty(e.prototype,`rank`,{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return ze().makeTensor(this.values,this.shape,this.dtype)},e}(),ze=null,R=null,Be=null,Ve=function(){function e(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||`float32`,this.size=M(e),this.strides=ve(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():`higher`}return e.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},e.prototype.asScalar=function(){return this.throwIfDisposed(),O(this.size===1,(function(){return`The array must have only 1 element.`})),this.reshape([])},e.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},e.prototype.as2D=function(e,t){return this.throwIfDisposed(),this.reshape([e,t])},e.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),this.reshape([e,t,n])},e.prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),this.reshape([e,t,n,r])},e.prototype.as5D=function(e,t,n,r,i){return this.throwIfDisposed(),this.reshape([e,t,n,r,i])},e.prototype.asType=function(e){return this.throwIfDisposed(),R.cast(this,e)},Object.defineProperty(e.prototype,`rank`,{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.buffer=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,R.buffer(this.shape,this.dtype,e)]}}))}))},e.prototype.bufferSync=function(){return R.buffer(this.shape,this.dtype,this.dataSync())},e.prototype.array=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,be(this.shape,e)]}}))}))},e.prototype.arraySync=function(){return be(this.shape,this.dataSync())},e.prototype.data=function(){return u(this,void 0,void 0,(function(){var e,t;return d(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),e=ze().read(this.dataId),this.dtype===`string`?[4,e]:[3,2];case 1:t=n.sent();try{return[2,t.map((function(e){return Ee(e)}))]}catch{throw Error(`Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().`)}n.label=2;case 2:return[2,e]}}))}))},e.prototype.dataSync=function(){this.throwIfDisposed();var e=ze().readSync(this.dataId);if(this.dtype===`string`)try{return e.map((function(e){return Ee(e)}))}catch{throw Error(`Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().`)}return e},e.prototype.bytes=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return this.throwIfDisposed(),[4,ze().read(this.dataId)];case 1:return e=t.sent(),this.dtype===`string`?[2,e]:[2,new Uint8Array(e.buffer)]}}))}))},e.prototype.dispose=function(){this.isDisposed||(ze().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(e.prototype,`isDisposed`,{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),e.prototype.throwIfDisposed=function(){if(this.isDisposed)throw Error(`Tensor is disposed.`)},e.prototype.toFloat=function(){return this.asType(`float32`)},e.prototype.toInt=function(){return this.asType(`int32`)},e.prototype.toBool=function(){return this.asType(`bool`)},e.prototype.print=function(e){return e===void 0&&(e=!1),R.print(this,e)},e.prototype.reshape=function(e){return this.throwIfDisposed(),R.reshape(this,e)},e.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape)},e.prototype.expandDims=function(e){return e===void 0&&(e=0),R.expandDims(this,e)},e.prototype.cumsum=function(e,t,n){return e===void 0&&(e=0),t===void 0&&(t=!1),n===void 0&&(n=!1),R.cumsum(this,e,t,n)},e.prototype.squeeze=function(e){return this.throwIfDisposed(),R.squeeze(this,e)},e.prototype.clone=function(){return this.throwIfDisposed(),R.clone(this)},e.prototype.oneHot=function(e,t,n){return this.throwIfDisposed(),R.oneHot(this,e,t,n)},e.prototype.toString=function(e){return e===void 0&&(e=!1),Pe(this.dataSync(),this.shape,this.dtype,e)},e.prototype.tile=function(e){return this.throwIfDisposed(),R.tile(this,e)},e.prototype.gather=function(e,t){return t===void 0&&(t=0),this.throwIfDisposed(),R.gather(this,e,t)},e.prototype.matMul=function(e,t,n){return t===void 0&&(t=!1),n===void 0&&(n=!1),this.throwIfDisposed(),R.matMul(this,e,t,n)},e.prototype.dot=function(e){return this.throwIfDisposed(),R.dot(this,e)},e.prototype.norm=function(e,t,n){return e===void 0&&(e=`euclidean`),t===void 0&&(t=null),n===void 0&&(n=!1),this.throwIfDisposed(),R.norm(this,e,t,n)},e.prototype.slice=function(e,t){return this.throwIfDisposed(),R.slice(this,e,t)},e.prototype.reverse=function(e){return this.throwIfDisposed(),R.reverse(this,e)},e.prototype.concat=function(t,n){return n===void 0&&(n=0),this.throwIfDisposed(),t instanceof e&&(t=[t]),R.concat([this].concat(t),n)},e.prototype.split=function(e,t){return t===void 0&&(t=0),this.throwIfDisposed(),R.split(this,e,t)},e.prototype.stack=function(e,t){return t===void 0&&(t=0),R.stack([this,e],t)},e.prototype.unstack=function(e){return e===void 0&&(e=0),R.unstack(this,e)},e.prototype.pad=function(e,t){return t===void 0&&(t=0),R.pad(this,e,t)},e.prototype.batchNormalization=function(e,t,n,r,i){return n===void 0&&(n=.001),Be(`tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon`),this.batchNorm(e,t,i,r,n)},e.prototype.batchNorm=function(e,t,n,r,i){return i===void 0&&(i=.001),this.throwIfDisposed(),R.batchNorm(this,e,t,n,r,i)},e.prototype.all=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.all(this,e,t)},e.prototype.any=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.any(this,e,t)},e.prototype.logSumExp=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.logSumExp(this,e,t)},e.prototype.sum=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.sum(this,e,t)},e.prototype.prod=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.prod(this,e,t)},e.prototype.mean=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.mean(this,e,t)},e.prototype.min=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.min(this,e,t)},e.prototype.max=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),R.max(this,e,t)},e.prototype.argMin=function(e){return e===void 0&&(e=null),this.throwIfDisposed(),R.argMin(this,e)},e.prototype.argMax=function(e){return e===void 0&&(e=null),this.throwIfDisposed(),R.argMax(this,e)},e.prototype.cast=function(e){return this.throwIfDisposed(),R.cast(this,e)},e.prototype.add=function(e){return this.throwIfDisposed(),R.add(this,e)},e.prototype.addStrict=function(e){return this.throwIfDisposed(),R.addStrict(this,e)},e.prototype.atan2=function(e){return this.throwIfDisposed(),R.atan2(this,e)},e.prototype.sub=function(e){return this.throwIfDisposed(),R.sub(this,e)},e.prototype.subStrict=function(e){return this.throwIfDisposed(),R.subStrict(this,e)},e.prototype.pow=function(e){return this.throwIfDisposed(),R.pow(this,e)},e.prototype.powStrict=function(e){return this.throwIfDisposed(),R.powStrict(this,e)},e.prototype.mul=function(e){return this.throwIfDisposed(),R.mul(this,e)},e.prototype.mulStrict=function(e){return this.throwIfDisposed(),R.mulStrict(this,e)},e.prototype.div=function(e){return this.throwIfDisposed(),R.div(this,e)},e.prototype.divNoNan=function(e){return this.throwIfDisposed(),R.divNoNan(this,e)},e.prototype.floorDiv=function(e){return this.throwIfDisposed(),R.floorDiv(this,e)},e.prototype.divStrict=function(e){return this.throwIfDisposed(),R.divStrict(this,e)},e.prototype.minimum=function(e){return this.throwIfDisposed(),R.minimum(this,e)},e.prototype.minimumStrict=function(e){return this.throwIfDisposed(),R.minimumStrict(this,e)},e.prototype.maximum=function(e){return this.throwIfDisposed(),R.maximum(this,e)},e.prototype.maximumStrict=function(e){return this.throwIfDisposed(),R.maximumStrict(this,e)},e.prototype.mod=function(e){return this.throwIfDisposed(),R.mod(this,e)},e.prototype.modStrict=function(e){return this.throwIfDisposed(),R.modStrict(this,e)},e.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),R.squaredDifferenceStrict(this,e)},e.prototype.transpose=function(e){return this.throwIfDisposed(),R.transpose(this,e)},e.prototype.notEqual=function(e){return this.throwIfDisposed(),R.notEqual(this,e)},e.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),R.notEqualStrict(this,e)},e.prototype.less=function(e){return this.throwIfDisposed(),R.less(this,e)},e.prototype.lessStrict=function(e){return this.throwIfDisposed(),R.lessStrict(this,e)},e.prototype.equal=function(e){return this.throwIfDisposed(),R.equal(this,e)},e.prototype.equalStrict=function(e){return this.throwIfDisposed(),R.equalStrict(this,e)},e.prototype.lessEqual=function(e){return this.throwIfDisposed(),R.lessEqual(this,e)},e.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),R.lessEqualStrict(this,e)},e.prototype.greater=function(e){return this.throwIfDisposed(),R.greater(this,e)},e.prototype.greaterStrict=function(e){return this.throwIfDisposed(),R.greaterStrict(this,e)},e.prototype.greaterEqual=function(e){return this.throwIfDisposed(),R.greaterEqual(this,e)},e.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),R.greaterEqualStrict(this,e)},e.prototype.logicalAnd=function(e){return this.throwIfDisposed(),R.logicalAnd(this,e)},e.prototype.logicalOr=function(e){return this.throwIfDisposed(),R.logicalOr(this,e)},e.prototype.logicalNot=function(){return this.throwIfDisposed(),R.logicalNot(this)},e.prototype.logicalXor=function(e){return this.throwIfDisposed(),R.logicalXor(this,e)},e.prototype.where=function(e,t){return this.throwIfDisposed(),R.where(e,this,t)},e.prototype.neg=function(){return this.throwIfDisposed(),R.neg(this)},e.prototype.ceil=function(){return this.throwIfDisposed(),R.ceil(this)},e.prototype.floor=function(){return this.throwIfDisposed(),R.floor(this)},e.prototype.sign=function(){return this.throwIfDisposed(),R.sign(this)},e.prototype.isNaN=function(){return this.throwIfDisposed(),R.isNaN(this)},e.prototype.isInf=function(){return this.throwIfDisposed(),R.isInf(this)},e.prototype.isFinite=function(){return this.throwIfDisposed(),R.isFinite(this)},e.prototype.exp=function(){return this.throwIfDisposed(),R.exp(this)},e.prototype.expm1=function(){return this.throwIfDisposed(),R.expm1(this)},e.prototype.log=function(){return this.throwIfDisposed(),R.log(this)},e.prototype.log1p=function(){return this.throwIfDisposed(),R.log1p(this)},e.prototype.sqrt=function(){return this.throwIfDisposed(),R.sqrt(this)},e.prototype.rsqrt=function(){return this.throwIfDisposed(),R.rsqrt(this)},e.prototype.square=function(){return this.throwIfDisposed(),R.square(this)},e.prototype.reciprocal=function(){return this.throwIfDisposed(),R.reciprocal(this)},e.prototype.abs=function(){return this.throwIfDisposed(),R.abs(this)},e.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),R.clipByValue(this,e,t)},e.prototype.relu=function(){return this.throwIfDisposed(),R.relu(this)},e.prototype.relu6=function(){return this.throwIfDisposed(),R.relu6(this)},e.prototype.elu=function(){return this.throwIfDisposed(),R.elu(this)},e.prototype.selu=function(){return this.throwIfDisposed(),R.selu(this)},e.prototype.leakyRelu=function(e){return e===void 0&&(e=.2),this.throwIfDisposed(),R.leakyRelu(this,e)},e.prototype.prelu=function(e){return this.throwIfDisposed(),R.prelu(this,e)},e.prototype.sigmoid=function(){return this.throwIfDisposed(),R.sigmoid(this)},e.prototype.logSigmoid=function(){return this.throwIfDisposed(),R.logSigmoid(this)},e.prototype.softplus=function(){return this.throwIfDisposed(),R.softplus(this)},e.prototype.zerosLike=function(){return this.throwIfDisposed(),R.zerosLike(this)},e.prototype.onesLike=function(){return this.throwIfDisposed(),R.onesLike(this)},e.prototype.sin=function(){return this.throwIfDisposed(),R.sin(this)},e.prototype.cos=function(){return this.throwIfDisposed(),R.cos(this)},e.prototype.tan=function(){return this.throwIfDisposed(),R.tan(this)},e.prototype.asin=function(){return this.throwIfDisposed(),R.asin(this)},e.prototype.acos=function(){return this.throwIfDisposed(),R.acos(this)},e.prototype.atan=function(){return this.throwIfDisposed(),R.atan(this)},e.prototype.sinh=function(){return this.throwIfDisposed(),R.sinh(this)},e.prototype.cosh=function(){return this.throwIfDisposed(),R.cosh(this)},e.prototype.tanh=function(){return this.throwIfDisposed(),R.tanh(this)},e.prototype.asinh=function(){return this.throwIfDisposed(),R.asinh(this)},e.prototype.acosh=function(){return this.throwIfDisposed(),R.acosh(this)},e.prototype.atanh=function(){return this.throwIfDisposed(),R.atanh(this)},e.prototype.erf=function(){return this.throwIfDisposed(),R.erf(this)},e.prototype.round=function(){return this.throwIfDisposed(),R.round(this)},e.prototype.step=function(e){return e===void 0&&(e=0),this.throwIfDisposed(),R.step(this,e)},e.prototype.softmax=function(e){return e===void 0&&(e=-1),this.throwIfDisposed(),R.softmax(this,e)},e.prototype.logSoftmax=function(e){return e===void 0&&(e=-1),this.throwIfDisposed(),R.logSoftmax(this,e)},e.prototype.resizeBilinear=function(e,t){return t===void 0&&(t=!1),this.throwIfDisposed(),R.image.resizeBilinear(this,e,t)},e.prototype.resizeNearestNeighbor=function(e,t){return t===void 0&&(t=!1),this.throwIfDisposed(),R.image.resizeNearestNeighbor(this,e,t)},e.prototype.conv1d=function(e,t,n,r,i,a){return r===void 0&&(r=`NWC`),i===void 0&&(i=1),this.throwIfDisposed(),R.conv1d(this,e,t,n,r,i,a)},e.prototype.conv2d=function(e,t,n,r,i,a){return r===void 0&&(r=`NHWC`),i===void 0&&(i=[1,1]),this.throwIfDisposed(),R.conv2d(this,e,t,n,r,i,a)},e.prototype.conv2dTranspose=function(e,t,n,r,i){return this.throwIfDisposed(),R.conv2dTranspose(this,e,t,n,r,i)},e.prototype.depthwiseConv2D=function(e,t,n,r,i,a){return r===void 0&&(r=`NHWC`),i===void 0&&(i=[1,1]),this.throwIfDisposed(),R.depthwiseConv2d(this,e,t,n,r,i,a)},e.prototype.separableConv2d=function(e,t,n,r,i,a){return i===void 0&&(i=[1,1]),a===void 0&&(a=`NHWC`),this.throwIfDisposed(),R.separableConv2d(this,e,t,n,r,i,a)},e.prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),R.avgPool(this,e,t,n,r)},e.prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),R.maxPool(this,e,t,n,r)},e.prototype.localResponseNormalization=function(e,t,n,r){return e===void 0&&(e=5),t===void 0&&(t=1),n===void 0&&(n=1),r===void 0&&(r=.5),R.localResponseNormalization(this,e,t,n,r)},e.prototype.pool=function(e,t,n,r,i){return this.throwIfDisposed(),R.pool(this,e,t,n,r,i)},e.prototype.variable=function(e,t,n){return e===void 0&&(e=!0),this.throwIfDisposed(),ze().makeVariable(this,e,t,n)},e.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),R.unsortedSegmentSum(this,e,t)},e.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),R.batchToSpaceND(this,e,t)},e.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),R.spaceToBatchND(this,e,t)},e.prototype.topk=function(e,t){return e===void 0&&(e=1),t===void 0&&(t=!0),this.throwIfDisposed(),R.topk(this,e,t)},e.prototype.stridedSlice=function(e,t,n,r,i,a,o,s){return r===void 0&&(r=0),i===void 0&&(i=0),a===void 0&&(a=0),o===void 0&&(o=0),s===void 0&&(s=0),this.throwIfDisposed(),R.stridedSlice(this,e,t,n,r,i,a,o,s)},e.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),R.depthToSpace(this,e,t)},e.prototype.fft=function(){return this.throwIfDisposed(),R.spectral.fft(this)},e.prototype.ifft=function(){return this.throwIfDisposed(),R.spectral.ifft(this)},e.prototype.rfft=function(){return this.throwIfDisposed(),R.spectral.rfft(this)},e.prototype.irfft=function(){return this.throwIfDisposed(),R.spectral.irfft(this)},e}();Object.defineProperty(Ve,Symbol.hasInstance,{value:function(e){return!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null}});var He,Ue,We,Ge,Ke,qe=function(e){function t(t,n,r,i){var a=e.call(this,t.shape,t.dtype,t.dataId,i)||this;return a.trainable=n,a.name=r,a}return l(t,e),t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw Error(`dtype of the new value (`+e.dtype+`) and previous value (`+this.dtype+`) must match`);if(!N(e.shape,this.shape))throw Error(`shape of the new value (`+e.shape+`) and previous value (`+this.shape+`) must match`);ze().disposeTensor(this),this.dataId=e.dataId,ze().incRef(this,null)},t.prototype.dispose=function(){ze().disposeVariable(this),this.isDisposedInternal=!0},t}(Ve);Object.defineProperty(qe,Symbol.hasInstance,{value:function(e){return e instanceof Ve&&e.assign!=null&&e.assign instanceof Function}}),function(e){e.R0=`R0`,e.R1=`R1`,e.R2=`R2`,e.R3=`R3`,e.R4=`R4`,e.R5=`R5`,e.R6=`R6`}(He||={}),function(e){e.float32=`float32`,e.int32=`int32`,e.bool=`int32`,e.complex64=`complex64`}(Ue||={}),function(e){e.float32=`float32`,e.int32=`int32`,e.bool=`bool`,e.complex64=`complex64`}(We||={}),function(e){e.float32=`float32`,e.int32=`float32`,e.bool=`float32`,e.complex64=`complex64`}(Ge||={}),function(e){e.float32=`complex64`,e.int32=`complex64`,e.bool=`complex64`,e.complex64=`complex64`}(Ke||={});var Je={float32:Ge,int32:Ue,bool:We,complex64:Ke};function Ye(e,t){if(e===`string`||t===`string`){if(e===`string`&&t===`string`)return`string`;throw Error(`Can not upcast `+e+` with `+t)}return Je[e][t]}function Xe(e){return Ye(e,`int32`)}function Ze(e,t){if(e.dtype===t.dtype)return[e,t];var n=Ye(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Qe(e,t){O(e.dtype===t.dtype,(function(){return`The dtypes of the first(`+e.dtype+`) and second(`+t.dtype+`) input must match`}))}function $e(e){var t=[];return function e(t,n,r){if(t!=null){if(t instanceof Ve)return void n.push(t);if(i=t,!(!Array.isArray(i)&&typeof i!=`object`)){var i,a=t;for(var o in a){var s=a[o];r.has(s)||(r.add(s),e(s,n,r))}}}}(e,t,new Set),t}var et;Object.freeze({makeTypesMatch:Ze,assertTypesMatch:Qe,isTensorInList:function(e,t){return t.some((function(t){return t.id===e.id}))},getTensorsInContainer:$e});var tt=function(){function e(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return e.prototype.dispose=function(){for(var e in this.registeredVariables)this.registeredVariables[e].dispose()},e}(),nt=function(){function e(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new tt}return e.prototype.ready=function(){return u(this,void 0,void 0,(function(){var e,t,n;return d(this,(function(r){switch(r.label){case 0:if(this.pendingBackendInit!=null)return[2,this.pendingBackendInit.then((function(){}))];if(this.backendInstance!=null)return[2];e=this.getSortedBackends(),t=0,r.label=1;case 1:return t<e.length?(n=e[t],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return t++,[3,1];case 5:throw Error(`Could not initialize any backends, all backend initializations failed.`)}}))}))},Object.defineProperty(e.prototype,`backend`,{get:function(){if(this.pendingBackendInit!=null)throw Error(`Backend '`+this.backendName+`' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){var e=this.initializeBackendsAndReturnBest(),t=e.name;if(e.asyncInit)throw Error(`The highest priority backend '`+t+`' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance},enumerable:!0,configurable:!0}),e.prototype.backendNames=function(){return Object.keys(this.registryFactory)},e.prototype.findBackend=function(e){return!(e in this.registry)&&(!(e in this.registryFactory)||this.initializeBackend(e).asyncInit)?null:this.registry[e]},e.prototype.findBackendFactory=function(e){return e in this.registryFactory?this.registryFactory[e].factory:null},e.prototype.registerBackend=function(e,t,n){return n===void 0&&(n=1),e in this.registryFactory?(console.warn(e+` backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)},e.prototype.setBackend=function(e){return u(this,void 0,void 0,(function(){var t,n,r;return d(this,(function(i){switch(i.label){case 0:if(this.registryFactory[e]==null)throw Error(`Backend name '`+e+`' not found in registry`);return this.backendName=e,this.registry[e]==null?(this.backendInstance=null,t=this.initializeBackend(e),n=t.success,t.asyncInit?[4,n]:[3,2]):[3,4];case 1:return r=i.sent(),[3,3];case 2:r=n,i.label=3;case 3:if(!r)return[2,!1];i.label=4;case 4:return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new ke(this.backendInstance),[2,!0]}}))}))},e.prototype.setupRegisteredKernels=function(){var e=this;b(this.backendName).forEach((function(t){t.setupFunc!=null&&t.setupFunc(e.backendInstance)}))},e.prototype.disposeRegisteredKernels=function(e){var t=this;b(e).forEach((function(n){n.disposeFunc!=null&&n.disposeFunc(t.registry[e])}))},e.prototype.initializeBackend=function(e){var t=this,n=this.registryFactory[e];if(n==null)throw Error(`Cannot initialize backend `+e+`, no registration found.`);try{var r=n.factory();if(Promise.resolve(r)===r){var i=++this.pendingBackendInitId,a=r.then((function(n){return!(i<t.pendingBackendInitId)&&(t.registry[e]=n,t.pendingBackendInit=null,!0)})).catch((function(n){return!(i<t.pendingBackendInitId)&&(t.pendingBackendInit=null,console.warn(`Initialization of backend `+e+` failed`),console.warn(n.stack||n.message),!1)}));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(t){return console.warn(`Initialization of backend `+e+` failed`),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}},e.prototype.removeBackend=function(e){if(!(e in this.registryFactory))throw Error(e+` backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},e.prototype.getSortedBackends=function(){var e=this;if(Object.keys(this.registryFactory).length===0)throw Error(`No backend found in registry.`);return Object.keys(this.registryFactory).sort((function(t,n){return e.registryFactory[n].priority-e.registryFactory[t].priority}))},e.prototype.initializeBackendsAndReturnBest=function(){for(var e=this.getSortedBackends(),t=0;t<e.length;t++){var n=e[t],r=this.initializeBackend(n),i=r.success,a=r.asyncInit;if(a||i)return{name:n,asyncInit:a}}throw Error(`Could not initialize any backends, all backend initializations failed.`)},e.prototype.moveData=function(e,t){var n=this.state.tensorInfo.get(t),r=n.backend,i=this.readSync(t);r.disposeData(t),n.backend=e,e.move(t,i,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},e.prototype.tidy=function(e,t){var n,r=this,i=null;if(t==null){if(typeof e!=`function`)throw Error(`Please provide a function to tidy()`);t=e}else{if(typeof e!=`string`&&!(e instanceof String))throw Error(`When calling with two arguments, the first argument to tidy() must be a string`);if(typeof t!=`function`)throw Error(`When calling with two arguments, the 2nd argument to tidy() must be a function`);i=e}return this.scopedRun((function(){return r.startScope(i)}),(function(){return r.endScope(n)}),(function(){return(n=t())instanceof Promise&&console.error(`Cannot return a Promise inside of tidy.`),n}))},e.prototype.scopedRun=function(e,t,n){e();try{var r=n();return t(),r}catch(e){throw t(),e}},e.prototype.nextTensorId=function(){return e.nextTensorId++},e.prototype.nextVariableId=function(){return e.nextVariableId++},e.prototype.clone=function(e){var t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(function(e){return{x:function(){return e.toFloat()}}}),[]),t},e.prototype.runKernel=function(e,t,n,r,i){return this.runKernelFunc(null,t,null,e,n,r,i)},e.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool(`IS_TEST`)},e.prototype.checkKernelForMemLeak=function(e,t,n){var r=this.backend.numDataIds(),i=0;n.forEach((function(e){i+=e.dtype===`complex64`?3:1}));var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-i-a;if(o>0)throw Error(`Backend '`+this.backendName+`' has an internal memory leak (`+o+` data ids) after running '`+e+`'`)},e.prototype.runKernelFunc=function(e,t,n,r,i,a,o){var s,c=this;a===void 0&&(a=[]),o===void 0&&(o=[]);var l=[],u=this.isTapeOn();r??=this.state.activeScope==null?``:this.state.activeScope.name;var d,f=function(e){u&&(l=e.map((function(e){return c.keep(c.clone(e))})))},p=this.state.numBytes,m=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var h,g=v(r,this.backendName);return d=g==null?function(){var t=c.backend.numDataIds();h=c.tidy((function(){return e(c.backend,f)}));var n=Array.isArray(h)?h:[h];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,t,n),n}:function(){var e=c.backend.numDataIds();h=g.kernelFunc({inputs:t,attrs:i,backend:c.backend});var n=Array.isArray(h)?h:[h];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,e,n);var s=n.map((function(e){var t=e.dataId,n=e.shape,r=e.dtype;return c.makeTensorFromDataId(t,n,r)})),l=s.filter((function(e,t){return o[t]}));return f((a||[]).slice().concat(l)),s},this.scopedRun((function(){return c.state.kernelDepth++}),(function(){return c.state.kernelDepth--}),(function(){s=c.ENV.getBool(`DEBUG`)?c.profiler.profileKernel(r,t,(function(){return d()})):d()})),u&&this.addTapeNode(r,t,s,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-m,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map((function(e){return t[e].shape})),outputShapes:s.map((function(e){return e.shape}))}),Array.isArray(h)?s:s[0]},e.prototype.makeTensor=function(e,t,n,r){if(e==null)throw Error(`Values passed to engine.makeTensor() are null`);n||=`float32`,r||=this.backend;var i=e;n===`string`&&fe(e[0])&&(i=e.map((function(e){return Te(e)})));var a=r.write(i,t,n),o=new Ve(t,n,a,this.nextTensorId());if(this.incRef(o,r),n===`string`){var s=this.state.tensorInfo.get(a),c=de(i);this.state.numBytes+=c-s.bytes,s.bytes=c}return o},e.prototype.makeTensorFromDataId=function(e,t,n,r){var i=new Ve(t,n||=`float32`,e,this.nextTensorId());return this.incRef(i,r),i},e.prototype.makeVariable=function(e,t,n,r){t===void 0&&(t=!0),n||=this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.asType(r));var i=new qe(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw Error(`Variable with name `+i.name+` was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i},e.prototype.incRef=function(e,t){var n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype===`string`&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;var r=0;e.dtype!==`complex64`&&e.dtype!==`string`&&(r=e.size*ue(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof qe||this.track(e)},e.prototype.disposeTensor=function(e){if(this.state.tensorInfo.has(e.dataId)){this.state.numTensors--,e.dtype===`string`&&this.state.numStringTensors--;var t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?(e.dtype!==`complex64`&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}},e.prototype.disposeVariables=function(){for(var e in this.state.registeredVariables){var t=this.state.registeredVariables[e];this.disposeVariable(t)}},e.prototype.disposeVariable=function(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons??=[],e.reasons.push(`Memory usage by string tensors is approximate (2 bytes per character)`)),e},e.prototype.profile=function(e){return u(this,void 0,void 0,(function(){var t,n;return d(this,(function(r){return this.state.profiling=!0,t=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(e){return e.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},e.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},e.prototype.addTapeNode=function(e,t,n,r,i){var a=this,o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},s=y(e);s!=null&&(r=s.gradFunc),r!=null&&(o.gradient=function(e){return e=e.map((function(e,t){if(e==null){var r=n[t],i=Se(r.size,r.dtype);return a.makeTensor(i,r.shape,r.dtype)}return e})),r(e.length>1?e:e[0],i)}),this.state.activeTape.push(o)},e.prototype.keep=function(e){return e.kept=!0,e},e.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},e.prototype.endTape=function(){this.state.gradientDepth--},e.prototype.startScope=function(e){var t={track:[],name:`unnamed scope`,id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t},e.prototype.endScope=function(e){for(var t=this,n=$e(e),r=new Set(n.map((function(e){return e.id}))),i=0;i<this.state.activeScope.track.length;i++){var a=this.state.activeScope.track[i];a.kept||r.has(a.id)||a.dispose()}var o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(e){e.kept||e.scopeId!==o.id||t.track(e)}))},e.prototype.gradients=function(e,t,n,r){var i=this;if(r===void 0&&(r=!1),O(t.length>0,(function(){return`gradients() received an empty list of xs.`})),n!=null&&n.dtype!==`float32`)throw Error(`dy must have 'float32' dtype, but has '`+n.dtype+`'`);var a=this.scopedRun((function(){return i.startTape()}),(function(){return i.endTape()}),(function(){return i.tidy(`forward`,e)}));O(a instanceof Ve,(function(){return`The result y returned by f() must be a tensor.`}));var o=function(e,t,n){for(var r={},i={},a=0;a<t.length;a++)r[t[a].id]=!0;for(a=0;a<e.length;a++){var o=(m=e[a]).inputs;for(var s in o){for(var c=o[s],l=!1,u=0;u<t.length;u++)if(r[c.id]){m.outputs.forEach((function(e){return r[e.id]=!0})),l=!0,i[m.id]=!0;break}if(l)break}}var d={};d[n.id]=!0;var f={};for(a=e.length-1;a>=0;a--)for(o=(m=e[a]).inputs,u=0;u<m.outputs.length;u++)if(d[m.outputs[u].id]){for(var s in o)d[o[s].id]=!0,f[m.id]=!0;break}var p=[];for(a=0;a<e.length;a++){var m;if(i[(m=e[a]).id]&&f[m.id]){var h={};for(var s in m.inputs){var g=m.inputs[s];r[g.id]&&(h[s]=g)}var _=Object.assign({},m);_.inputs=h,_.outputs=m.outputs,p.push(_)}}return p}(this.state.activeTape,t,a);if(!r&&o.length===0&&t.length>0)throw Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.`);return this.tidy(`backward`,(function(){var e,r,s={};s[a.id]=n??(e=a.shape,r=xe(M(e),`float32`),z.makeTensor(r,e,`float32`)),function(e,t,n){for(var r=function(r){var i=t[r],a=[];if(i.outputs.forEach((function(t){var n=e[t.id];n==null?a.push(null):a.push(n)})),i.gradient==null)throw Error(`Cannot compute gradient: gradient function not found for `+i.kernelName+`.`);var o=i.gradient(a),s=function(t){if(!(t in o))throw Error(`Cannot backprop through input `+t+`. Available gradients found: `+Object.keys(o)+`.`);var r=n((function(){return o[t]()}));if(r.dtype!==`float32`)throw Error(`Error in gradient for op `+i.kernelName+`. The gradient of input `+t+` must have 'float32' dtype, but has '`+r.dtype+`'`);var a=i.inputs[t];if(!N(r.shape,a.shape))throw Error(`Error in gradient for op `+i.kernelName+`. The gradient of input '`+t+`' has shape '`+r.shape+`', which does not match the shape of the input '`+a.shape+`'`);if(e[a.id]==null)e[a.id]=r;else{var s=e[a.id];e[a.id]=s.add(r),s.dispose()}};for(var c in i.inputs)s(c)},i=t.length-1;i>=0;i--)r(i)}(s,o,(function(e){return i.tidy(e)}));var c=t.map((function(e){return s[e.id]}));return i.state.gradientDepth===0&&(i.state.activeTape.forEach((function(e){for(var t=0,n=e.saved;t<n.length;t++)n[t].dispose()})),i.state.activeTape=null),{value:a,grads:c}}))},e.prototype.customGrad=function(e){var t=this;return O(ge(e),(function(){return`The f passed in customGrad(f) must be a function.`})),function(){for(var n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];O(r.every((function(e){return e instanceof Ve})),(function(){return`The args passed in customGrad(f)(x1, x2,...) must all be tensors`}));var a={};return r.forEach((function(e,t){a[t]=e})),t.runKernelFunc((function(t,i){return O((n=e.apply(void 0,r.concat([i]))).value instanceof Ve,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),O(ge(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),a,(function(e,t){var i=n.gradFunc(e,t),a=Array.isArray(i)?i:[i];O(a.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),O(a.every((function(e){return e instanceof Ve})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var o={};return a.forEach((function(e,t){o[t]=function(){return e}})),o}))}},e.prototype.readSync=function(e){return this.state.tensorInfo.get(e).backend.readSync(e)},e.prototype.read=function(e){return this.state.tensorInfo.get(e).backend.read(e)},e.prototype.time=function(e){return u(this,void 0,void 0,(function(){var t,n;return d(this,(function(r){switch(r.label){case 0:return t=Ce(),[4,this.backend.time(e)];case 1:return(n=r.sent()).wallMs=Ce()-t,[2,n]}}))}))},e.prototype.track=function(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e},Object.defineProperty(e.prototype,`registeredVariables`,{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),e.prototype.reset=function(){for(var e in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new tt,this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},e.nextTensorId=0,e.nextVariableId=0,e}(),z=function(){var e=function(){if(et==null){var e=void 0;if(typeof window<`u`)e=window;else if(typeof global<`u`)e=global;else if(typeof process<`u`)e=process;else{if(typeof self>`u`)throw Error(`Could not find a global object`);e=self}et=e}return et}();return e._tfengine??=new nt(new f(e)),function(e){h=e}(e._tfengine.ENV),ze=function(){return e._tfengine},e._tfengine}();function rt(){return typeof window<`u`&&window.document!=null||typeof WorkerGlobalScope<`u`}var it=m();it.registerFlag(`DEBUG`,(function(){return!1}),(function(e){e&&console.warn(`Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.`)})),it.registerFlag(`IS_BROWSER`,(function(){return rt()})),it.registerFlag(`IS_NODE`,(function(){return typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0})),it.registerFlag(`IS_CHROME`,(function(){return typeof navigator<`u`&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),it.registerFlag(`PROD`,(function(){return!1})),it.registerFlag(`TENSORLIKE_CHECK_SHAPE_CONSISTENCY`,(function(){return it.getBool(`DEBUG`)})),it.registerFlag(`DEPRECATION_WARNINGS_ENABLED`,(function(){return!0})),it.registerFlag(`IS_TEST`,(function(){return!1}));var at,ot,st,ct={},lt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function ut(e,t){ct[e]=t}function dt(e){e in ct||(ct[e]=function(e){if(e!==1&&e!==2)throw Error(`Cannot get WebGL rendering context, WebGL is disabled.`);var t=function(e){if(typeof OffscreenCanvas<`u`&&e===2)return new OffscreenCanvas(300,150);if(typeof document<`u`)return document.createElement(`canvas`);throw Error(`Cannot create a canvas in this context`)}(e);return t.addEventListener(`webglcontextlost`,(function(t){t.preventDefault(),delete ct[e]}),!1),e===1?t.getContext(`webgl`,lt)||t.getContext(`experimental-webgl`,lt):t.getContext(`webgl2`,lt)}(e));var t=ct[e];return t.isContextLost()?(delete ct[e],dt(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),ct[e])}function ft(e,t){return[t,e]}function pt(e){var t=M(e);return I(Math.ceil(t/4))}function mt(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function ht(e,t){var n,r,i,a,o,s,c,l,u,d=e;return m().getNumber(`WEBGL_VERSION`)===2?(n=d.R32F,r=d.R16F,i=d.RGBA16F,a=d.RGBA32F,o=d.RED,s=4,c=1,l=d.HALF_FLOAT,u=d.FLOAT):(n=e.RGBA,r=e.RGBA,i=e.RGBA,a=d.RGBA,o=e.RGBA,s=4,c=4,l=t==null?null:t.HALF_FLOAT_OES,u=e.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:a,textureFormatFloat:o,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:u}}function B(e,t,n){var r=n();return t&&function(e){var t=e.getError();if(t!==e.NO_ERROR)throw Error(`WebGL Error: `+yt(e,t))}(e),r}(function(e){e[e.DENSE=0]=`DENSE`,e[e.SHARED_BATCH=1]=`SHARED_BATCH`})(at||={}),function(e){e[e.RENDER=0]=`RENDER`,e[e.UPLOAD=1]=`UPLOAD`,e[e.PIXELS=2]=`PIXELS`,e[e.DOWNLOAD=3]=`DOWNLOAD`}(ot||={}),function(e){e[e.UNPACKED_FLOAT16=0]=`UNPACKED_FLOAT16`,e[e.UNPACKED_FLOAT32=1]=`UNPACKED_FLOAT32`,e[e.PACKED_4X1_UNSIGNED_BYTE=2]=`PACKED_4X1_UNSIGNED_BYTE`,e[e.PACKED_2X2_FLOAT32=3]=`PACKED_2X2_FLOAT32`,e[e.PACKED_2X2_FLOAT16=4]=`PACKED_2X2_FLOAT16`}(st||={});var gt=5.96e-8,_t=65504;function vt(e){return!!(m().getBool(`WEBGL_RENDER_FLOAT32_ENABLED`)||e===0||gt<Math.abs(e)&&Math.abs(e)<_t)}function yt(e,t){switch(t){case e.NO_ERROR:return`NO_ERROR`;case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`Unknown error code `+t}}function bt(e,t,n){return Ut(e,t,(function(){return e.getExtension(n)}),`Extension "`+n+`" not supported on this browser.`)}function xt(e,t,n){var r=Ut(e,t,(function(){return e.createShader(e.VERTEX_SHADER)}),`Unable to create vertex WebGLShader.`);if(B(e,t,(function(){return e.shaderSource(r,n)})),B(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(r)),Error(`Failed to compile vertex shader.`);return r}function St(e,t,n){var r=Ut(e,t,(function(){return e.createShader(e.FRAGMENT_SHADER)}),`Unable to create fragment WebGLShader.`);if(B(e,t,(function(){return e.shaderSource(r,n)})),B(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw function(e,t){var n=Tt.exec(t);if(n==null)return console.log(`Couldn't parse line number in error: `+t),void console.log(e);for(var r=+n[1],i=e.split(`
|
|
6
|
-
`),a=i.length.toString().length+2,o=i.map((function(e,t){return
|
|
5
|
+
`)}function qe(e,t,n){return de(Array.isArray(e)?parseFloat(e[0].toFixed(Ge))+` + `+parseFloat(e[1].toFixed(Ge))+`j`:we(e)?`'`+e+`'`:n===`bool`?Je(e):parseFloat(e.toFixed(Ge)).toString(),t)}function Je(e){return e===0?`false`:`true`}function Ye(e){for(var t=[],n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Xe=function(){function e(e,t,n){var r=this;if(this.dtype=t,this.shape=e.slice(),this.size=R(e),n!=null){var i=n.length;I(i===this.size,(function(){return`Length of values '`+i+`' does not match the size inferred by the shape '`+r.size+`'.`}))}if(t===`complex64`)throw Error(`complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).`);this.values=n||_e(t,this.size),this.strides=Ae(e)}return e.prototype.set=function(e){for(var t=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];n.length===0&&(n=[0]),I(n.length===this.rank,(function(){return`The number of provided coordinates (`+n.length+`) must match the rank (`+t.rank+`)`}));var i=this.locToIndex(n);this.values[i]=e},e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];e.length===0&&(e=[0]);for(var n=0,r=0,i=e;r<i.length;r++){var a=i[r];if(a<0||a>=this.shape[n]){var o=`Requested out of range element at `+e+`. Buffer shape=`+this.shape;throw Error(o)}n++}for(var s=e[e.length-1],c=0;c<e.length-1;++c)s+=this.strides[c]*e[c];return this.values[s]},e.prototype.locToIndex=function(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];for(var t=e[e.length-1],n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t},e.prototype.indexToLoc=function(e){if(this.rank===0)return[];if(this.rank===1)return[e];for(var t=Array(this.shape.length),n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t},Object.defineProperty(e.prototype,`rank`,{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return Ze().makeTensor(this.values,this.shape,this.dtype)},e}(),Ze=null,B=null,Qe=null,$e=function(){function e(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||`float32`,this.size=R(e),this.strides=Ae(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():`higher`}return e.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},e.prototype.asScalar=function(){return this.throwIfDisposed(),I(this.size===1,(function(){return`The array must have only 1 element.`})),this.reshape([])},e.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},e.prototype.as2D=function(e,t){return this.throwIfDisposed(),this.reshape([e,t])},e.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),this.reshape([e,t,n])},e.prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),this.reshape([e,t,n,r])},e.prototype.as5D=function(e,t,n,r,i){return this.throwIfDisposed(),this.reshape([e,t,n,r,i])},e.prototype.asType=function(e){return this.throwIfDisposed(),B.cast(this,e)},Object.defineProperty(e.prototype,`rank`,{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.buffer=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,B.buffer(this.shape,this.dtype,e)]}}))}))},e.prototype.bufferSync=function(){return B.buffer(this.shape,this.dtype,this.dataSync())},e.prototype.array=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,Me(this.shape,e)]}}))}))},e.prototype.arraySync=function(){return Me(this.shape,this.dataSync())},e.prototype.data=function(){return w(this,void 0,void 0,(function(){var e,t;return T(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),e=Ze().read(this.dataId),this.dtype===`string`?[4,e]:[3,2];case 1:t=n.sent();try{return[2,t.map((function(e){return Re(e)}))]}catch{throw Error(`Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().`)}n.label=2;case 2:return[2,e]}}))}))},e.prototype.dataSync=function(){this.throwIfDisposed();var e=Ze().readSync(this.dataId);if(this.dtype===`string`)try{return e.map((function(e){return Re(e)}))}catch{throw Error(`Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().`)}return e},e.prototype.bytes=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return this.throwIfDisposed(),[4,Ze().read(this.dataId)];case 1:return e=t.sent(),this.dtype===`string`?[2,e]:[2,new Uint8Array(e.buffer)]}}))}))},e.prototype.dispose=function(){this.isDisposed||(Ze().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(e.prototype,`isDisposed`,{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),e.prototype.throwIfDisposed=function(){if(this.isDisposed)throw Error(`Tensor is disposed.`)},e.prototype.toFloat=function(){return this.asType(`float32`)},e.prototype.toInt=function(){return this.asType(`int32`)},e.prototype.toBool=function(){return this.asType(`bool`)},e.prototype.print=function(e){return e===void 0&&(e=!1),B.print(this,e)},e.prototype.reshape=function(e){return this.throwIfDisposed(),B.reshape(this,e)},e.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape)},e.prototype.expandDims=function(e){return e===void 0&&(e=0),B.expandDims(this,e)},e.prototype.cumsum=function(e,t,n){return e===void 0&&(e=0),t===void 0&&(t=!1),n===void 0&&(n=!1),B.cumsum(this,e,t,n)},e.prototype.squeeze=function(e){return this.throwIfDisposed(),B.squeeze(this,e)},e.prototype.clone=function(){return this.throwIfDisposed(),B.clone(this)},e.prototype.oneHot=function(e,t,n){return this.throwIfDisposed(),B.oneHot(this,e,t,n)},e.prototype.toString=function(e){return e===void 0&&(e=!1),Ke(this.dataSync(),this.shape,this.dtype,e)},e.prototype.tile=function(e){return this.throwIfDisposed(),B.tile(this,e)},e.prototype.gather=function(e,t){return t===void 0&&(t=0),this.throwIfDisposed(),B.gather(this,e,t)},e.prototype.matMul=function(e,t,n){return t===void 0&&(t=!1),n===void 0&&(n=!1),this.throwIfDisposed(),B.matMul(this,e,t,n)},e.prototype.dot=function(e){return this.throwIfDisposed(),B.dot(this,e)},e.prototype.norm=function(e,t,n){return e===void 0&&(e=`euclidean`),t===void 0&&(t=null),n===void 0&&(n=!1),this.throwIfDisposed(),B.norm(this,e,t,n)},e.prototype.slice=function(e,t){return this.throwIfDisposed(),B.slice(this,e,t)},e.prototype.reverse=function(e){return this.throwIfDisposed(),B.reverse(this,e)},e.prototype.concat=function(t,n){return n===void 0&&(n=0),this.throwIfDisposed(),t instanceof e&&(t=[t]),B.concat([this].concat(t),n)},e.prototype.split=function(e,t){return t===void 0&&(t=0),this.throwIfDisposed(),B.split(this,e,t)},e.prototype.stack=function(e,t){return t===void 0&&(t=0),B.stack([this,e],t)},e.prototype.unstack=function(e){return e===void 0&&(e=0),B.unstack(this,e)},e.prototype.pad=function(e,t){return t===void 0&&(t=0),B.pad(this,e,t)},e.prototype.batchNormalization=function(e,t,n,r,i){return n===void 0&&(n=.001),Qe(`tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon`),this.batchNorm(e,t,i,r,n)},e.prototype.batchNorm=function(e,t,n,r,i){return i===void 0&&(i=.001),this.throwIfDisposed(),B.batchNorm(this,e,t,n,r,i)},e.prototype.all=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.all(this,e,t)},e.prototype.any=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.any(this,e,t)},e.prototype.logSumExp=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.logSumExp(this,e,t)},e.prototype.sum=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.sum(this,e,t)},e.prototype.prod=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.prod(this,e,t)},e.prototype.mean=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.mean(this,e,t)},e.prototype.min=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.min(this,e,t)},e.prototype.max=function(e,t){return e===void 0&&(e=null),t===void 0&&(t=!1),this.throwIfDisposed(),B.max(this,e,t)},e.prototype.argMin=function(e){return e===void 0&&(e=null),this.throwIfDisposed(),B.argMin(this,e)},e.prototype.argMax=function(e){return e===void 0&&(e=null),this.throwIfDisposed(),B.argMax(this,e)},e.prototype.cast=function(e){return this.throwIfDisposed(),B.cast(this,e)},e.prototype.add=function(e){return this.throwIfDisposed(),B.add(this,e)},e.prototype.addStrict=function(e){return this.throwIfDisposed(),B.addStrict(this,e)},e.prototype.atan2=function(e){return this.throwIfDisposed(),B.atan2(this,e)},e.prototype.sub=function(e){return this.throwIfDisposed(),B.sub(this,e)},e.prototype.subStrict=function(e){return this.throwIfDisposed(),B.subStrict(this,e)},e.prototype.pow=function(e){return this.throwIfDisposed(),B.pow(this,e)},e.prototype.powStrict=function(e){return this.throwIfDisposed(),B.powStrict(this,e)},e.prototype.mul=function(e){return this.throwIfDisposed(),B.mul(this,e)},e.prototype.mulStrict=function(e){return this.throwIfDisposed(),B.mulStrict(this,e)},e.prototype.div=function(e){return this.throwIfDisposed(),B.div(this,e)},e.prototype.divNoNan=function(e){return this.throwIfDisposed(),B.divNoNan(this,e)},e.prototype.floorDiv=function(e){return this.throwIfDisposed(),B.floorDiv(this,e)},e.prototype.divStrict=function(e){return this.throwIfDisposed(),B.divStrict(this,e)},e.prototype.minimum=function(e){return this.throwIfDisposed(),B.minimum(this,e)},e.prototype.minimumStrict=function(e){return this.throwIfDisposed(),B.minimumStrict(this,e)},e.prototype.maximum=function(e){return this.throwIfDisposed(),B.maximum(this,e)},e.prototype.maximumStrict=function(e){return this.throwIfDisposed(),B.maximumStrict(this,e)},e.prototype.mod=function(e){return this.throwIfDisposed(),B.mod(this,e)},e.prototype.modStrict=function(e){return this.throwIfDisposed(),B.modStrict(this,e)},e.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),B.squaredDifferenceStrict(this,e)},e.prototype.transpose=function(e){return this.throwIfDisposed(),B.transpose(this,e)},e.prototype.notEqual=function(e){return this.throwIfDisposed(),B.notEqual(this,e)},e.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),B.notEqualStrict(this,e)},e.prototype.less=function(e){return this.throwIfDisposed(),B.less(this,e)},e.prototype.lessStrict=function(e){return this.throwIfDisposed(),B.lessStrict(this,e)},e.prototype.equal=function(e){return this.throwIfDisposed(),B.equal(this,e)},e.prototype.equalStrict=function(e){return this.throwIfDisposed(),B.equalStrict(this,e)},e.prototype.lessEqual=function(e){return this.throwIfDisposed(),B.lessEqual(this,e)},e.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),B.lessEqualStrict(this,e)},e.prototype.greater=function(e){return this.throwIfDisposed(),B.greater(this,e)},e.prototype.greaterStrict=function(e){return this.throwIfDisposed(),B.greaterStrict(this,e)},e.prototype.greaterEqual=function(e){return this.throwIfDisposed(),B.greaterEqual(this,e)},e.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),B.greaterEqualStrict(this,e)},e.prototype.logicalAnd=function(e){return this.throwIfDisposed(),B.logicalAnd(this,e)},e.prototype.logicalOr=function(e){return this.throwIfDisposed(),B.logicalOr(this,e)},e.prototype.logicalNot=function(){return this.throwIfDisposed(),B.logicalNot(this)},e.prototype.logicalXor=function(e){return this.throwIfDisposed(),B.logicalXor(this,e)},e.prototype.where=function(e,t){return this.throwIfDisposed(),B.where(e,this,t)},e.prototype.neg=function(){return this.throwIfDisposed(),B.neg(this)},e.prototype.ceil=function(){return this.throwIfDisposed(),B.ceil(this)},e.prototype.floor=function(){return this.throwIfDisposed(),B.floor(this)},e.prototype.sign=function(){return this.throwIfDisposed(),B.sign(this)},e.prototype.isNaN=function(){return this.throwIfDisposed(),B.isNaN(this)},e.prototype.isInf=function(){return this.throwIfDisposed(),B.isInf(this)},e.prototype.isFinite=function(){return this.throwIfDisposed(),B.isFinite(this)},e.prototype.exp=function(){return this.throwIfDisposed(),B.exp(this)},e.prototype.expm1=function(){return this.throwIfDisposed(),B.expm1(this)},e.prototype.log=function(){return this.throwIfDisposed(),B.log(this)},e.prototype.log1p=function(){return this.throwIfDisposed(),B.log1p(this)},e.prototype.sqrt=function(){return this.throwIfDisposed(),B.sqrt(this)},e.prototype.rsqrt=function(){return this.throwIfDisposed(),B.rsqrt(this)},e.prototype.square=function(){return this.throwIfDisposed(),B.square(this)},e.prototype.reciprocal=function(){return this.throwIfDisposed(),B.reciprocal(this)},e.prototype.abs=function(){return this.throwIfDisposed(),B.abs(this)},e.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),B.clipByValue(this,e,t)},e.prototype.relu=function(){return this.throwIfDisposed(),B.relu(this)},e.prototype.relu6=function(){return this.throwIfDisposed(),B.relu6(this)},e.prototype.elu=function(){return this.throwIfDisposed(),B.elu(this)},e.prototype.selu=function(){return this.throwIfDisposed(),B.selu(this)},e.prototype.leakyRelu=function(e){return e===void 0&&(e=.2),this.throwIfDisposed(),B.leakyRelu(this,e)},e.prototype.prelu=function(e){return this.throwIfDisposed(),B.prelu(this,e)},e.prototype.sigmoid=function(){return this.throwIfDisposed(),B.sigmoid(this)},e.prototype.logSigmoid=function(){return this.throwIfDisposed(),B.logSigmoid(this)},e.prototype.softplus=function(){return this.throwIfDisposed(),B.softplus(this)},e.prototype.zerosLike=function(){return this.throwIfDisposed(),B.zerosLike(this)},e.prototype.onesLike=function(){return this.throwIfDisposed(),B.onesLike(this)},e.prototype.sin=function(){return this.throwIfDisposed(),B.sin(this)},e.prototype.cos=function(){return this.throwIfDisposed(),B.cos(this)},e.prototype.tan=function(){return this.throwIfDisposed(),B.tan(this)},e.prototype.asin=function(){return this.throwIfDisposed(),B.asin(this)},e.prototype.acos=function(){return this.throwIfDisposed(),B.acos(this)},e.prototype.atan=function(){return this.throwIfDisposed(),B.atan(this)},e.prototype.sinh=function(){return this.throwIfDisposed(),B.sinh(this)},e.prototype.cosh=function(){return this.throwIfDisposed(),B.cosh(this)},e.prototype.tanh=function(){return this.throwIfDisposed(),B.tanh(this)},e.prototype.asinh=function(){return this.throwIfDisposed(),B.asinh(this)},e.prototype.acosh=function(){return this.throwIfDisposed(),B.acosh(this)},e.prototype.atanh=function(){return this.throwIfDisposed(),B.atanh(this)},e.prototype.erf=function(){return this.throwIfDisposed(),B.erf(this)},e.prototype.round=function(){return this.throwIfDisposed(),B.round(this)},e.prototype.step=function(e){return e===void 0&&(e=0),this.throwIfDisposed(),B.step(this,e)},e.prototype.softmax=function(e){return e===void 0&&(e=-1),this.throwIfDisposed(),B.softmax(this,e)},e.prototype.logSoftmax=function(e){return e===void 0&&(e=-1),this.throwIfDisposed(),B.logSoftmax(this,e)},e.prototype.resizeBilinear=function(e,t){return t===void 0&&(t=!1),this.throwIfDisposed(),B.image.resizeBilinear(this,e,t)},e.prototype.resizeNearestNeighbor=function(e,t){return t===void 0&&(t=!1),this.throwIfDisposed(),B.image.resizeNearestNeighbor(this,e,t)},e.prototype.conv1d=function(e,t,n,r,i,a){return r===void 0&&(r=`NWC`),i===void 0&&(i=1),this.throwIfDisposed(),B.conv1d(this,e,t,n,r,i,a)},e.prototype.conv2d=function(e,t,n,r,i,a){return r===void 0&&(r=`NHWC`),i===void 0&&(i=[1,1]),this.throwIfDisposed(),B.conv2d(this,e,t,n,r,i,a)},e.prototype.conv2dTranspose=function(e,t,n,r,i){return this.throwIfDisposed(),B.conv2dTranspose(this,e,t,n,r,i)},e.prototype.depthwiseConv2D=function(e,t,n,r,i,a){return r===void 0&&(r=`NHWC`),i===void 0&&(i=[1,1]),this.throwIfDisposed(),B.depthwiseConv2d(this,e,t,n,r,i,a)},e.prototype.separableConv2d=function(e,t,n,r,i,a){return i===void 0&&(i=[1,1]),a===void 0&&(a=`NHWC`),this.throwIfDisposed(),B.separableConv2d(this,e,t,n,r,i,a)},e.prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),B.avgPool(this,e,t,n,r)},e.prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),B.maxPool(this,e,t,n,r)},e.prototype.localResponseNormalization=function(e,t,n,r){return e===void 0&&(e=5),t===void 0&&(t=1),n===void 0&&(n=1),r===void 0&&(r=.5),B.localResponseNormalization(this,e,t,n,r)},e.prototype.pool=function(e,t,n,r,i){return this.throwIfDisposed(),B.pool(this,e,t,n,r,i)},e.prototype.variable=function(e,t,n){return e===void 0&&(e=!0),this.throwIfDisposed(),Ze().makeVariable(this,e,t,n)},e.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),B.unsortedSegmentSum(this,e,t)},e.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),B.batchToSpaceND(this,e,t)},e.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),B.spaceToBatchND(this,e,t)},e.prototype.topk=function(e,t){return e===void 0&&(e=1),t===void 0&&(t=!0),this.throwIfDisposed(),B.topk(this,e,t)},e.prototype.stridedSlice=function(e,t,n,r,i,a,o,s){return r===void 0&&(r=0),i===void 0&&(i=0),a===void 0&&(a=0),o===void 0&&(o=0),s===void 0&&(s=0),this.throwIfDisposed(),B.stridedSlice(this,e,t,n,r,i,a,o,s)},e.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),B.depthToSpace(this,e,t)},e.prototype.fft=function(){return this.throwIfDisposed(),B.spectral.fft(this)},e.prototype.ifft=function(){return this.throwIfDisposed(),B.spectral.ifft(this)},e.prototype.rfft=function(){return this.throwIfDisposed(),B.spectral.rfft(this)},e.prototype.irfft=function(){return this.throwIfDisposed(),B.spectral.irfft(this)},e}();Object.defineProperty($e,Symbol.hasInstance,{value:function(e){return!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null}});var et,tt,nt,rt,it,at=function(e){function t(t,n,r,i){var a=e.call(this,t.shape,t.dtype,t.dataId,i)||this;return a.trainable=n,a.name=r,a}return C(t,e),t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw Error(`dtype of the new value (`+e.dtype+`) and previous value (`+this.dtype+`) must match`);if(!z(e.shape,this.shape))throw Error(`shape of the new value (`+e.shape+`) and previous value (`+this.shape+`) must match`);Ze().disposeTensor(this),this.dataId=e.dataId,Ze().incRef(this,null)},t.prototype.dispose=function(){Ze().disposeVariable(this),this.isDisposedInternal=!0},t}($e);Object.defineProperty(at,Symbol.hasInstance,{value:function(e){return e instanceof $e&&e.assign!=null&&e.assign instanceof Function}}),function(e){e.R0=`R0`,e.R1=`R1`,e.R2=`R2`,e.R3=`R3`,e.R4=`R4`,e.R5=`R5`,e.R6=`R6`}(et||={}),function(e){e.float32=`float32`,e.int32=`int32`,e.bool=`int32`,e.complex64=`complex64`}(tt||={}),function(e){e.float32=`float32`,e.int32=`int32`,e.bool=`bool`,e.complex64=`complex64`}(nt||={}),function(e){e.float32=`float32`,e.int32=`float32`,e.bool=`float32`,e.complex64=`complex64`}(rt||={}),function(e){e.float32=`complex64`,e.int32=`complex64`,e.bool=`complex64`,e.complex64=`complex64`}(it||={});var ot={float32:rt,int32:tt,bool:nt,complex64:it};function st(e,t){if(e===`string`||t===`string`){if(e===`string`&&t===`string`)return`string`;throw Error(`Can not upcast `+e+` with `+t)}return ot[e][t]}function ct(e){return st(e,`int32`)}function lt(e,t){if(e.dtype===t.dtype)return[e,t];var n=st(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ut(e,t){I(e.dtype===t.dtype,(function(){return`The dtypes of the first(`+e.dtype+`) and second(`+t.dtype+`) input must match`}))}function dt(e){var t=[];return function e(t,n,r){if(t!=null){if(t instanceof $e)return void n.push(t);if(i=t,!(!Array.isArray(i)&&typeof i!=`object`)){var i,a=t;for(var o in a){var s=a[o];r.has(s)||(r.add(s),e(s,n,r))}}}}(e,t,new Set),t}var ft;Object.freeze({makeTypesMatch:lt,assertTypesMatch:ut,isTensorInList:function(e,t){return t.some((function(t){return t.id===e.id}))},getTensorsInContainer:dt});var pt=function(){function e(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return e.prototype.dispose=function(){for(var e in this.registeredVariables)this.registeredVariables[e].dispose()},e}(),mt=function(){function e(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new pt}return e.prototype.ready=function(){return w(this,void 0,void 0,(function(){var e,t,n;return T(this,(function(r){switch(r.label){case 0:if(this.pendingBackendInit!=null)return[2,this.pendingBackendInit.then((function(){}))];if(this.backendInstance!=null)return[2];e=this.getSortedBackends(),t=0,r.label=1;case 1:return t<e.length?(n=e[t],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return t++,[3,1];case 5:throw Error(`Could not initialize any backends, all backend initializations failed.`)}}))}))},Object.defineProperty(e.prototype,`backend`,{get:function(){if(this.pendingBackendInit!=null)throw Error(`Backend '`+this.backendName+`' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){var e=this.initializeBackendsAndReturnBest(),t=e.name;if(e.asyncInit)throw Error(`The highest priority backend '`+t+`' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance},enumerable:!0,configurable:!0}),e.prototype.backendNames=function(){return Object.keys(this.registryFactory)},e.prototype.findBackend=function(e){return!(e in this.registry)&&(!(e in this.registryFactory)||this.initializeBackend(e).asyncInit)?null:this.registry[e]},e.prototype.findBackendFactory=function(e){return e in this.registryFactory?this.registryFactory[e].factory:null},e.prototype.registerBackend=function(e,t,n){return n===void 0&&(n=1),e in this.registryFactory?(console.warn(e+` backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)},e.prototype.setBackend=function(e){return w(this,void 0,void 0,(function(){var t,n,r;return T(this,(function(i){switch(i.label){case 0:if(this.registryFactory[e]==null)throw Error(`Backend name '`+e+`' not found in registry`);return this.backendName=e,this.registry[e]==null?(this.backendInstance=null,t=this.initializeBackend(e),n=t.success,t.asyncInit?[4,n]:[3,2]):[3,4];case 1:return r=i.sent(),[3,3];case 2:r=n,i.label=3;case 3:if(!r)return[2,!1];i.label=4;case 4:return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Ve(this.backendInstance),[2,!0]}}))}))},e.prototype.setupRegisteredKernels=function(){var e=this;P(this.backendName).forEach((function(t){t.setupFunc!=null&&t.setupFunc(e.backendInstance)}))},e.prototype.disposeRegisteredKernels=function(e){var t=this;P(e).forEach((function(n){n.disposeFunc!=null&&n.disposeFunc(t.registry[e])}))},e.prototype.initializeBackend=function(e){var t=this,n=this.registryFactory[e];if(n==null)throw Error(`Cannot initialize backend `+e+`, no registration found.`);try{var r=n.factory();if(Promise.resolve(r)===r){var i=++this.pendingBackendInitId,a=r.then((function(n){return!(i<t.pendingBackendInitId)&&(t.registry[e]=n,t.pendingBackendInit=null,!0)})).catch((function(n){return!(i<t.pendingBackendInitId)&&(t.pendingBackendInit=null,console.warn(`Initialization of backend `+e+` failed`),console.warn(n.stack||n.message),!1)}));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(t){return console.warn(`Initialization of backend `+e+` failed`),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}},e.prototype.removeBackend=function(e){if(!(e in this.registryFactory))throw Error(e+` backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},e.prototype.getSortedBackends=function(){var e=this;if(Object.keys(this.registryFactory).length===0)throw Error(`No backend found in registry.`);return Object.keys(this.registryFactory).sort((function(t,n){return e.registryFactory[n].priority-e.registryFactory[t].priority}))},e.prototype.initializeBackendsAndReturnBest=function(){for(var e=this.getSortedBackends(),t=0;t<e.length;t++){var n=e[t],r=this.initializeBackend(n),i=r.success,a=r.asyncInit;if(a||i)return{name:n,asyncInit:a}}throw Error(`Could not initialize any backends, all backend initializations failed.`)},e.prototype.moveData=function(e,t){var n=this.state.tensorInfo.get(t),r=n.backend,i=this.readSync(t);r.disposeData(t),n.backend=e,e.move(t,i,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},e.prototype.tidy=function(e,t){var n,r=this,i=null;if(t==null){if(typeof e!=`function`)throw Error(`Please provide a function to tidy()`);t=e}else{if(typeof e!=`string`&&!(e instanceof String))throw Error(`When calling with two arguments, the first argument to tidy() must be a string`);if(typeof t!=`function`)throw Error(`When calling with two arguments, the 2nd argument to tidy() must be a function`);i=e}return this.scopedRun((function(){return r.startScope(i)}),(function(){return r.endScope(n)}),(function(){return(n=t())instanceof Promise&&console.error(`Cannot return a Promise inside of tidy.`),n}))},e.prototype.scopedRun=function(e,t,n){e();try{var r=n();return t(),r}catch(e){throw t(),e}},e.prototype.nextTensorId=function(){return e.nextTensorId++},e.prototype.nextVariableId=function(){return e.nextVariableId++},e.prototype.clone=function(e){var t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(function(e){return{x:function(){return e.toFloat()}}}),[]),t},e.prototype.runKernel=function(e,t,n,r,i){return this.runKernelFunc(null,t,null,e,n,r,i)},e.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool(`IS_TEST`)},e.prototype.checkKernelForMemLeak=function(e,t,n){var r=this.backend.numDataIds(),i=0;n.forEach((function(e){i+=e.dtype===`complex64`?3:1}));var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-i-a;if(o>0)throw Error(`Backend '`+this.backendName+`' has an internal memory leak (`+o+` data ids) after running '`+e+`'`)},e.prototype.runKernelFunc=function(e,t,n,r,i,a,o){var s,c=this;a===void 0&&(a=[]),o===void 0&&(o=[]);var l=[],u=this.isTapeOn();r??=this.state.activeScope==null?``:this.state.activeScope.name;var d,f=function(e){u&&(l=e.map((function(e){return c.keep(c.clone(e))})))},p=this.state.numBytes,m=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var h,g=M(r,this.backendName);return d=g==null?function(){var t=c.backend.numDataIds();h=c.tidy((function(){return e(c.backend,f)}));var n=Array.isArray(h)?h:[h];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,t,n),n}:function(){var e=c.backend.numDataIds();h=g.kernelFunc({inputs:t,attrs:i,backend:c.backend});var n=Array.isArray(h)?h:[h];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,e,n);var s=n.map((function(e){var t=e.dataId,n=e.shape,r=e.dtype;return c.makeTensorFromDataId(t,n,r)})),l=s.filter((function(e,t){return o[t]}));return f((a||[]).slice().concat(l)),s},this.scopedRun((function(){return c.state.kernelDepth++}),(function(){return c.state.kernelDepth--}),(function(){s=c.ENV.getBool(`DEBUG`)?c.profiler.profileKernel(r,t,(function(){return d()})):d()})),u&&this.addTapeNode(r,t,s,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-m,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map((function(e){return t[e].shape})),outputShapes:s.map((function(e){return e.shape}))}),Array.isArray(h)?s:s[0]},e.prototype.makeTensor=function(e,t,n,r){if(e==null)throw Error(`Values passed to engine.makeTensor() are null`);n||=`float32`,r||=this.backend;var i=e;n===`string`&&we(e[0])&&(i=e.map((function(e){return Le(e)})));var a=r.write(i,t,n),o=new $e(t,n,a,this.nextTensorId());if(this.incRef(o,r),n===`string`){var s=this.state.tensorInfo.get(a),c=Ce(i);this.state.numBytes+=c-s.bytes,s.bytes=c}return o},e.prototype.makeTensorFromDataId=function(e,t,n,r){var i=new $e(t,n||=`float32`,e,this.nextTensorId());return this.incRef(i,r),i},e.prototype.makeVariable=function(e,t,n,r){t===void 0&&(t=!0),n||=this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.asType(r));var i=new at(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw Error(`Variable with name `+i.name+` was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i},e.prototype.incRef=function(e,t){var n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype===`string`&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;var r=0;e.dtype!==`complex64`&&e.dtype!==`string`&&(r=e.size*Se(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof at||this.track(e)},e.prototype.disposeTensor=function(e){if(this.state.tensorInfo.has(e.dataId)){this.state.numTensors--,e.dtype===`string`&&this.state.numStringTensors--;var t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?(e.dtype!==`complex64`&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}},e.prototype.disposeVariables=function(){for(var e in this.state.registeredVariables){var t=this.state.registeredVariables[e];this.disposeVariable(t)}},e.prototype.disposeVariable=function(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons??=[],e.reasons.push(`Memory usage by string tensors is approximate (2 bytes per character)`)),e},e.prototype.profile=function(e){return w(this,void 0,void 0,(function(){var t,n;return T(this,(function(r){return this.state.profiling=!0,t=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(e){return e.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},e.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},e.prototype.addTapeNode=function(e,t,n,r,i){var a=this,o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},s=N(e);s!=null&&(r=s.gradFunc),r!=null&&(o.gradient=function(e){return e=e.map((function(e,t){if(e==null){var r=n[t],i=Pe(r.size,r.dtype);return a.makeTensor(i,r.shape,r.dtype)}return e})),r(e.length>1?e:e[0],i)}),this.state.activeTape.push(o)},e.prototype.keep=function(e){return e.kept=!0,e},e.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},e.prototype.endTape=function(){this.state.gradientDepth--},e.prototype.startScope=function(e){var t={track:[],name:`unnamed scope`,id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t},e.prototype.endScope=function(e){for(var t=this,n=dt(e),r=new Set(n.map((function(e){return e.id}))),i=0;i<this.state.activeScope.track.length;i++){var a=this.state.activeScope.track[i];a.kept||r.has(a.id)||a.dispose()}var o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(e){e.kept||e.scopeId!==o.id||t.track(e)}))},e.prototype.gradients=function(e,t,n,r){var i=this;if(r===void 0&&(r=!1),I(t.length>0,(function(){return`gradients() received an empty list of xs.`})),n!=null&&n.dtype!==`float32`)throw Error(`dy must have 'float32' dtype, but has '`+n.dtype+`'`);var a=this.scopedRun((function(){return i.startTape()}),(function(){return i.endTape()}),(function(){return i.tidy(`forward`,e)}));I(a instanceof $e,(function(){return`The result y returned by f() must be a tensor.`}));var o=function(e,t,n){for(var r={},i={},a=0;a<t.length;a++)r[t[a].id]=!0;for(a=0;a<e.length;a++){var o=(m=e[a]).inputs;for(var s in o){for(var c=o[s],l=!1,u=0;u<t.length;u++)if(r[c.id]){m.outputs.forEach((function(e){return r[e.id]=!0})),l=!0,i[m.id]=!0;break}if(l)break}}var d={};d[n.id]=!0;var f={};for(a=e.length-1;a>=0;a--)for(o=(m=e[a]).inputs,u=0;u<m.outputs.length;u++)if(d[m.outputs[u].id]){for(var s in o)d[o[s].id]=!0,f[m.id]=!0;break}var p=[];for(a=0;a<e.length;a++){var m;if(i[(m=e[a]).id]&&f[m.id]){var h={};for(var s in m.inputs){var g=m.inputs[s];r[g.id]&&(h[s]=g)}var _=Object.assign({},m);_.inputs=h,_.outputs=m.outputs,p.push(_)}}return p}(this.state.activeTape,t,a);if(!r&&o.length===0&&t.length>0)throw Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.`);return this.tidy(`backward`,(function(){var e,r,s={};s[a.id]=n??(e=a.shape,r=Ne(R(e),`float32`),V.makeTensor(r,e,`float32`)),function(e,t,n){for(var r=function(r){var i=t[r],a=[];if(i.outputs.forEach((function(t){var n=e[t.id];n==null?a.push(null):a.push(n)})),i.gradient==null)throw Error(`Cannot compute gradient: gradient function not found for `+i.kernelName+`.`);var o=i.gradient(a),s=function(t){if(!(t in o))throw Error(`Cannot backprop through input `+t+`. Available gradients found: `+Object.keys(o)+`.`);var r=n((function(){return o[t]()}));if(r.dtype!==`float32`)throw Error(`Error in gradient for op `+i.kernelName+`. The gradient of input `+t+` must have 'float32' dtype, but has '`+r.dtype+`'`);var a=i.inputs[t];if(!z(r.shape,a.shape))throw Error(`Error in gradient for op `+i.kernelName+`. The gradient of input '`+t+`' has shape '`+r.shape+`', which does not match the shape of the input '`+a.shape+`'`);if(e[a.id]==null)e[a.id]=r;else{var s=e[a.id];e[a.id]=s.add(r),s.dispose()}};for(var c in i.inputs)s(c)},i=t.length-1;i>=0;i--)r(i)}(s,o,(function(e){return i.tidy(e)}));var c=t.map((function(e){return s[e.id]}));return i.state.gradientDepth===0&&(i.state.activeTape.forEach((function(e){for(var t=0,n=e.saved;t<n.length;t++)n[t].dispose()})),i.state.activeTape=null),{value:a,grads:c}}))},e.prototype.customGrad=function(e){var t=this;return I(Oe(e),(function(){return`The f passed in customGrad(f) must be a function.`})),function(){for(var n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];I(r.every((function(e){return e instanceof $e})),(function(){return`The args passed in customGrad(f)(x1, x2,...) must all be tensors`}));var a={};return r.forEach((function(e,t){a[t]=e})),t.runKernelFunc((function(t,i){return I((n=e.apply(void 0,r.concat([i]))).value instanceof $e,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),I(Oe(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),a,(function(e,t){var i=n.gradFunc(e,t),a=Array.isArray(i)?i:[i];I(a.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),I(a.every((function(e){return e instanceof $e})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var o={};return a.forEach((function(e,t){o[t]=function(){return e}})),o}))}},e.prototype.readSync=function(e){return this.state.tensorInfo.get(e).backend.readSync(e)},e.prototype.read=function(e){return this.state.tensorInfo.get(e).backend.read(e)},e.prototype.time=function(e){return w(this,void 0,void 0,(function(){var t,n;return T(this,(function(r){switch(r.label){case 0:return t=Fe(),[4,this.backend.time(e)];case 1:return(n=r.sent()).wallMs=Fe()-t,[2,n]}}))}))},e.prototype.track=function(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e},Object.defineProperty(e.prototype,`registeredVariables`,{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),e.prototype.reset=function(){for(var e in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new pt,this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},e.nextTensorId=0,e.nextVariableId=0,e}(),V=function(){var e=function(){if(ft==null){var e=void 0;if(typeof window<`u`)e=window;else if(typeof global<`u`)e=global;else if(typeof process<`u`)e=process;else{if(typeof self>`u`)throw Error(`Could not find a global object`);e=self}ft=e}return ft}();return e._tfengine??=new mt(new E(e)),function(e){k=e}(e._tfengine.ENV),Ze=function(){return e._tfengine},e._tfengine}();function ht(){return typeof window<`u`&&window.document!=null||typeof WorkerGlobalScope<`u`}var gt=O();gt.registerFlag(`DEBUG`,(function(){return!1}),(function(e){e&&console.warn(`Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.`)})),gt.registerFlag(`IS_BROWSER`,(function(){return ht()})),gt.registerFlag(`IS_NODE`,(function(){return typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0})),gt.registerFlag(`IS_CHROME`,(function(){return typeof navigator<`u`&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),gt.registerFlag(`PROD`,(function(){return!1})),gt.registerFlag(`TENSORLIKE_CHECK_SHAPE_CONSISTENCY`,(function(){return gt.getBool(`DEBUG`)})),gt.registerFlag(`DEPRECATION_WARNINGS_ENABLED`,(function(){return!0})),gt.registerFlag(`IS_TEST`,(function(){return!1}));var _t,vt,yt,bt={},xt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function St(e,t){bt[e]=t}function Ct(e){e in bt||(bt[e]=function(e){if(e!==1&&e!==2)throw Error(`Cannot get WebGL rendering context, WebGL is disabled.`);var t=function(e){if(typeof OffscreenCanvas<`u`&&e===2)return new OffscreenCanvas(300,150);if(typeof document<`u`)return document.createElement(`canvas`);throw Error(`Cannot create a canvas in this context`)}(e);return t.addEventListener(`webglcontextlost`,(function(t){t.preventDefault(),delete bt[e]}),!1),e===1?t.getContext(`webgl`,xt)||t.getContext(`experimental-webgl`,xt):t.getContext(`webgl2`,xt)}(e));var t=bt[e];return t.isContextLost()?(delete bt[e],Ct(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),bt[e])}function wt(e,t){return[t,e]}function Tt(e){var t=R(e);return ue(Math.ceil(t/4))}function Et(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Dt(e,t){var n,r,i,a,o,s,c,l,u,d=e;return O().getNumber(`WEBGL_VERSION`)===2?(n=d.R32F,r=d.R16F,i=d.RGBA16F,a=d.RGBA32F,o=d.RED,s=4,c=1,l=d.HALF_FLOAT,u=d.FLOAT):(n=e.RGBA,r=e.RGBA,i=e.RGBA,a=d.RGBA,o=e.RGBA,s=4,c=4,l=t==null?null:t.HALF_FLOAT_OES,u=e.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:a,textureFormatFloat:o,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:u}}function H(e,t,n){var r=n();return t&&function(e){var t=e.getError();if(t!==e.NO_ERROR)throw Error(`WebGL Error: `+jt(e,t))}(e),r}(function(e){e[e.DENSE=0]=`DENSE`,e[e.SHARED_BATCH=1]=`SHARED_BATCH`})(_t||={}),function(e){e[e.RENDER=0]=`RENDER`,e[e.UPLOAD=1]=`UPLOAD`,e[e.PIXELS=2]=`PIXELS`,e[e.DOWNLOAD=3]=`DOWNLOAD`}(vt||={}),function(e){e[e.UNPACKED_FLOAT16=0]=`UNPACKED_FLOAT16`,e[e.UNPACKED_FLOAT32=1]=`UNPACKED_FLOAT32`,e[e.PACKED_4X1_UNSIGNED_BYTE=2]=`PACKED_4X1_UNSIGNED_BYTE`,e[e.PACKED_2X2_FLOAT32=3]=`PACKED_2X2_FLOAT32`,e[e.PACKED_2X2_FLOAT16=4]=`PACKED_2X2_FLOAT16`}(yt||={});var Ot=5.96e-8,kt=65504;function At(e){return!!(O().getBool(`WEBGL_RENDER_FLOAT32_ENABLED`)||e===0||Ot<Math.abs(e)&&Math.abs(e)<kt)}function jt(e,t){switch(t){case e.NO_ERROR:return`NO_ERROR`;case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`Unknown error code `+t}}function Mt(e,t,n){return tn(e,t,(function(){return e.getExtension(n)}),`Extension "`+n+`" not supported on this browser.`)}function Nt(e,t,n){var r=tn(e,t,(function(){return e.createShader(e.VERTEX_SHADER)}),`Unable to create vertex WebGLShader.`);if(H(e,t,(function(){return e.shaderSource(r,n)})),H(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(r)),Error(`Failed to compile vertex shader.`);return r}function Pt(e,t,n){var r=tn(e,t,(function(){return e.createShader(e.FRAGMENT_SHADER)}),`Unable to create fragment WebGLShader.`);if(H(e,t,(function(){return e.shaderSource(r,n)})),H(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw function(e,t){var n=Lt.exec(t);if(n==null)return console.log(`Couldn't parse line number in error: `+t),void console.log(e);for(var r=+n[1],i=e.split(`
|
|
6
|
+
`),a=i.length.toString().length+2,o=i.map((function(e,t){return de((t+1).toString(),a)+e})),s=0,c=0;c<o.length;c++)s=Math.max(o[c].length,s);var l=o.slice(0,r-1),u=o.slice(r-1,r),d=o.slice(r);console.log(l.join(`
|
|
7
7
|
`)),console.log(t.split(`
|
|
8
|
-
`)[0]),console.log(`%c `+
|
|
9
|
-
`))}(n,e.getShaderInfoLog(r)),Error(`Failed to compile fragment shader.`);return r}var Ct,wt,Tt=/ERROR: [0-9]+:([0-9]+):/g;function Et(e,t){return Ut(e,t,(function(){return e.createProgram()}),`Unable to create WebGLProgram.`)}function Dt(e,t,n){if(B(e,t,(function(){return e.linkProgram(n)})),!1===e.getProgramParameter(n,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(n)),Error(`Failed to link vertex and fragment shaders.`)}function Ot(e,t,n){if(B(e,t,(function(){return e.validateProgram(n)})),!1===e.getProgramParameter(n,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(n)),Error(`Shader program validation failed.`)}function kt(e,t,n){var r=Ut(e,t,(function(){return e.createBuffer()}),`Unable to create WebGLBuffer`);return B(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),B(e,t,(function(){return e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function At(e,t,n){var r=Ut(e,t,(function(){return e.createBuffer()}),`Unable to create WebGLBuffer`);return B(e,t,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)})),B(e,t,(function(){return e.bufferData(e.ELEMENT_ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function jt(e,t){return Ut(e,t,(function(){return e.createTexture()}),`Unable to create WebGLTexture.`)}function Mt(e,t){var n=m().getNumber(`WEBGL_MAX_TEXTURE_SIZE`);if(e<=0||t<=0){var r=`[`+e+`x`+t+`]`;throw Error(`Requested texture size `+r+` is invalid.`)}if(e>n||t>n)throw r=`[`+e+`x`+t+`]`,Error(`Requested texture size `+r+` greater than WebGL maximum on this browser / GPU `+(`[`+n+`x`+n+`]`)+`.`)}function Nt(e,t){return Ut(e,t,(function(){return e.createFramebuffer()}),`Unable to create WebGLFramebuffer.`)}function Pt(e,t,n,r,i,a,o,s){var c=e.getAttribLocation(n,r);return c!==-1&&(B(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,i)})),B(e,t,(function(){return e.vertexAttribPointer(c,a,e.FLOAT,!1,o,s)})),B(e,t,(function(){return e.enableVertexAttribArray(c)})),!0)}function Ft(e,t,n,r){Wt(e,r),B(e,t,(function(){return e.activeTexture(e.TEXTURE0+r)})),B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)}))}function It(e,t,n,r){return Ut(e,t,(function(){return e.getUniformLocation(n,r)}),`uniform "`+r+`" not present in program.`)}function Lt(e,t,n){return e.getUniformLocation(t,n)}function Rt(e,t,n,r,i,a){B(e,t,(function(){return Ft(e,t,r,a)})),B(e,t,(function(){return e.uniform1i(i,a)}))}function zt(e,t,n,r){B(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)})),B(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}))}function Bt(e,t,n){B(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)})),B(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)}))}function Vt(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw Error(`Error binding framebuffer: `+Ht(e,t))}function Ht(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return`FRAMEBUFFER_INCOMPLETE_ATTACHMENT`;case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return`FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT`;case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return`FRAMEBUFFER_INCOMPLETE_DIMENSIONS`;case e.FRAMEBUFFER_UNSUPPORTED:return`FRAMEBUFFER_UNSUPPORTED`;default:return`unknown error `+t}}function Ut(e,t,n,r){var i=B(e,t,(function(){return n()}));if(i==null)throw Error(r);return i}function Wt(e,t){var n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw Error(`textureUnit must be in `+(`[gl.TEXTURE0, gl.TEXTURE`+n+`]`)+`.`)}function Gt(e,t){return t===void 0&&(t=2),M(e.slice(0,e.length-t))}function Kt(e){if(e.length===0)throw Error(`Cannot get rows and columns of an empty shape array.`);return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function qt(e){var t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Gt(e)].concat(Kt(e))),t}function Jt(e,t){var n;t===void 0&&(t=!1);var r=m().getNumber(`WEBGL_MAX_TEXTURE_SIZE`);t&&(r*=2,(e=e.map((function(t,n){return n>=e.length-2?E(e[n]):e[n]}))).length===1&&(e=[2,e[0]])),e.length!==2&&(e=re(e).newShape);var i=M(e);if(e.length<=1&&i<=r)return[1,i];if(e.length===2&&e[0]<=r&&e[1]<=r)return e;if(e.length===3&&e[0]*e[1]<=r&&e[2]<=r)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=r&&e[1]*e[2]<=r)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=r&&e[3]<=r)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=r&&e[1]*e[2]*e[3]<=r)return[e[0],e[1]*e[2]*e[3]];if(t){var a=Gt(e),o=2,s=2;return e.length&&(o=(n=Kt(e))[0],s=n[1]),I(i=o/2*a*(s/2)).map((function(e){return 2*e}))}return I(i)}function Yt(e){return e%2==0}function Xt(e,t){if(N(e=e.slice(-2),t=t.slice(-2))||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){var n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r||Yt(n)&&Yt(r)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Yt(e[0])&&Yt(t[0])}function Zt(e){if(Ct==null){var t=dt(e);Ct=t.getParameter(t.MAX_TEXTURE_SIZE)}return Ct}function Qt(e){if(wt==null){var t=dt(e);wt=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,wt)}function $t(e){if(e===0)return 0;var t=dt(e);return en(t,`EXT_disjoint_timer_query_webgl2`)&&e===2?2:en(t,`EXT_disjoint_timer_query`)?1:0}function en(e,t){return e.getExtension(t)!=null}function tn(e){try{if(dt(e)!=null)return!0}catch{return!1}return!1}function nn(e){if(e===0)return!1;var t=dt(e);if(e===1){if(!en(t,`OES_texture_float`))return!1}else if(!en(t,`EXT_color_buffer_float`))return!1;return an(t)}function rn(e){if(e===0)return!1;var t=dt(e);return e===1?!!en(t,`OES_texture_float`)&&!!en(t,`WEBGL_color_buffer_float`)&&an(t):en(t,`EXT_color_buffer_float`)?an(t):en(t,`EXT_color_buffer_half_float`)?function(e,t){var n=ht(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);var a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(i),a}(t,t.getExtension(`EXT_color_buffer_half_float`)):!1}function an(e){var t=ht(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);var i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),i}function on(e){return e===2&&dt(e).fenceSync!=null}var sn=Object.freeze({callAndCheck:B,canBeRepresented:vt,getWebGLErrorMessage:yt,getExtensionOrThrow:bt,createVertexShader:xt,createFragmentShader:St,createProgram:Et,linkProgram:Dt,validateProgram:Ot,createStaticVertexBuffer:kt,createStaticIndexBuffer:At,getNumChannels:function(){return m().getNumber(`WEBGL_VERSION`)===2?1:4},createTexture:jt,validateTextureSize:Mt,createFramebuffer:Nt,bindVertexBufferToProgramAttribute:Pt,bindTextureUnit:Ft,unbindTextureUnit:function(e,t,n){Wt(e,n),B(e,t,(function(){return e.activeTexture(e.TEXTURE0+n)})),B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:It,getProgramUniformLocation:Lt,bindTextureToProgramUniformSampler:Rt,bindCanvasToFramebuffer:function(e,t){B(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),B(e,t,(function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)})),B(e,t,(function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)}))},bindColorTextureToFramebuffer:zt,unbindColorTextureFromFramebuffer:Bt,validateFramebuffer:Vt,getFramebufferErrorMessage:Ht,getBatchDim:Gt,getRowsCols:Kt,getShapeAs3D:qt,getTextureShapeFromLogicalShape:Jt,isReshapeFree:Xt,getWebGLMaxTextureSize:Zt,resetMaxTextureSize:function(){Ct=null},resetMaxTexturesInShader:function(){wt=null},getMaxTexturesInShader:Qt,getWebGLDisjointQueryTimerVersion:$t,hasExtension:en,isWebGLVersionEnabled:tn,isCapableOfRenderingToFloatTexture:nn,isDownloadFloatTextureEnabled:rn,isWebGLFenceEnabled:on}),V=m();function cn(e){m().getBool(`DEPRECATION_WARNINGS_ENABLED`)&&console.warn(e+` You can disable deprecation warnings with tf.disableDeprecationWarnings().`)}function H(e,t){return z.tidy(e,t)}function ln(e){$e(e).forEach((function(e){return e.dispose()}))}function un(e){return z.keep(e)}function dn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];m().getBool(`IS_TEST`)||console.warn.apply(console,e)}function fn(e,t){var n=e;if(le(e))return t===`string`?[]:[e.length];if(!Array.isArray(e))return[];for(var r=[];Array.isArray(n)||le(n)&&t!==`string`;)r.push(n.length),n=n[0];return Array.isArray(e)&&m().getBool(`TENSORLIKE_CHECK_SHAPE_CONSISTENCY`)&&function e(t,n,r){if(r||=[],!Array.isArray(t)&&!le(t))return void O(n.length===0,(function(){return`Element arr[`+r.join(`][`)+`] is a primitive, but should be an array/TypedArray of `+n[0]+` elements`}));O(n.length>0,(function(){return`Element arr[`+r.join(`][`)+`] should be a primitive, but is an array of `+t.length+` elements`})),O(t.length===n[0],(function(){return`Element arr[`+r.join(`][`)+`] should have `+n[0]+` elements, but has `+t.length+` elements`}));for(var i=n.slice(1),a=0;a<t.length;++a)e(t[a],i,r.concat(a))}(e,r,[]),r}function pn(e,t,n,r){if(e!=null&&(e!==`numeric`&&e!==t||e===`numeric`&&t===`string`))throw Error(`Argument '`+n+`' passed to '`+r+`' must be `+e+` tensor, but got `+t+` tensor`)}function U(e,t,n,r){if(r===void 0&&(r=`numeric`),e instanceof Ve)return pn(r,e.dtype,t,n),e;var i=he(e);if(i!==`string`&&[`bool`,`int32`,`float32`].indexOf(r)>=0&&(i=r),pn(r,i,t,n),e==null||!le(e)&&!Array.isArray(e)&&typeof e!=`number`&&typeof e!=`boolean`&&typeof e!=`string`){var a=e==null?`null`:e.constructor.name;throw Error(`Argument '`+t+`' passed to '`+n+`' must be a Tensor or TensorLike, but got '`+a+`'`)}var o=fn(e,i);le(e)||Array.isArray(e)||(e=[e]);var s=i===`string`?j(e,[],!0):ye(e,i,m().getBool(`DEBUG`));return z.makeTensor(s,o,i)}function mn(e,t,n,r){if(r===void 0&&(r=`numeric`),!Array.isArray(e))throw Error(`Argument `+t+` passed to `+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map((function(e,r){return U(e,t+`[`+r+`]`,n)}),r)}function hn(e,t){for(var n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function gn(e,t,n){for(var r=e.length+t.length,i=[],a=0,o=0,s=0;s<r;s++)n.indexOf(s)===-1?i.push(e[a++]):i.push(t[o++]);return i}function _n(e,t){for(var n=[],r=e.length,i=0;i<r;i++)t.indexOf(i)===-1&&n.push(e[i]);return[n,t.map((function(t){return e[t]}))]}function vn(e,t){return gn(e,t.map((function(e){return 1})),t)}function yn(e,t,n){O(hn(t,n),(function(){return e+` supports only inner-most axes for now. Got axes `+t+` and rank-`+n+` input.`}))}function bn(e,t){if(hn(e,t))return null;for(var n=[],r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach((function(e){return n.push(e)})),n}function xn(e){return e.map((function(e,t){return[t,e]})).sort((function(e,t){return e[1]-t[1]})).map((function(e){return e[0]}))}function Sn(e,t){for(var n=[],r=t-e;r<t;++r)n.push(r);return n}function Cn(e,t){var n=e[0].length;e.forEach((function(e,t){O(e.length===n,(function(){return`Error in concat`+n+`D: rank of tensors[`+t+`] must be the same as the rank of the rest (`+n+`)`}))})),O(t>=0&&t<n,(function(){return`Error in concat`+n+`D: axis must be between 0 and `+(n-1)+`.`}));var r=e[0];e.forEach((function(e,i){for(var a=0;a<n;a++)O(a===t||e[a]===r[a],(function(){return`Error in concat`+n+`D: Shape of tensors[`+i+`] (`+e+`) does not match the shape of the rest (`+r+`) along the non-concatenated axis `+i+`.`}))}))}function wn(e,t){for(var n=e[0].slice(),r=1;r<e.length;r++)n[t]+=e[r][t];return n}function W(e){var t=Object.keys(e);if(t.length!==1)throw Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with `+t.length+` keys.`);var n=t[0],r=e[n];n.endsWith(`_`)&&(n=n.substring(0,n.length-1));var i=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];z.startScope(n);try{var i=r.apply(void 0,e);return i instanceof Promise&&console.error(`Cannot return a Promise inside of tidy.`),z.endScope(i),i}catch(e){throw z.endScope(null),e}};return Object.defineProperty(i,`name`,{value:n,configurable:!0}),i}V.registerFlag(`HAS_WEBGL`,(function(){return V.getNumber(`WEBGL_VERSION`)>0})),V.registerFlag(`WEBGL_VERSION`,(function(){return tn(2)?2:tn(1)?1:0})),V.registerFlag(`WEBGL_BUFFER_SUPPORTED`,(function(){return V.get(`WEBGL_VERSION`)===2})),V.registerFlag(`WEBGL_CPU_FORWARD`,(function(){return!0})),V.registerFlag(`WEBGL_FORCE_F16_TEXTURES`,(function(){return!1})),V.registerFlag(`WEBGL_PACK`,(function(){return V.getBool(`HAS_WEBGL`)})),V.registerFlag(`WEBGL_PACK_NORMALIZATION`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_CLIP`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_DEPTHWISECONV`,(function(){return!1})),V.registerFlag(`WEBGL_PACK_BINARY_OPERATIONS`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_UNARY_OPERATIONS`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_ARRAY_OPERATIONS`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_IMAGE_OPERATIONS`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_PACK_REDUCE`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_LAZILY_UNPACK`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_CONV_IM2COL`,(function(){return V.getBool(`WEBGL_PACK`)})),V.registerFlag(`WEBGL_MAX_TEXTURE_SIZE`,(function(){return Zt(V.getNumber(`WEBGL_VERSION`))})),V.registerFlag(`WEBGL_MAX_TEXTURES_IN_SHADER`,(function(){return Qt(V.getNumber(`WEBGL_VERSION`))})),V.registerFlag(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`,(function(){var e=V.getNumber(`WEBGL_VERSION`);return e===0?0:$t(e)})),V.registerFlag(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`,(function(){return V.getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e})),V.registerFlag(`WEBGL_RENDER_FLOAT32_CAPABLE`,(function(){return nn(V.getNumber(`WEBGL_VERSION`))})),V.registerFlag(`WEBGL_RENDER_FLOAT32_ENABLED`,(function(){return!V.getBool(`WEBGL_FORCE_F16_TEXTURES`)&&V.getBool(`WEBGL_RENDER_FLOAT32_CAPABLE`)})),V.registerFlag(`WEBGL_DOWNLOAD_FLOAT_ENABLED`,(function(){return rn(V.getNumber(`WEBGL_VERSION`))})),V.registerFlag(`WEBGL_FENCE_API_ENABLED`,(function(){return on(V.getNumber(`WEBGL_VERSION`))})),V.registerFlag(`WEBGL_SIZE_UPLOAD_UNIFORM`,(function(){return V.getBool(`WEBGL_RENDER_FLOAT32_ENABLED`)?4:0})),Be=cn;var Tn=W({complex_:function(e,t){var n=U(e,`real`,`complex`),r=U(t,`imag`,`complex`);return k(n.shape,r.shape,`real and imag shapes, `+n.shape+` and `+r.shape+`, must match in call to tf.complex().`),z.runKernelFunc((function(e){return e.complex(n,r)}),{$real:n,$imag:r})}}),En=W({real_:function(e){var t=U(e,`input`,`real`);return z.runKernelFunc((function(e){return e.real(t)}),{$input:t})}}),Dn=W({imag_:function(e){var t=U(e,`input`,`imag`);return z.runKernelFunc((function(e){return e.imag(t)}),{$input:t})}});function On(e,t,n){return kn(e,t,fn(e,n),n)}function kn(e,t,n,r){if(r??=he(e),r===`complex64`)throw Error(`Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).`);if(!le(e)&&!Array.isArray(e)&&typeof e!=`number`&&typeof e!=`boolean`&&typeof e!=`string`)throw Error(`values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray`);if(t!=null){we(t);var i=M(t),a=M(n);O(i===a,(function(){return`Based on the provided shape, [`+t+`], the tensor should have `+i+` values but has `+a}));for(var o=0;o<n.length;++o){var s=n[o],c=o!==n.length-1||s!==M(t.slice(o));O(n[o]===t[o]||!c,(function(){return`Error creating a new Tensor. Inferred shape (`+n+`) does not match the provided shape (`+t+`). `}))}}return le(e)||Array.isArray(e)||(e=[e]),t||=n,e=r===`string`?j(e,[],!0):ye(e,r,m().getBool(`DEBUG`)),z.makeTensor(e,t,r)}function G(e,t){if((le(e)&&t!==`string`||Array.isArray(e))&&t!==`complex64`)throw Error(`Error creating a new Scalar: value must be a primitive (number|boolean|string)`);if(t===`string`&&le(e)&&!(e instanceof Uint8Array))throw Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return kn(e,[],[],t)}function An(e,t){A(e);var n=fn(e,t);if(n.length!==1)throw Error(`tensor1d() requires values to be a flat/TypedArray`);return kn(e,null,n,t)}function jn(e,t,n){if(A(e),t!=null&&t.length!==2)throw Error(`tensor2d() requires shape to have two numbers`);var r=fn(e,n);if(r.length!==2&&r.length!==1)throw Error(`tensor2d() requires values to be number[][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return kn(e,t,r,n)}function Mn(e,t,n){if(A(e),t!=null&&t.length!==3)throw Error(`tensor3d() requires shape to have three numbers`);var r=fn(e,n);if(r.length!==3&&r.length!==1)throw Error(`tensor3d() requires values to be number[][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor3d() requires shape to be provided when `values` are a flat array");return kn(e,t,r,n)}function Nn(e,t,n){if(A(e),t!=null&&t.length!==4)throw Error(`tensor4d() requires shape to have four numbers`);var r=fn(e,n);if(r.length!==4&&r.length!==1)throw Error(`tensor4d() requires values to be number[][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor4d() requires shape to be provided when `values` are a flat array");return kn(e,t,r,n)}function Pn(e,t,n){if(A(e),t!=null&&t.length!==5)throw Error(`tensor5d() requires shape to have five numbers`);var r=fn(e,n);if(r.length!==5&&r.length!==1)throw Error(`tensor5d() requires values to be number[][][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor5d() requires shape to be provided when `values` are a flat array");return kn(e,t,r,n)}function Fn(e,t,n){if(A(e),t!=null&&t.length!==6)throw Error(`tensor6d() requires shape to have six numbers`);var r=fn(e,n);if(r.length!==6&&r.length!==1)throw Error(`tensor6d() requires values to be number[][][][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor6d() requires shape to be provided when `values` are a flat array");return kn(e,t||=r,r,n)}function In(e,t,n,r){return t===void 0&&(t=!0),z.makeVariable(e,t,n,r)}function Ln(e,t){if(t===void 0&&(t=`float32`),t===`complex64`)return Tn(Ln(e,`float32`),Rn(e,`float32`));var n=xe(M(e),t);return z.makeTensor(n,e,t)}function Rn(e,t){if(t===void 0&&(t=`float32`),t===`complex64`)return Tn(Rn(e,`float32`),Rn(e,`float32`));var n=Se(M(e),t);return z.makeTensor(n,e,t)}function zn(e,t,n){return z.runKernelFunc((function(r){return r.fill(e,t,n)}),{})}function Bn(e,t,n){if(n<=0)throw Error(`The number of values should be positive.`);return z.runKernelFunc((function(r){return r.linspace(e,t,n)}),{})}function Vn(e,t,n,r){if(n===void 0&&(n=1),r===void 0&&(r=`float32`),n===0)throw Error(`Cannot have a step of zero`);if(e===t||e<t&&n<0||t<e&&n>1)return Rn([0],r);var i=Se(Math.abs(Math.ceil((t-e)/n)),r);t<e&&n===1&&(n=-1),i[0]=e;for(var a=1;a<i.length;a++)i[a]=i[a-1]+n;return An(i,r)}var Hn=W({onesLike_:function(e){var t=U(e,`x`,`onesLike`);return t.dtype===`complex64`?Tn(Hn(En(t)),Un(Dn(t))):z.runKernelFunc((function(e){return e.onesLike(t)}),{$x:t},(function(e,t){return{$x:function(){return Un(e)}}}))}}),Un=W({zerosLike_:function(e){var t=U(e,`x`,`zerosLike`);return z.runKernelFunc((function(e){return e.zerosLike(t)}),{$x:t},(function(e,t){return{$x:function(){return Un(e)}}}))}}),Wn=W({concat_:function(e,t){t===void 0&&(t=0),O(e.length>=1,(function(){return`Pass at least one tensor to concat`}));var n=mn(e,`tensors`,`concat`);n[0].dtype===`complex64`&&n.forEach((function(e){if(e.dtype!==`complex64`)throw Error(`Cannot concatenate complex64 tensors with a tensor
|
|
10
|
-
with dtype `+e.dtype+`. `)})),t=L(t,n[0].shape)[0];var r=wn(n.map((function(e){return e.shape})),t);if(M(r)===0)return On([],r);if((n=n.filter((function(e){return e.size>0}))).length===1)return n[0];var i=n.map((function(e){return e.shape}));Cn(i,t);var a=n,o={axis:t};return z.runKernelFunc((function(e){return e.concat(n,t)}),a,(function(e){return Yn(e,i.map((function(e){return e[t]})),t).map((function(e){return function(){return e}}))}),`Concat`,o)}}),Gn=W({concat1d_:function(e){return Wn(e,0)}}),Kn=W({concat2d_:function(e,t){return Wn(e,t)}}),qn=W({concat3d_:function(e,t){return Wn(e,t)}}),Jn=W({concat4d_:function(e,t){return Wn(e,t)}}),Yn=W({split_:function(e,t,n){n===void 0&&(n=0);var r,i=U(e,`x`,`split`);return n=L(n,i.shape)[0],typeof t==`number`?(O(i.shape[n]%t==0,(function(){return`Number of splits must evenly divide the axis.`})),r=Array(t).fill(i.shape[n]/t)):(O(i.shape[n]===t.reduce((function(e,t){return e+t})),(function(){return`The sum of sizes must match the size of the axis dimension.`})),r=t),z.runKernelFunc((function(e){return e.split(i,r,n)}),{$x:i},(function(e){return{$x:function(){return Wn(e,n)}}}))}});function Xn(e,t){return e(t={exports:{}},t.exports),t.exports}var Zn=Xn((function(e){(function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 23283064365386963e-26*(t>>>0)});n.next=function(){var e=2091639*n.s0+23283064365386963e-26*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(` `),n.s1=r(` `),n.s2=r(` `),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.alea=a})(0,e,!1)})),Qn=Xn((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a})(0,e,!1)})),$n=Xn((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a})(0,e,!1)})),er=Xn((function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,i=t.i;return e=r[i],n=(e^=e>>>7)^e<<24,n^=(e=r[i+1&7])^e>>>10,n^=(e=r[i+3&7])^e>>>3,n^=(e=r[i+4&7])^e<<7,e=r[i+7&7],n^=(e^=e<<13)^e<<9,r[i]=n,t.i=i+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a})(0,e,!1)})),tr=Xn((function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,i=t.X,a=t.i;return t.w=r=r+1640531527|0,n=i[a+34&127],e=i[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=i[a]=n^e,t.i=a,n+(r^r>>>16)|0},function(e,t){var n,r,i,a,o,s=[],c=128;for(t===(0|t)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=(n=s[127&a]^=r+o)==0?i+1:0);for(i>=128&&(s[127&(t&&t.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a})(0,e,!1)})),nr=Xn((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a})(0,e,!1)})),rr=Xn((function(e){(function(t,n){var r,i=this,a=256,o=6,c=`random`,l=n.pow(a,o),u=n.pow(2,52),d=2*u,f=a-1;function p(e,s,f){var p=[],v=g(function e(t,n){var r,i=[],a=typeof t;if(n&&a==`object`)for(r in t)try{i.push(e(t[r],n-1))}catch{}return i.length?i:a==`string`?t:t+`\0`}((s=s==1?{entropy:!0}:s||{}).entropy?[e,_(t)]:e??function(){try{var e;return r&&(e=r.randomBytes)?e=e(a):(e=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(e)),_(e)}catch{var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,_(t)]}}(),3),p),y=new m(p),b=function(){for(var e=y.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=y.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,g(_(y.S),t),(s.pass||f||function(e,t,r,i){return i&&(i.S&&h(i,y),e.state=function(){return h(y,{})}),r?(n[c]=e,t):e})(b,v,`global`in s?s.global:this==n,s.state)}function m(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function g(e,t){for(var n,r=e+``,i=0;i<r.length;)t[f&i]=f&(n^=19*t[f&i])+r.charCodeAt(i++);return _(t)}function _(e){return String.fromCharCode.apply(0,e)}if(n[`seed`+c]=p,g(n.random(),t),e.exports){e.exports=p;try{r=s()}catch{}}})([],Math)}));rr.alea=Zn,rr.xor128=Qn,rr.xorwow=$n,rr.xorshift7=er,rr.xor4096=tr,rr.tychei=nr;var ir=rr.alea,ar=function(){function e(e,t,n,r,i){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev),this.random=ir((i||Math.random()).toString())}return e.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var e=this.nextVal;return this.nextVal=NaN,e}for(var t,n,r=!1;!r;){var i=void 0,a=void 0,o=void 0;do o=(i=2*this.random()-1)*i+(a=2*this.random()-1)*a;while(o>=1||o===0);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return this.dtype==null||this.dtype===`float32`?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),or=function(){function e(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n,this.randu=ir((r||Math.random()).toString()),this.randn=new ar(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}return e.prototype.nextValue=function(){for(var e,t,n,r,i,a;;){do r=this.randn.nextValue(),a=1+this.c*r;while(a<=0);if(a*=a*a,t=1-.331*(e=r*r)*e,n=.5*e+this.d*(1-a+Math.log(a)),(i=this.randu())<t||Math.log(i)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=this.randu()**(1/this.alpha)),this.convertValue(a)},e.prototype.convertValue=function(e){return this.dtype===`float32`?e:Math.round(e)},e}(),sr=function(){function e(e,t,n,r){var i=this;if(e===void 0&&(e=0),t===void 0&&(t=1),this.canReturnFloat=function(){return i.dtype==null||i.dtype===`float32`},this.min=e,this.range=t-e,this.dtype=n,r??=Math.random(),typeof r==`number`&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw Error(`The difference between `+e+` - `+t+` <= 1 and dtype is not float`);this.random=ir(r)}return e.prototype.convertValue=function(e){return this.canReturnFloat()?e:Math.round(e)},e.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},e}();function K(e,t,n){return t===void 0&&(t=`float32`),t||=`float32`,we(e),new Re(e,t,n)}function cr(e,t){t===void 0&&(t=!1),console.log(e.toString(t))}var lr=W({batchToSpaceND_:function(e,t,n){var r=U(e,`x`,`batchToSpaceND`),i=t.reduce((function(e,t){return e*t}));return O(r.rank>=1+t.length,(function(){return`input rank is `+r.rank+` but should be > than blockShape.length `+t.length})),O(n.length===t.length,(function(){return`crops.length is `+n.length+` but should be equal to blockShape.length `+t.length})),O(r.shape[0]%i==0,(function(){return`input tensor batch is `+r.shape[0]+` but is not divisible by the product of the elements of blockShape `+t.join(` * `)+` === `+i})),z.runKernelFunc((function(e){return e.batchToSpaceND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}}))}}),ur=W({broadcastTo_:function(e,t){var n=U(e,`broadcastTo`,`x`),r=n.shape;if(t.some((function(e){return!(e>0)||e%1!=0})))throw Error(`broadcastTo(): Invalid broadcast shape [`+t+`].`);if(t.length<n.rank)throw Error(`broadcastTo(): shape.length=`+t.length+` < input.rank=`+n.rank+`.`);if(t.length>n.rank){for(var i=n.shape.slice();i.length<t.length;)i.unshift(1);n=n.reshape(i)}for(var a=Array.from(t),o=t.length-1;o>=0;o--)if(n.shape[o]===t[o])a[o]=1;else if(n.shape[o]!==1)throw Error(`broadcastTo(): [`+r+`] cannot be broadcast to [`+t+`].`);var s=a.map((function(e,t){return e>1?t:-1})).filter((function(e){return e>=0}));return s.length===0?n.clone():z.runKernelFunc((function(e){return e.tile(n,a)}),{input:n},(function(e){return{input:function(){return e.sum(s,!0)}}}))}}),dr=W({cast_:function(e,t){var n=U(e,`x`,`cast`);if(!se(t))throw Error(`Failed to cast to unknown dtype `+t);if(t===`string`&&n.dtype!==`string`||t!==`string`&&n.dtype===`string`)throw Error(`Only strings can be casted to strings`);var r={dtype:t};return z.runKernelFunc((function(e){return e.cast(n,t)}),{x:n},(function(e){return{x:function(){return e.clone()}}}),`Cast`,r)}}),fr=W({clone_:function(e){var t=U(e,`x`,`clone`,null);return z.runKernelFunc((function(){return z.makeTensorFromDataId(t.dataId,t.shape,t.dtype)}),{$x:t},(function(e){return{$x:function(){return e.toFloat()}}}))}}),pr=W({cumsum_:function(e,t,n,r){t===void 0&&(t=0),n===void 0&&(n=!1),r===void 0&&(r=!1);var i=U(e,`x`,`cumsum`),a=bn([t|=0],i.rank),o=i;a!=null&&(o=i.transpose(a));var s=Sn(1,i.rank)[0],c=z.runKernelFunc((function(e){return e.cumsum(o,s,n,r)}),{permutedX:o},(function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}}));return a!=null&&(c=c.transpose(a)),c}}),mr=W({depthToSpace_:function(e,t,n){n===void 0&&(n=`NHWC`);var r=U(e,`x`,`depthToSpace`),i=n===`NHWC`?r.shape[1]:r.shape[2],a=n===`NHWC`?r.shape[2]:r.shape[3],o=n===`NHWC`?r.shape[3]:r.shape[1];return O(i*t>=0,(function(){return`Negative dimension size caused by overflow when multiplying
|
|
8
|
+
`)[0]),console.log(`%c `+de(u[0],s),`border:1px solid red; background-color:#e3d2d2; color:#a61717`),console.log(d.join(`
|
|
9
|
+
`))}(n,e.getShaderInfoLog(r)),Error(`Failed to compile fragment shader.`);return r}var Ft,It,Lt=/ERROR: [0-9]+:([0-9]+):/g;function Rt(e,t){return tn(e,t,(function(){return e.createProgram()}),`Unable to create WebGLProgram.`)}function zt(e,t,n){if(H(e,t,(function(){return e.linkProgram(n)})),!1===e.getProgramParameter(n,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(n)),Error(`Failed to link vertex and fragment shaders.`)}function Bt(e,t,n){if(H(e,t,(function(){return e.validateProgram(n)})),!1===e.getProgramParameter(n,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(n)),Error(`Shader program validation failed.`)}function Vt(e,t,n){var r=tn(e,t,(function(){return e.createBuffer()}),`Unable to create WebGLBuffer`);return H(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),H(e,t,(function(){return e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function Ht(e,t,n){var r=tn(e,t,(function(){return e.createBuffer()}),`Unable to create WebGLBuffer`);return H(e,t,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)})),H(e,t,(function(){return e.bufferData(e.ELEMENT_ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function Ut(e,t){return tn(e,t,(function(){return e.createTexture()}),`Unable to create WebGLTexture.`)}function Wt(e,t){var n=O().getNumber(`WEBGL_MAX_TEXTURE_SIZE`);if(e<=0||t<=0){var r=`[`+e+`x`+t+`]`;throw Error(`Requested texture size `+r+` is invalid.`)}if(e>n||t>n)throw r=`[`+e+`x`+t+`]`,Error(`Requested texture size `+r+` greater than WebGL maximum on this browser / GPU `+(`[`+n+`x`+n+`]`)+`.`)}function Gt(e,t){return tn(e,t,(function(){return e.createFramebuffer()}),`Unable to create WebGLFramebuffer.`)}function Kt(e,t,n,r,i,a,o,s){var c=e.getAttribLocation(n,r);return c!==-1&&(H(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,i)})),H(e,t,(function(){return e.vertexAttribPointer(c,a,e.FLOAT,!1,o,s)})),H(e,t,(function(){return e.enableVertexAttribArray(c)})),!0)}function qt(e,t,n,r){nn(e,r),H(e,t,(function(){return e.activeTexture(e.TEXTURE0+r)})),H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)}))}function Jt(e,t,n,r){return tn(e,t,(function(){return e.getUniformLocation(n,r)}),`uniform "`+r+`" not present in program.`)}function Yt(e,t,n){return e.getUniformLocation(t,n)}function Xt(e,t,n,r,i,a){H(e,t,(function(){return qt(e,t,r,a)})),H(e,t,(function(){return e.uniform1i(i,a)}))}function Zt(e,t,n,r){H(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)})),H(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}))}function Qt(e,t,n){H(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)})),H(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)}))}function $t(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw Error(`Error binding framebuffer: `+en(e,t))}function en(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return`FRAMEBUFFER_INCOMPLETE_ATTACHMENT`;case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return`FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT`;case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return`FRAMEBUFFER_INCOMPLETE_DIMENSIONS`;case e.FRAMEBUFFER_UNSUPPORTED:return`FRAMEBUFFER_UNSUPPORTED`;default:return`unknown error `+t}}function tn(e,t,n,r){var i=H(e,t,(function(){return n()}));if(i==null)throw Error(r);return i}function nn(e,t){var n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw Error(`textureUnit must be in `+(`[gl.TEXTURE0, gl.TEXTURE`+n+`]`)+`.`)}function rn(e,t){return t===void 0&&(t=2),R(e.slice(0,e.length-t))}function an(e){if(e.length===0)throw Error(`Cannot get rows and columns of an empty shape array.`);return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function on(e){var t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[rn(e)].concat(an(e))),t}function sn(e,t){var n;t===void 0&&(t=!1);var r=O().getNumber(`WEBGL_MAX_TEXTURE_SIZE`);t&&(r*=2,(e=e.map((function(t,n){return n>=e.length-2?ie(e[n]):e[n]}))).length===1&&(e=[2,e[0]])),e.length!==2&&(e=he(e).newShape);var i=R(e);if(e.length<=1&&i<=r)return[1,i];if(e.length===2&&e[0]<=r&&e[1]<=r)return e;if(e.length===3&&e[0]*e[1]<=r&&e[2]<=r)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=r&&e[1]*e[2]<=r)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=r&&e[3]<=r)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=r&&e[1]*e[2]*e[3]<=r)return[e[0],e[1]*e[2]*e[3]];if(t){var a=rn(e),o=2,s=2;return e.length&&(o=(n=an(e))[0],s=n[1]),ue(i=o/2*a*(s/2)).map((function(e){return 2*e}))}return ue(i)}function cn(e){return e%2==0}function ln(e,t){if(z(e=e.slice(-2),t=t.slice(-2))||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){var n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r||cn(n)&&cn(r)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&cn(e[0])&&cn(t[0])}function un(e){if(Ft==null){var t=Ct(e);Ft=t.getParameter(t.MAX_TEXTURE_SIZE)}return Ft}function dn(e){if(It==null){var t=Ct(e);It=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,It)}function fn(e){if(e===0)return 0;var t=Ct(e);return pn(t,`EXT_disjoint_timer_query_webgl2`)&&e===2?2:pn(t,`EXT_disjoint_timer_query`)?1:0}function pn(e,t){return e.getExtension(t)!=null}function mn(e){try{if(Ct(e)!=null)return!0}catch{return!1}return!1}function hn(e){if(e===0)return!1;var t=Ct(e);if(e===1){if(!pn(t,`OES_texture_float`))return!1}else if(!pn(t,`EXT_color_buffer_float`))return!1;return _n(t)}function gn(e){if(e===0)return!1;var t=Ct(e);return e===1?!!pn(t,`OES_texture_float`)&&!!pn(t,`WEBGL_color_buffer_float`)&&_n(t):pn(t,`EXT_color_buffer_float`)?_n(t):pn(t,`EXT_color_buffer_half_float`)?function(e,t){var n=Dt(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);var a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(i),a}(t,t.getExtension(`EXT_color_buffer_half_float`)):!1}function _n(e){var t=Dt(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);var i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),i}function vn(e){return e===2&&Ct(e).fenceSync!=null}var yn=Object.freeze({callAndCheck:H,canBeRepresented:At,getWebGLErrorMessage:jt,getExtensionOrThrow:Mt,createVertexShader:Nt,createFragmentShader:Pt,createProgram:Rt,linkProgram:zt,validateProgram:Bt,createStaticVertexBuffer:Vt,createStaticIndexBuffer:Ht,getNumChannels:function(){return O().getNumber(`WEBGL_VERSION`)===2?1:4},createTexture:Ut,validateTextureSize:Wt,createFramebuffer:Gt,bindVertexBufferToProgramAttribute:Kt,bindTextureUnit:qt,unbindTextureUnit:function(e,t,n){nn(e,n),H(e,t,(function(){return e.activeTexture(e.TEXTURE0+n)})),H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:Jt,getProgramUniformLocation:Yt,bindTextureToProgramUniformSampler:Xt,bindCanvasToFramebuffer:function(e,t){H(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),H(e,t,(function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)})),H(e,t,(function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)}))},bindColorTextureToFramebuffer:Zt,unbindColorTextureFromFramebuffer:Qt,validateFramebuffer:$t,getFramebufferErrorMessage:en,getBatchDim:rn,getRowsCols:an,getShapeAs3D:on,getTextureShapeFromLogicalShape:sn,isReshapeFree:ln,getWebGLMaxTextureSize:un,resetMaxTextureSize:function(){Ft=null},resetMaxTexturesInShader:function(){It=null},getMaxTexturesInShader:dn,getWebGLDisjointQueryTimerVersion:fn,hasExtension:pn,isWebGLVersionEnabled:mn,isCapableOfRenderingToFloatTexture:hn,isDownloadFloatTextureEnabled:gn,isWebGLFenceEnabled:vn}),U=O();function bn(e){O().getBool(`DEPRECATION_WARNINGS_ENABLED`)&&console.warn(e+` You can disable deprecation warnings with tf.disableDeprecationWarnings().`)}function W(e,t){return V.tidy(e,t)}function xn(e){dt(e).forEach((function(e){return e.dispose()}))}function Sn(e){return V.keep(e)}function Cn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];O().getBool(`IS_TEST`)||console.warn.apply(console,e)}function wn(e,t){var n=e;if(xe(e))return t===`string`?[]:[e.length];if(!Array.isArray(e))return[];for(var r=[];Array.isArray(n)||xe(n)&&t!==`string`;)r.push(n.length),n=n[0];return Array.isArray(e)&&O().getBool(`TENSORLIKE_CHECK_SHAPE_CONSISTENCY`)&&function e(t,n,r){if(r||=[],!Array.isArray(t)&&!xe(t))return void I(n.length===0,(function(){return`Element arr[`+r.join(`][`)+`] is a primitive, but should be an array/TypedArray of `+n[0]+` elements`}));I(n.length>0,(function(){return`Element arr[`+r.join(`][`)+`] should be a primitive, but is an array of `+t.length+` elements`})),I(t.length===n[0],(function(){return`Element arr[`+r.join(`][`)+`] should have `+n[0]+` elements, but has `+t.length+` elements`}));for(var i=n.slice(1),a=0;a<t.length;++a)e(t[a],i,r.concat(a))}(e,r,[]),r}function Tn(e,t,n,r){if(e!=null&&(e!==`numeric`&&e!==t||e===`numeric`&&t===`string`))throw Error(`Argument '`+n+`' passed to '`+r+`' must be `+e+` tensor, but got `+t+` tensor`)}function G(e,t,n,r){if(r===void 0&&(r=`numeric`),e instanceof $e)return Tn(r,e.dtype,t,n),e;var i=De(e);if(i!==`string`&&[`bool`,`int32`,`float32`].indexOf(r)>=0&&(i=r),Tn(r,i,t,n),e==null||!xe(e)&&!Array.isArray(e)&&typeof e!=`number`&&typeof e!=`boolean`&&typeof e!=`string`){var a=e==null?`null`:e.constructor.name;throw Error(`Argument '`+t+`' passed to '`+n+`' must be a Tensor or TensorLike, but got '`+a+`'`)}var o=wn(e,i);xe(e)||Array.isArray(e)||(e=[e]);var s=i===`string`?se(e,[],!0):je(e,i,O().getBool(`DEBUG`));return V.makeTensor(s,o,i)}function En(e,t,n,r){if(r===void 0&&(r=`numeric`),!Array.isArray(e))throw Error(`Argument `+t+` passed to `+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map((function(e,r){return G(e,t+`[`+r+`]`,n)}),r)}function Dn(e,t){for(var n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function On(e,t,n){for(var r=e.length+t.length,i=[],a=0,o=0,s=0;s<r;s++)n.indexOf(s)===-1?i.push(e[a++]):i.push(t[o++]);return i}function kn(e,t){for(var n=[],r=e.length,i=0;i<r;i++)t.indexOf(i)===-1&&n.push(e[i]);return[n,t.map((function(t){return e[t]}))]}function An(e,t){return On(e,t.map((function(e){return 1})),t)}function jn(e,t,n){I(Dn(t,n),(function(){return e+` supports only inner-most axes for now. Got axes `+t+` and rank-`+n+` input.`}))}function Mn(e,t){if(Dn(e,t))return null;for(var n=[],r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach((function(e){return n.push(e)})),n}function Nn(e){return e.map((function(e,t){return[t,e]})).sort((function(e,t){return e[1]-t[1]})).map((function(e){return e[0]}))}function Pn(e,t){for(var n=[],r=t-e;r<t;++r)n.push(r);return n}function Fn(e,t){var n=e[0].length;e.forEach((function(e,t){I(e.length===n,(function(){return`Error in concat`+n+`D: rank of tensors[`+t+`] must be the same as the rank of the rest (`+n+`)`}))})),I(t>=0&&t<n,(function(){return`Error in concat`+n+`D: axis must be between 0 and `+(n-1)+`.`}));var r=e[0];e.forEach((function(e,i){for(var a=0;a<n;a++)I(a===t||e[a]===r[a],(function(){return`Error in concat`+n+`D: Shape of tensors[`+i+`] (`+e+`) does not match the shape of the rest (`+r+`) along the non-concatenated axis `+i+`.`}))}))}function In(e,t){for(var n=e[0].slice(),r=1;r<e.length;r++)n[t]+=e[r][t];return n}function K(e){var t=Object.keys(e);if(t.length!==1)throw Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with `+t.length+` keys.`);var n=t[0],r=e[n];n.endsWith(`_`)&&(n=n.substring(0,n.length-1));var i=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];V.startScope(n);try{var i=r.apply(void 0,e);return i instanceof Promise&&console.error(`Cannot return a Promise inside of tidy.`),V.endScope(i),i}catch(e){throw V.endScope(null),e}};return Object.defineProperty(i,`name`,{value:n,configurable:!0}),i}U.registerFlag(`HAS_WEBGL`,(function(){return U.getNumber(`WEBGL_VERSION`)>0})),U.registerFlag(`WEBGL_VERSION`,(function(){return mn(2)?2:mn(1)?1:0})),U.registerFlag(`WEBGL_BUFFER_SUPPORTED`,(function(){return U.get(`WEBGL_VERSION`)===2})),U.registerFlag(`WEBGL_CPU_FORWARD`,(function(){return!0})),U.registerFlag(`WEBGL_FORCE_F16_TEXTURES`,(function(){return!1})),U.registerFlag(`WEBGL_PACK`,(function(){return U.getBool(`HAS_WEBGL`)})),U.registerFlag(`WEBGL_PACK_NORMALIZATION`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_CLIP`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_DEPTHWISECONV`,(function(){return!1})),U.registerFlag(`WEBGL_PACK_BINARY_OPERATIONS`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_UNARY_OPERATIONS`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_ARRAY_OPERATIONS`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_IMAGE_OPERATIONS`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_PACK_REDUCE`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_LAZILY_UNPACK`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_CONV_IM2COL`,(function(){return U.getBool(`WEBGL_PACK`)})),U.registerFlag(`WEBGL_MAX_TEXTURE_SIZE`,(function(){return un(U.getNumber(`WEBGL_VERSION`))})),U.registerFlag(`WEBGL_MAX_TEXTURES_IN_SHADER`,(function(){return dn(U.getNumber(`WEBGL_VERSION`))})),U.registerFlag(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`,(function(){var e=U.getNumber(`WEBGL_VERSION`);return e===0?0:fn(e)})),U.registerFlag(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`,(function(){return U.getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e})),U.registerFlag(`WEBGL_RENDER_FLOAT32_CAPABLE`,(function(){return hn(U.getNumber(`WEBGL_VERSION`))})),U.registerFlag(`WEBGL_RENDER_FLOAT32_ENABLED`,(function(){return!U.getBool(`WEBGL_FORCE_F16_TEXTURES`)&&U.getBool(`WEBGL_RENDER_FLOAT32_CAPABLE`)})),U.registerFlag(`WEBGL_DOWNLOAD_FLOAT_ENABLED`,(function(){return gn(U.getNumber(`WEBGL_VERSION`))})),U.registerFlag(`WEBGL_FENCE_API_ENABLED`,(function(){return vn(U.getNumber(`WEBGL_VERSION`))})),U.registerFlag(`WEBGL_SIZE_UPLOAD_UNIFORM`,(function(){return U.getBool(`WEBGL_RENDER_FLOAT32_ENABLED`)?4:0})),Qe=bn;var Ln=K({complex_:function(e,t){var n=G(e,`real`,`complex`),r=G(t,`imag`,`complex`);return L(n.shape,r.shape,`real and imag shapes, `+n.shape+` and `+r.shape+`, must match in call to tf.complex().`),V.runKernelFunc((function(e){return e.complex(n,r)}),{$real:n,$imag:r})}}),Rn=K({real_:function(e){var t=G(e,`input`,`real`);return V.runKernelFunc((function(e){return e.real(t)}),{$input:t})}}),zn=K({imag_:function(e){var t=G(e,`input`,`imag`);return V.runKernelFunc((function(e){return e.imag(t)}),{$input:t})}});function Bn(e,t,n){return Vn(e,t,wn(e,n),n)}function Vn(e,t,n,r){if(r??=De(e),r===`complex64`)throw Error(`Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).`);if(!xe(e)&&!Array.isArray(e)&&typeof e!=`number`&&typeof e!=`boolean`&&typeof e!=`string`)throw Error(`values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray`);if(t!=null){Ie(t);var i=R(t),a=R(n);I(i===a,(function(){return`Based on the provided shape, [`+t+`], the tensor should have `+i+` values but has `+a}));for(var o=0;o<n.length;++o){var s=n[o],c=o!==n.length-1||s!==R(t.slice(o));I(n[o]===t[o]||!c,(function(){return`Error creating a new Tensor. Inferred shape (`+n+`) does not match the provided shape (`+t+`). `}))}}return xe(e)||Array.isArray(e)||(e=[e]),t||=n,e=r===`string`?se(e,[],!0):je(e,r,O().getBool(`DEBUG`)),V.makeTensor(e,t,r)}function q(e,t){if((xe(e)&&t!==`string`||Array.isArray(e))&&t!==`complex64`)throw Error(`Error creating a new Scalar: value must be a primitive (number|boolean|string)`);if(t===`string`&&xe(e)&&!(e instanceof Uint8Array))throw Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Vn(e,[],[],t)}function Hn(e,t){oe(e);var n=wn(e,t);if(n.length!==1)throw Error(`tensor1d() requires values to be a flat/TypedArray`);return Vn(e,null,n,t)}function Un(e,t,n){if(oe(e),t!=null&&t.length!==2)throw Error(`tensor2d() requires shape to have two numbers`);var r=wn(e,n);if(r.length!==2&&r.length!==1)throw Error(`tensor2d() requires values to be number[][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Vn(e,t,r,n)}function Wn(e,t,n){if(oe(e),t!=null&&t.length!==3)throw Error(`tensor3d() requires shape to have three numbers`);var r=wn(e,n);if(r.length!==3&&r.length!==1)throw Error(`tensor3d() requires values to be number[][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor3d() requires shape to be provided when `values` are a flat array");return Vn(e,t,r,n)}function Gn(e,t,n){if(oe(e),t!=null&&t.length!==4)throw Error(`tensor4d() requires shape to have four numbers`);var r=wn(e,n);if(r.length!==4&&r.length!==1)throw Error(`tensor4d() requires values to be number[][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor4d() requires shape to be provided when `values` are a flat array");return Vn(e,t,r,n)}function Kn(e,t,n){if(oe(e),t!=null&&t.length!==5)throw Error(`tensor5d() requires shape to have five numbers`);var r=wn(e,n);if(r.length!==5&&r.length!==1)throw Error(`tensor5d() requires values to be number[][][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor5d() requires shape to be provided when `values` are a flat array");return Vn(e,t,r,n)}function qn(e,t,n){if(oe(e),t!=null&&t.length!==6)throw Error(`tensor6d() requires shape to have six numbers`);var r=wn(e,n);if(r.length!==6&&r.length!==1)throw Error(`tensor6d() requires values to be number[][][][][][] or flat/TypedArray`);if(r.length===1&&t==null)throw Error("tensor6d() requires shape to be provided when `values` are a flat array");return Vn(e,t||=r,r,n)}function Jn(e,t,n,r){return t===void 0&&(t=!0),V.makeVariable(e,t,n,r)}function Yn(e,t){if(t===void 0&&(t=`float32`),t===`complex64`)return Ln(Yn(e,`float32`),Xn(e,`float32`));var n=Ne(R(e),t);return V.makeTensor(n,e,t)}function Xn(e,t){if(t===void 0&&(t=`float32`),t===`complex64`)return Ln(Xn(e,`float32`),Xn(e,`float32`));var n=Pe(R(e),t);return V.makeTensor(n,e,t)}function Zn(e,t,n){return V.runKernelFunc((function(r){return r.fill(e,t,n)}),{})}function Qn(e,t,n){if(n<=0)throw Error(`The number of values should be positive.`);return V.runKernelFunc((function(r){return r.linspace(e,t,n)}),{})}function $n(e,t,n,r){if(n===void 0&&(n=1),r===void 0&&(r=`float32`),n===0)throw Error(`Cannot have a step of zero`);if(e===t||e<t&&n<0||t<e&&n>1)return Xn([0],r);var i=Pe(Math.abs(Math.ceil((t-e)/n)),r);t<e&&n===1&&(n=-1),i[0]=e;for(var a=1;a<i.length;a++)i[a]=i[a-1]+n;return Hn(i,r)}var er=K({onesLike_:function(e){var t=G(e,`x`,`onesLike`);return t.dtype===`complex64`?Ln(er(Rn(t)),tr(zn(t))):V.runKernelFunc((function(e){return e.onesLike(t)}),{$x:t},(function(e,t){return{$x:function(){return tr(e)}}}))}}),tr=K({zerosLike_:function(e){var t=G(e,`x`,`zerosLike`);return V.runKernelFunc((function(e){return e.zerosLike(t)}),{$x:t},(function(e,t){return{$x:function(){return tr(e)}}}))}}),nr=K({concat_:function(e,t){t===void 0&&(t=0),I(e.length>=1,(function(){return`Pass at least one tensor to concat`}));var n=En(e,`tensors`,`concat`);n[0].dtype===`complex64`&&n.forEach((function(e){if(e.dtype!==`complex64`)throw Error(`Cannot concatenate complex64 tensors with a tensor
|
|
10
|
+
with dtype `+e.dtype+`. `)})),t=me(t,n[0].shape)[0];var r=In(n.map((function(e){return e.shape})),t);if(R(r)===0)return Bn([],r);if((n=n.filter((function(e){return e.size>0}))).length===1)return n[0];var i=n.map((function(e){return e.shape}));Fn(i,t);var a=n,o={axis:t};return V.runKernelFunc((function(e){return e.concat(n,t)}),a,(function(e){return sr(e,i.map((function(e){return e[t]})),t).map((function(e){return function(){return e}}))}),`Concat`,o)}}),rr=K({concat1d_:function(e){return nr(e,0)}}),ir=K({concat2d_:function(e,t){return nr(e,t)}}),ar=K({concat3d_:function(e,t){return nr(e,t)}}),or=K({concat4d_:function(e,t){return nr(e,t)}}),sr=K({split_:function(e,t,n){n===void 0&&(n=0);var r,i=G(e,`x`,`split`);return n=me(n,i.shape)[0],typeof t==`number`?(I(i.shape[n]%t==0,(function(){return`Number of splits must evenly divide the axis.`})),r=Array(t).fill(i.shape[n]/t)):(I(i.shape[n]===t.reduce((function(e,t){return e+t})),(function(){return`The sum of sizes must match the size of the axis dimension.`})),r=t),V.runKernelFunc((function(e){return e.split(i,r,n)}),{$x:i},(function(e){return{$x:function(){return nr(e,n)}}}))}});function cr(e,t){return e(t={exports:{}},t.exports),t.exports}var lr=cr((function(e){(function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 23283064365386963e-26*(t>>>0)});n.next=function(){var e=2091639*n.s0+23283064365386963e-26*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(` `),n.s1=r(` `),n.s2=r(` `),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.alea=a})(0,e,!1)})),ur=cr((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a})(0,e,!1)})),dr=cr((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a})(0,e,!1)})),fr=cr((function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,i=t.i;return e=r[i],n=(e^=e>>>7)^e<<24,n^=(e=r[i+1&7])^e>>>10,n^=(e=r[i+3&7])^e>>>3,n^=(e=r[i+4&7])^e<<7,e=r[i+7&7],n^=(e^=e<<13)^e<<9,r[i]=n,t.i=i+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a})(0,e,!1)})),pr=cr((function(e){(function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,i=t.X,a=t.i;return t.w=r=r+1640531527|0,n=i[a+34&127],e=i[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=i[a]=n^e,t.i=a,n+(r^r>>>16)|0},function(e,t){var n,r,i,a,o,s=[],c=128;for(t===(0|t)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=(n=s[127&a]^=r+o)==0?i+1:0);for(i>=128&&(s[127&(t&&t.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a})(0,e,!1)})),mr=cr((function(e){(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a})(0,e,!1)})),hr=cr((function(e){(function(t,n){var r,i=this,a=256,o=6,s=`random`,c=n.pow(a,o),l=n.pow(2,52),u=2*l,d=a-1;function f(e,d,f){var _=[],v=h(function e(t,n){var r,i=[],a=typeof t;if(n&&a==`object`)for(r in t)try{i.push(e(t[r],n-1))}catch{}return i.length?i:a==`string`?t:t+`\0`}((d=d==1?{entropy:!0}:d||{}).entropy?[e,g(t)]:e??function(){try{var e;return r&&(e=r.randomBytes)?e=e(a):(e=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(e)),g(e)}catch{var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,g(t)]}}(),3),_),y=new p(_),b=function(){for(var e=y.g(o),t=c,n=0;e<l;)e=(e+n)*a,t*=a,n=y.g(1);for(;e>=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,h(g(y.S),t),(d.pass||f||function(e,t,r,i){return i&&(i.S&&m(i,y),e.state=function(){return m(y,{})}),r?(n[s]=e,t):e})(b,v,`global`in d?d.global:this==n,d.state)}function p(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=d&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=d&i+1],n=n*a+s[d&(s[i]=s[o=d&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function h(e,t){for(var n,r=e+``,i=0;i<r.length;)t[d&i]=d&(n^=19*t[d&i])+r.charCodeAt(i++);return g(t)}function g(e){return String.fromCharCode.apply(0,e)}if(n[`seed`+s]=f,h(n.random(),t),e.exports){e.exports=f;try{r=x()}catch{}}})([],Math)}));hr.alea=lr,hr.xor128=ur,hr.xorwow=dr,hr.xorshift7=fr,hr.xor4096=pr,hr.tychei=mr;var gr=hr.alea,_r=function(){function e(e,t,n,r,i){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev),this.random=gr((i||Math.random()).toString())}return e.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var e=this.nextVal;return this.nextVal=NaN,e}for(var t,n,r=!1;!r;){var i=void 0,a=void 0,o=void 0;do o=(i=2*this.random()-1)*i+(a=2*this.random()-1)*a;while(o>=1||o===0);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return this.dtype==null||this.dtype===`float32`?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),vr=function(){function e(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n,this.randu=gr((r||Math.random()).toString()),this.randn=new _r(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}return e.prototype.nextValue=function(){for(var e,t,n,r,i,a;;){do r=this.randn.nextValue(),a=1+this.c*r;while(a<=0);if(a*=a*a,t=1-.331*(e=r*r)*e,n=.5*e+this.d*(1-a+Math.log(a)),(i=this.randu())<t||Math.log(i)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=this.randu()**(1/this.alpha)),this.convertValue(a)},e.prototype.convertValue=function(e){return this.dtype===`float32`?e:Math.round(e)},e}(),yr=function(){function e(e,t,n,r){var i=this;if(e===void 0&&(e=0),t===void 0&&(t=1),this.canReturnFloat=function(){return i.dtype==null||i.dtype===`float32`},this.min=e,this.range=t-e,this.dtype=n,r??=Math.random(),typeof r==`number`&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw Error(`The difference between `+e+` - `+t+` <= 1 and dtype is not float`);this.random=gr(r)}return e.prototype.convertValue=function(e){return this.canReturnFloat()?e:Math.round(e)},e.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},e}();function J(e,t,n){return t===void 0&&(t=`float32`),t||=`float32`,Ie(e),new Xe(e,t,n)}function br(e,t){t===void 0&&(t=!1),console.log(e.toString(t))}var xr=K({batchToSpaceND_:function(e,t,n){var r=G(e,`x`,`batchToSpaceND`),i=t.reduce((function(e,t){return e*t}));return I(r.rank>=1+t.length,(function(){return`input rank is `+r.rank+` but should be > than blockShape.length `+t.length})),I(n.length===t.length,(function(){return`crops.length is `+n.length+` but should be equal to blockShape.length `+t.length})),I(r.shape[0]%i==0,(function(){return`input tensor batch is `+r.shape[0]+` but is not divisible by the product of the elements of blockShape `+t.join(` * `)+` === `+i})),V.runKernelFunc((function(e){return e.batchToSpaceND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}}))}}),Sr=K({broadcastTo_:function(e,t){var n=G(e,`broadcastTo`,`x`),r=n.shape;if(t.some((function(e){return!(e>0)||e%1!=0})))throw Error(`broadcastTo(): Invalid broadcast shape [`+t+`].`);if(t.length<n.rank)throw Error(`broadcastTo(): shape.length=`+t.length+` < input.rank=`+n.rank+`.`);if(t.length>n.rank){for(var i=n.shape.slice();i.length<t.length;)i.unshift(1);n=n.reshape(i)}for(var a=Array.from(t),o=t.length-1;o>=0;o--)if(n.shape[o]===t[o])a[o]=1;else if(n.shape[o]!==1)throw Error(`broadcastTo(): [`+r+`] cannot be broadcast to [`+t+`].`);var s=a.map((function(e,t){return e>1?t:-1})).filter((function(e){return e>=0}));return s.length===0?n.clone():V.runKernelFunc((function(e){return e.tile(n,a)}),{input:n},(function(e){return{input:function(){return e.sum(s,!0)}}}))}}),Cr=K({cast_:function(e,t){var n=G(e,`x`,`cast`);if(!ye(t))throw Error(`Failed to cast to unknown dtype `+t);if(t===`string`&&n.dtype!==`string`||t!==`string`&&n.dtype===`string`)throw Error(`Only strings can be casted to strings`);var r={dtype:t};return V.runKernelFunc((function(e){return e.cast(n,t)}),{x:n},(function(e){return{x:function(){return e.clone()}}}),`Cast`,r)}}),wr=K({clone_:function(e){var t=G(e,`x`,`clone`,null);return V.runKernelFunc((function(){return V.makeTensorFromDataId(t.dataId,t.shape,t.dtype)}),{$x:t},(function(e){return{$x:function(){return e.toFloat()}}}))}}),Tr=K({cumsum_:function(e,t,n,r){t===void 0&&(t=0),n===void 0&&(n=!1),r===void 0&&(r=!1);var i=G(e,`x`,`cumsum`),a=Mn([t|=0],i.rank),o=i;a!=null&&(o=i.transpose(a));var s=Pn(1,i.rank)[0],c=V.runKernelFunc((function(e){return e.cumsum(o,s,n,r)}),{permutedX:o},(function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}}));return a!=null&&(c=c.transpose(a)),c}}),Er=K({depthToSpace_:function(e,t,n){n===void 0&&(n=`NHWC`);var r=G(e,`x`,`depthToSpace`),i=n===`NHWC`?r.shape[1]:r.shape[2],a=n===`NHWC`?r.shape[2]:r.shape[3],o=n===`NHWC`?r.shape[3]:r.shape[1];return I(i*t>=0,(function(){return`Negative dimension size caused by overflow when multiplying
|
|
11
11
|
`+i+` and `+t+` for depthToSpace with input shape
|
|
12
|
-
`+r.shape})),
|
|
12
|
+
`+r.shape})),I(a*t>=0,(function(){return`Negative dimension size caused by overflow when multiplying
|
|
13
13
|
`+a+` and `+t+` for depthToSpace with input shape
|
|
14
|
-
`+r.shape})),O(o%(t*t)==0,(function(){return`Dimension size must be evenly divisible by `+t*t+` but is `+o+` for depthToSpace with input shape `+r.shape})),z.runKernelFunc((function(e){return e.depthToSpace(r,t,n)}),{$x:r})}}),hr=W({expandDims_:function(e,t){t===void 0&&(t=0);var n=U(e,`x`,`expandDims`,null);O(t<=n.rank,(function(){return`Axis must be <= rank of the tensor`}));var r=n.shape.slice();return t<0&&(O(-(n.rank+1)<=t,(function(){return`Axis must be in the interval [`+-(n.rank+1)+`, `+n.rank+`]`})),t=n.rank+t+1),r.splice(t,0,1),Or(n,r)}}),gr=W({eye_:function(e,t,n,r){r===void 0&&(r=`float32`),t??=e;for(var i=K([e,t],r),a=e<=t?e:t,o=0;o<a;++o)i.set(1,o,o);var s=i.toTensor().as2D(e,t);if(n==null)return s;if(n.length===1)return Mr(hr(s,0),[n[0],1,1]);if(n.length===2)return Mr(hr(hr(s,0),0),[n[0],n[1],1,1]);if(n.length===3)return Mr(hr(hr(hr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw Error(`eye() currently supports only 1D and 2D batchShapes, but received `+n.length+`D.`)}}),_r=W({multinomial_:function(e,t,n,r){r===void 0&&(r=!1);var i=U(e,`logits`,`multinomial`),a=i.size,o=i.rank;if(a<2)throw Error(`Error in multinomial: you need at least 2 outcomes, but got `+a+`.`);if(o>2)throw Error(`Rank of probabilities must be 1 or 2, but is `+o);n||=Math.random();var s=o===1?i.as2D(1,-1):i,c=z.runKernelFunc((function(e){return e.multinomial(s,r,t,n)}),{logits2D:s});return o===1?c.as1D():c}}),vr=W({oneHot_:function(e,t,n,r){if(n===void 0&&(n=1),r===void 0&&(r=0),t<2)throw Error(`Error in oneHot: depth must be >=2, but it is `+t);var i=U(e,`indices`,`oneHot`,`int32`),a=i.shape.concat([t]);return i=i.flatten(),z.runKernelFunc((function(e){return e.oneHot(i,t,n,r)}),{$indices:i},(function(e){return{$indices:function(){return Rn(i.shape,`float32`)}}})).reshape(a)}}),yr=W({pad_:function(e,t,n){n===void 0&&(n=0);var r=U(e,`x`,`pad`);if(r.rank===0)throw Error(`pad(scalar) is not defined. Pass non-scalar to pad`);var i={paddings:t,constantValue:n};return z.runKernelFunc((function(e){return e.pad(r,t,n)}),{x:r},(function(e){var n=t.map((function(e){return e[0]}));return{x:function(){return e.slice(n,r.shape)}}}),`PadV2`,i)}}),br=W({pad1d_:function(e,t,n){return n===void 0&&(n=0),O(t.length===2,(function(){return`Invalid number of paddings. Must be length of 2.`})),yr(e,[t],n)}}),xr=W({pad2d_:function(e,t,n){return n===void 0&&(n=0),O(t.length===2&&t[0].length===2&&t[1].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),yr(e,t,n)}}),Sr=W({pad3d_:function(e,t,n){return n===void 0&&(n=0),O(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),yr(e,t,n)}}),Cr=W({pad4d_:function(e,t,n){return n===void 0&&(n=0),O(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),yr(e,t,n)}}),wr=W({rand_:function(e,t,n){var r=M(e),i=null;if(n==null||n===`float32`)i=new Float32Array(r);else if(n===`int32`)i=new Int32Array(r);else{if(n!==`bool`)throw Error(`Unknown data type `+n);i=new Uint8Array(r)}for(var a=0;a<r;a++)i[a]=t();return z.makeTensor(i,e,n)}}),Tr=W({randomNormal_:function(e,t,n,r,i){if(t===void 0&&(t=0),n===void 0&&(n=1),r!=null&&r===`bool`)throw Error(`Unsupported data type `+r);for(var a=new ar(t,n,r,!1,i),o=K(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Er=W({randomGamma_:function(e,t,n,r,i){if(n===void 0&&(n=1),r===void 0&&(r=`float32`),n??=1,r??=`float32`,r!==`float32`&&r!==`int32`)throw Error(`Unsupported data type `+r);for(var a=new or(t,n,r,i),o=K(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Dr=W({randomUniform_:function(e,t,n,r,i){t===void 0&&(t=0),n===void 0&&(n=1),r===void 0&&(r=`float32`);for(var a=K(e,r),o=new sr(t,n,null,i),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),Or=W({reshape_:function(e,t){var n=U(e,`x`,`reshape`,null);t=ne(t,n.size),O(n.size===M(t),(function(){return`new shape and old shape must have the same number of elements.`}));var r={shape:t};return z.runKernelFunc((function(e){return e.reshape(n,t)}),{x:n},(function(e){return{x:function(){return e.reshape(n.shape)}}}),`Reshape`,r)}}),kr=W({spaceToBatchND_:function(e,t,n){var r=U(e,`x`,`spaceToBatchND`);return O(r.rank>=1+t.length,(function(){return`input rank `+r.rank+` should be > than [blockShape] `+t.length})),O(n.length===t.length,(function(){return`paddings.shape[0] `+n.length+` must be equal to [blockShape] `+t.length})),O(r.shape.reduce((function(e,r,i){return i>0&&i<=t.length?e&&(r+n[i-1][0]+n[i-1][1])%t[i-1]==0:e}),!0),(function(){return`input spatial dimensions `+r.shape.slice(1)+` with paddings `+n.toString()+` must be divisible by blockShapes `+t.toString()})),z.runKernelFunc((function(e){return e.spaceToBatchND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}}))}}),Ar=W({squeeze_:function(e,t){var n=U(e,`x`,`squeeze`);return Or(n,re(n.shape,t).newShape)}}),jr=W({stack_:function(e,t){t===void 0&&(t=0);var n=mn(e,`tensors`,`stack`);if(O(n.length>=1,(function(){return`Pass at least one tensor to tf.stack`})),n.length===1)return n[0].expandDims(t);var r=n[0].rank,i=n[0].shape,a=n[0].dtype;return O(t<=r,(function(){return`Axis must be <= rank of the tensor`})),n.forEach((function(e){k(i,e.shape,`All tensors passed to stack must have matching shapes`)})),n.forEach((function(e){O(a===e.dtype,(function(){return`All tensors passed to stack must have matching dtypes`}))})),Wn(n.map((function(e){return e.expandDims(t)})),t)}}),Mr=W({tile_:function(e,t){var n=U(e,`x`,`tile`,null);O(n.rank===t.length,(function(){return`Error in transpose: rank of input `+n.rank+` must match length of reps `+t+`.`}));var r=[n],i={reps:t};return z.runKernelFunc((function(e,r){var i=e.tile(n,t);return r([n]),i}),{x:n},(function(e,n){var r=n[0];return{x:function(){var n=Un(r);if(r.rank===1)for(var i=0;i<t[0];++i)n=n.add(e.slice([i*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(i=0;i<t[0];++i)for(var a=0;a<t[1];++a)n=n.add(e.slice([i*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(i=0;i<t[0];++i)for(a=0;a<t[1];++a)for(var o=0;o<t[2];++o)n=n.add(e.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(r.rank!==4)throw Error(`Gradient for tile operation is not implemented for rank-`+r.rank+` tensors yet.`);for(i=0;i<t[0];++i)for(a=0;a<t[1];++a)for(o=0;o<t[2];++o)for(var s=0;s<t[3];++s)n=n.add(e.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),`Tile`,i,r)}}),Nr=W({truncatedNormal_:function(e,t,n,r,i){if(t===void 0&&(t=0),n===void 0&&(n=1),r!=null&&r===`bool`)throw Error(`Unsupported data type `+r);for(var a=new ar(t,n,r,!0,i),o=K(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Pr=W({unstack_:function(e,t){t===void 0&&(t=0),t||=0;var n=U(e,`x`,`unstack`);O(t>=-n.shape.length&&t<n.shape.length,(function(){return`Axis = `+t+` is not in [-`+n.shape.length+`, `+n.shape.length+`)`})),t<0&&(t+=n.shape.length);var r={axis:t};return z.runKernelFunc((function(e){return e.unstack(n,t)}),{x:n},(function(e){return{x:function(){return jr(e,t)}}}),`Unpack`,r)}}),Fr=function(e,t){return u(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u,f;return d(this,(function(d){switch(d.label){case 0:return n=U(e,`x`,`setdiff1d`),r=U(t,`y`,`setdiff1d`),O(n.dtype===r.dtype,(function(){return`x and y should have the same dtype, but got x (`+n.dtype+`) and y (`+r.dtype+`).`})),O(n.rank===1,(function(){return`x should be 1D tensor, but got x (`+n.shape+`).`})),O(r.rank===1,(function(){return`y should be 1D tensor, but got y (`+r.shape+`).`})),[4,n.data()];case 1:return i=d.sent(),[4,r.data()];case 2:for(a=d.sent(),o=new Set(a),s=0,u=0;u<i.length;u++)o.has(i[u])||s++;for(c=new Re([s],n.dtype),l=new Re([s],`int32`),u=0,f=0;u<i.length;u++)o.has(i[u])||(c.values[f]=i[u],l.values[f]=u,f++);return[2,[c.toTensor(),l.toTensor()]]}}))}))};function Ir(e,t,n,r){r===void 0&&(r=!0);var i=[];if(r)(i=i.concat(t.slice(0))).push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);for(var a=t.length,o=0;o<a;++o)i=i.concat([e[o+1]/t[o],t[o]]);i=i.concat(e.slice(a+1))}return i}function Lr(e,t,n){n===void 0&&(n=!0);var r=[];if(n){r.push(t);for(var i=t+1;i<e;++i)i<=2*t?(r.push(i),r.push(i-(t+1))):r.push(i)}else{var a=[],o=[];for(i=1;i<e;++i)i>=2*t+1||i%2==1?o.push(i):a.push(i);r.push.apply(r,a),r.push(0),r.push.apply(r,o)}return r}function Rr(e,t,n,r){r===void 0&&(r=!0);var i=[];r?i.push(e[0]/n):i.push(e[0]*n);for(var a=1;a<e.length;++a)a<=t.length?r?i.push(t[a-1]*e[a]):i.push(e[a]/t[a-1]):i.push(e[a]);return i}function zr(e,t){for(var n=[0],r=0;r<t;++r)n.push(e[r][0]);return n}function Br(e,t,n){for(var r=e.slice(0,1),i=0;i<n;++i)r.push(e[i+1]-t[i][0]-t[i][1]);return r}function Vr(e,t){if(e.rank<1)throw Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was `+e.rank+`.`);if(t.rank<1)throw Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was `+t.rank+`.`);if(t.dtype!==`int32`)throw Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was `+t.dtype+`.`);if(t.shape[t.rank-1]>e.rank)throw Error(`index innermost dimension length must be <= tensor rank; saw: `+t.shape[t.rank-1]+` vs. `+e.rank);if(e.size===0)throw Error(`Requested more than 0 entries, but input is empty. Input shape: `+e.shape+`.`);for(var n=t.shape,r=n[n.length-1],i=1,a=0;a<n.length-1;++a)i*=n[a];var o=e.shape,s=n.slice();s.pop();var c=1;for(a=r;a<e.rank;++a)c*=o[a],s.push(o[a]);var l=ve(e.shape).map((function(e){return e/c})).concat([1]).slice(0,r);return[s,i,c,l]}Object.freeze({prepareAndValidate:Vr});var Hr=30;function Ur(e){return e<=Hr?e:_e(e,Math.floor(Math.sqrt(e)))}function Wr(e,t,n){var r=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: `+n.shape+`, indices.shape: `+t.shape+`, shape: `+e+`, sliceDim: `+r+`, and batchDim: `+i+`.`;if(n.rank<i)throw Error(a+` update.rank < `+i+`. `);if(e.length<r+(n.rank-i))throw Error(a+` Output shape length < `+(r+(n.rank-i)));if(n.rank!==i+e.length-r)throw Error(a+` update.rank != `+(i+e.length-r));for(var o=0;o<i;++o)if(n.shape[o]!==t.shape[o])throw Error(a+` updates.shape[`+o+`] (`+n.shape[o]+`) != indices.shape[`+o+`] (`+t.shape[o]+`).`);for(o=0;o<n.rank-i;++o)if(n.shape[o+i]!==e[o+r])throw Error(a+` updates.shape[`+(o+i)+`] (`+n.shape[o+i]+`) != shape[`+(o+i)+`] (`+e[o+i]+`)`)}function Gr(e,t,n){if(t.rank<1)throw Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was `+t.rank+`.`);if(e.rank<1)throw Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was `+e.rank+`.`);if(t.dtype!==`int32`)throw Error(`The dtype of 'indices' should be int32, but got dtype: `+t.dtype);if(n.length<1)throw Error(`Output rank must be greater or equal to 1, but got shape: `+n);if(n.length===0){if(t.size===0)throw Error(`Indices specified for empty output. indices shape: `+t.shape);if(e.size===0)throw Error(`Updates specified for empty output. updates shape: `+e.shape)}Wr(n,t,e)}function Kr(e,t,n){for(var r=t.shape.length,i=r>1?t.shape[r-1]:1,a=n.length,o=1,s=i;s<a;++s)o*=n[s];var c=i<1?1:i;return{sliceRank:i,numUpdates:M(t.shape)/c,sliceSize:o,strides:ve(n.slice(0,i)).concat([1]),outputSize:M(n)}}Object.freeze({validateUpdateShape:Wr,validateInput:Gr,calculateShapes:Kr});function qr(e,t,n){O(e.rank===t.length,(function(){return`Error in slice`+e.rank+`D: Length of begin `+t+` must match the rank of the array (`+e.rank+`).`})),O(e.rank===n.length,(function(){return`Error in slice`+e.rank+`D: Length of size `+n+` must match the rank of the array (`+e.rank+`).`}));for(var r=function(r){O(t[r]+n[r]<=e.shape[r],(function(){return`Error in slice`+e.rank+`D: begin[`+r+`] + size[`+r+`] (`+(t[r]+n[r])+`) would overflow input.shape[`+r+`] (`+e.shape[r]+`)`}))},i=0;i<e.rank;++i)r(i)}function Jr(e){for(var t=[],n=0;e>0;)1&e&&t.push(n),e/=2,n++;return t}function Yr(e,t,n){for(var r=[],i=0;i<e.length;i++)r[i]=Math.ceil((t[i]-e[i])/n[i]);return r}function Xr(e,t,n,r,i){var a=t[i],o=n[i]||1;(e&1<<i||a==null)&&(a=o>0?-(2**53-1):2**53-1);var s=r[i];return a<0&&(a+=s),a=T(0,a,s-1)}function Zr(e,t,n,r,i){var a=t[i],o=n[i]||1;(e&1<<i||a==null)&&(a=o>0?2**53-1:-(2**53-1));var s=r[i];return a<0&&(a+=s),a=o>0?T(0,a,s):T(-1,a,s-1)}function Qr(e,t,n){for(var r=n.length,i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(i=r+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function $r(e,t){for(var n=e.length>0?e[e.length-1]:1,r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}Object.freeze({assertParamsValid:qr,maskToAxes:Jr,computeOutShape:Yr,startForAxis:Xr,stopForAxis:Zr,isSliceContinous:Qr,computeFlatOffset:$r});function ei(e,t){O(ge(e),(function(){return`The f passed in variableGrads(f) must be a function`})),O(t==null||Array.isArray(t)&&t.every((function(e){return e instanceof qe})),(function(){return`The varList passed in variableGrads(f, varList) must be an array of variables`}));var n=t!=null;if(!n)for(var r in t=[],z.registeredVariables)t.push(z.registeredVariables[r]);var i=n?t.filter((function(e){return!e.trainable})):null,a=t.length;O((t=t.filter((function(e){return e.trainable}))).length>0,(function(){return`variableGrads() expects at least one of the input variables to be trainable, but none of the `+a+` variables is trainable.`}));var o=z.gradients(e,t,null,!0),s=o.value,c=o.grads;O(c.some((function(e){return e!=null})),(function(){return`Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().`})),O(s.rank===0,(function(){return`The f passed in variableGrads(f) must return a scalar, but it returned a rank-`+s.rank+` tensor`}));var l={};return t.forEach((function(e,t){c[t]!=null&&(l[e.name]=c[t])})),i?.forEach((function(e){return l[e.name]=null})),{value:s,grads:l}}function ti(e){return z.customGrad(e)}var ni=W({softmax_:function(e,t){t===void 0&&(t=-1);var n=U(e,`logits`,`softmax`,`float32`);if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank `+n.rank+` and dim was `+t);return z.runKernelFunc((function(e,r){var i=e.softmax(n,t);return r([i]),i}),{logits:n},(function(e,n){var r=n[0],i=e.mul(r);return{logits:function(){return i.sub(i.sum([t],!0).mul(r))}}}),`Softmax`,{dim:t},[],[!0])}}),ri=W({logSoftmax_:function(e,t){t===void 0&&(t=-1);var n=U(e,`logits`,`logSoftmax`);if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank `+n.rank+` and axis was `+t);return ti((function(e,n){var r=e.max(t,!0),i=e.sub(r),a=i.toFloat().sub(i.exp().sum(t,!0).log());return n([a]),{value:a,gradFunc:function(e,n){var r=n[0].exp();return e.sub(e.sum(t,!0).mul(r))}}}))(n)}}),ii=function(){function e(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}return e.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},e.prototype.set=function(e,t){this.dataIdsCount++,this.data.set(e,t)},e.prototype.has=function(e){return this.data.has(e)},e.prototype.delete=function(e){return this.dataIdsCount--,this.data.delete(e)},e.prototype.numDataIds=function(){return this.dataIdsCount},e}(),ai=function(){function e(){}return e.prototype.time=function(e){return q(`time`)},e.prototype.read=function(e){return q(`read`)},e.prototype.readSync=function(e){return q(`readSync`)},e.prototype.numDataIds=function(){return q(`numDataIds`)},e.prototype.disposeData=function(e){return q(`disposeData`)},e.prototype.write=function(e,t,n){return q(`write`)},e.prototype.move=function(e,t,n,r){return q(`move`)},e.prototype.memory=function(){return q(`memory`)},e.prototype.floatPrecision=function(){return q(`floatPrecision`)},e.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},e.prototype.batchMatMul=function(e,t,n,r){return q(`batchMatMul`)},e.prototype.fusedBatchMatMul=function(e){return e.a,e.b,e.transposeA,e.transposeB,e.bias,e.activation,e.preluActivationWeights,q(`fusedBatchMatMul`)},e.prototype.slice=function(e,t,n){return q(`slice`)},e.prototype.stridedSlice=function(e,t,n,r){return q(`stridedSlice`)},e.prototype.unstack=function(e,t){return q(`unstack`)},e.prototype.reverse=function(e,t){return q(`reverse`)},e.prototype.concat=function(e,t){return q(`concat`)},e.prototype.neg=function(e){return q(`neg`)},e.prototype.add=function(e,t){return q(`add`)},e.prototype.addN=function(e){return q(`addN`)},e.prototype.subtract=function(e,t){return q(`subtract`)},e.prototype.multiply=function(e,t){return q(`multiply`)},e.prototype.realDivide=function(e,t){return q(`realDivide`)},e.prototype.floorDiv=function(e,t){return q(`floorDiv`)},e.prototype.sum=function(e,t){return q(`sum`)},e.prototype.prod=function(e,t){return q(`prod`)},e.prototype.unsortedSegmentSum=function(e,t,n){return q(`unsortedSegmentSum`)},e.prototype.argMin=function(e,t){return q(`argMin`)},e.prototype.argMax=function(e,t){return q(`argMax`)},e.prototype.equal=function(e,t){return q(`equal`)},e.prototype.notEqual=function(e,t){return q(`notEqual`)},e.prototype.less=function(e,t){return q(`less`)},e.prototype.lessEqual=function(e,t){return q(`lessEqual`)},e.prototype.greater=function(e,t){return q(`greater`)},e.prototype.greaterEqual=function(e,t){return q(`greaterEqual`)},e.prototype.logicalNot=function(e){return q(`logicalNot`)},e.prototype.logicalAnd=function(e,t){return q(`logicalAnd`)},e.prototype.logicalOr=function(e,t){return q(`logicalOr`)},e.prototype.where=function(e){return q(`where`)},e.prototype.select=function(e,t,n){return q(`select`)},e.prototype.topk=function(e,t,n){return q(`topk`)},e.prototype.min=function(e,t){return q(`min`)},e.prototype.minimum=function(e,t){return q(`minimum`)},e.prototype.mod=function(e,t){return q(`mod`)},e.prototype.max=function(e,t){return q(`max`)},e.prototype.maximum=function(e,t){return q(`maximum`)},e.prototype.all=function(e,t){return q(`all`)},e.prototype.any=function(e,t){return q(`any`)},e.prototype.squaredDifference=function(e,t){return q(`squaredDifference`)},e.prototype.ceil=function(e){return q(`ceil`)},e.prototype.floor=function(e){return q(`floor`)},e.prototype.round=function(e){return q(`round`)},e.prototype.sign=function(e){return q(`sign`)},e.prototype.isNaN=function(e){return q(`isNaN`)},e.prototype.isInf=function(e){return q(`isInf`)},e.prototype.isFinite=function(e){return q(`isFinite`)},e.prototype.pow=function(e,t){return q(`pow`)},e.prototype.exp=function(e){return q(`exp`)},e.prototype.expm1=function(e){return q(`expm1`)},e.prototype.softmax=function(e,t){return q(`softmax`)},e.prototype.log=function(e){return q(`log`)},e.prototype.log1p=function(e){return q(`log1p`)},e.prototype.sqrt=function(e){return q(`sqrt`)},e.prototype.rsqrt=function(e){return q(`rsqrt`)},e.prototype.square=function(e){return q(`square`)},e.prototype.reciprocal=function(e){return q(`reciprocal`)},e.prototype.relu=function(e){return q(`relu`)},e.prototype.relu6=function(e){return q(`relu6`)},e.prototype.prelu=function(e,t){return q(`prelu`)},e.prototype.elu=function(e){return q(`elu`)},e.prototype.eluDer=function(e,t){return q(`eluDer`)},e.prototype.selu=function(e){return q(`selu`)},e.prototype.int=function(e){return q(`int`)},e.prototype.clip=function(e,t,n){return q(`clip`)},e.prototype.abs=function(e){return q(`abs`)},e.prototype.complexAbs=function(e){return q(`complexAbs`)},e.prototype.sigmoid=function(e){return q(`sigmoid`)},e.prototype.softplus=function(e){return q(`softplus`)},e.prototype.sin=function(e){return q(`sin`)},e.prototype.cos=function(e){return q(`cos`)},e.prototype.tan=function(e){return q(`tan`)},e.prototype.asin=function(e){return q(`asin`)},e.prototype.acos=function(e){return q(`acos`)},e.prototype.atan=function(e){return q(`atan`)},e.prototype.atan2=function(e,t){return q(`atan2`)},e.prototype.sinh=function(e){return q(`sinh`)},e.prototype.cosh=function(e){return q(`cosh`)},e.prototype.tanh=function(e){return q(`tanh`)},e.prototype.asinh=function(e){return q(`asinh`)},e.prototype.acosh=function(e){return q(`acosh`)},e.prototype.atanh=function(e){return q(`atanh`)},e.prototype.erf=function(e){return q(`erf`)},e.prototype.step=function(e,t){return q(`step`)},e.prototype.fusedConv2d=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,q(`fusedConv2d`)},e.prototype.conv2d=function(e,t,n){return q(`conv2d`)},e.prototype.conv2dDerInput=function(e,t,n){return q(`conv2dDerInput`)},e.prototype.conv2dDerFilter=function(e,t,n){return q(`conv2dDerFilter`)},e.prototype.fusedDepthwiseConv2D=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,q(`fusedDepthwiseConv2D`)},e.prototype.depthwiseConv2D=function(e,t,n){return q(`depthwiseConv2D`)},e.prototype.depthwiseConv2DDerInput=function(e,t,n){return q(`depthwiseConv2DDerInput`)},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){return q(`depthwiseConv2DDerFilter`)},e.prototype.conv3d=function(e,t,n){return q(`conv3d`)},e.prototype.conv3dDerInput=function(e,t,n){return q(`conv3dDerInput`)},e.prototype.conv3dDerFilter=function(e,t,n){return q(`conv3dDerFilter`)},e.prototype.maxPool=function(e,t){return q(`maxPool`)},e.prototype.maxPoolBackprop=function(e,t,n,r){return q(`maxPoolBackprop`)},e.prototype.avgPool=function(e,t){return q(`avgPool`)},e.prototype.avgPoolBackprop=function(e,t,n){return q(`avgPoolBackprop`)},e.prototype.avgPool3d=function(e,t){return q(`avgPool3d`)},e.prototype.avgPool3dBackprop=function(e,t,n){return q(`avgPool3dBackprop`)},e.prototype.maxPool3d=function(e,t){return q(`maxPool3d`)},e.prototype.maxPool3dBackprop=function(e,t,n,r){return q(`maxPool3dBackprop`)},e.prototype.reshape=function(e,t){return q(`reshape`)},e.prototype.cast=function(e,t){return q(`cast`)},e.prototype.tile=function(e,t){return q(`tile`)},e.prototype.pad=function(e,t,n){return q(`pad`)},e.prototype.transpose=function(e,t){return q(`transpose`)},e.prototype.gather=function(e,t,n){return q(`gather`)},e.prototype.gatherND=function(e,t){return q(`gatherND`)},e.prototype.scatterND=function(e,t,n){return q(`scatterND`)},e.prototype.batchToSpaceND=function(e,t,n){return q(`batchToSpaceND`)},e.prototype.spaceToBatchND=function(e,t,n){return q(`spaceToBatchND`)},e.prototype.resizeBilinear=function(e,t,n,r){return q(`resizeBilinear`)},e.prototype.resizeBilinearBackprop=function(e,t,n){return q(`resizeBilinearBackprop`)},e.prototype.resizeNearestNeighbor=function(e,t,n,r){return q(`resizeNearestNeighbor`)},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){return q(`resizeNearestNeighborBackprop`)},e.prototype.batchNormalization=function(e,t,n,r,i,a){return q(`batchNormalization`)},e.prototype.localResponseNormalization4D=function(e,t,n,r,i){return q(`localResponseNormalization4D`)},e.prototype.LRNGrad=function(e,t,n,r,i,a,o){return q(`LRNGrad`)},e.prototype.multinomial=function(e,t,n,r){return q(`multinomial`)},e.prototype.oneHot=function(e,t,n,r){return q(`oneHot`)},e.prototype.cumsum=function(e,t,n,r){return q(`cumsum`)},e.prototype.nonMaxSuppression=function(e,t,n,r,i){return q(`nonMaxSuppression`)},e.prototype.fft=function(e){return q(`fft`)},e.prototype.ifft=function(e){return q(`ifft`)},e.prototype.complex=function(e,t){return q(`complex`)},e.prototype.real=function(e){return q(`real`)},e.prototype.imag=function(e){return q(`imag`)},e.prototype.cropAndResize=function(e,t,n,r,i,a){return q(`cropAndResize`)},e.prototype.depthToSpace=function(e,t,n){return q(`depthToSpace`)},e.prototype.split=function(e,t,n){return q(`split`)},e.prototype.sparseToDense=function(e,t,n,r){return q(`sparseToDense`)},e.prototype.diag=function(e){return q(`diag`)},e.prototype.fill=function(e,t,n){return q(`fill`)},e.prototype.onesLike=function(e){return q(`onesLike`)},e.prototype.zerosLike=function(e){return q(`zerosLike`)},e.prototype.linspace=function(e,t,n){return q(`linspace`)},e.prototype.dispose=function(){return q(`dispose`)},e}();function q(e){throw Error(`'`+e+`' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}function oi(e,t){for(var n=e.length,r=[],i=0;i<n;i++){var a=n-1-i,o=e[a]||1;(t[t.length-1-i]||1)>1&&o===1&&r.unshift(a)}return r}function si(e,t){for(var n=[],r=0;r<t.length;r++){var i=e[e.length-r-1],a=t.length-r-1,o=t[a];(i==null||i===1&&o>1)&&n.unshift(a)}return n}function J(e,t){for(var n=[],r=Math.max(e.length,t.length),i=0;i<r;i++){var a=e[e.length-i-1];a??=1;var o=t[t.length-i-1];if(o??=1,a===1)n.unshift(o);else if(o===1)n.unshift(a);else{if(a!==o)throw Error(`Operands could not be broadcast together with shapes `+e+` and `+t+`.`);n.unshift(a)}}return n}function ci(e,t,n,r,i,a,o){o===void 0&&(o=`channelsLast`);var s,c=pi(t),l=c[0],u=c[1];if(o===`channelsLast`)s=[l,u,e[3],e[3]];else{if(o!==`channelsFirst`)throw Error(`Unknown dataFormat `+o);s=[l,u,e[1],e[1]]}return ui(e,s,n,r,i,a,!1,o)}function li(e,t,n,r,i,a,o){o===void 0&&(o=`NDHWC`);var s,c,l=mi(t),u=l[0],d=l[1],f=l[2];if(o===`NDHWC`)c=`channelsLast`,s=[u,d,f,e[4],e[4]];else{if(o!==`NCDHW`)throw Error(`Unknown dataFormat `+o);c=`channelsFirst`,s=[u,d,f,e[1],e[1]]}return di(e,s,n,r,i,!1,c,a)}function ui(e,t,n,r,i,a,o,s){o===void 0&&(o=!1),s===void 0&&(s=`channelsLast`);var c=[-1,-1,-1,-1],l=c[0],u=c[1],d=c[2],f=c[3];if(s===`channelsLast`)l=e[0],u=e[1],d=e[2],f=e[3];else{if(s!==`channelsFirst`)throw Error(`Unknown dataFormat `+s);l=e[0],f=e[1],u=e[2],d=e[3]}var p,m=t[0],h=t[1],g=t[3],_=pi(n),v=_[0],y=_[1],b=pi(r),x=b[0],S=b[1],C=hi(m,x),w=hi(h,S),T=function(e,t,n,r,i,a,o,s){var c,l,u;if(typeof e==`number`){c={top:e,bottom:e,left:e,right:e,type:e===0?`VALID`:`NUMBER`};var d=function(e,t,n,r,i){r??=fi(e,t,n);var a=e[0],o=e[1],s=gi((a-t+2*r)/n+1,i);O(P(s),(function(){return`The output # of rows (`+s+`) must be an integer. Change the stride and/or zero pad parameters`}));var c=gi((o-t+2*r)/n+1,i);return O(P(c),(function(){return`The output # of columns (`+c+`) must be an integer. Change the stride and/or zero pad parameters`})),[s,c]}([t,n],a,r,e,s);l=d[0],u=d[1]}else if(e===`same`){l=Math.ceil(t/r),u=Math.ceil(n/i);var f=Math.max(0,(l-1)*r+a-t),p=Math.max(0,(u-1)*i+o-n),m=Math.floor(f/2),h=f-m,g=Math.floor(p/2);c={top:m,bottom:h,left:g,right:p-g,type:`SAME`}}else{if(e!==`valid`)throw Error(`Unknown padding parameter: `+e);c={top:0,bottom:0,left:0,right:0,type:`VALID`},l=Math.ceil((t-a+1)/r),u=Math.ceil((n-o+1)/i)}return{padInfo:c,outHeight:l,outWidth:u}}(i,u,d,v,y,C,w,a),E=T.padInfo,D=T.outHeight,k=T.outWidth,A=o?g*f:g;return s===`channelsFirst`?p=[l,A,D,k]:s===`channelsLast`&&(p=[l,D,k,A]),{batchSize:l,dataFormat:s,inHeight:u,inWidth:d,inChannels:f,outHeight:D,outWidth:k,outChannels:A,padInfo:E,strideHeight:v,strideWidth:y,filterHeight:m,filterWidth:h,effectiveFilterHeight:C,effectiveFilterWidth:w,dilationHeight:x,dilationWidth:S,inShape:e,outShape:p,filterShape:t}}function di(e,t,n,r,i,a,o,s){a===void 0&&(a=!1),o===void 0&&(o=`channelsLast`);var c=[-1,-1,-1,-1,-1],l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];if(o===`channelsLast`)l=e[0],u=e[1],d=e[2],f=e[3],p=e[4];else{if(o!==`channelsFirst`)throw Error(`Unknown dataFormat `+o);l=e[0],p=e[1],u=e[2],d=e[3],f=e[4]}var m,h=t[0],g=t[1],_=t[2],v=t[4],y=mi(n),b=y[0],x=y[1],S=y[2],C=mi(r),w=C[0],T=C[1],E=C[2],D=hi(h,w),k=hi(g,T),A=hi(_,E),j=function(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,m;if(typeof e==`number`){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?`VALID`:`NUMBER`};var h=function(e,t,n,r,i,a){i??=fi(e,t,r);var o=e[0],s=e[1],c=e[2],l=gi((o-t+2*i)/r+1,a);O(P(l),(function(){return`The output # of depths (`+l+`) must be an integer. Change the stride and/or zero pad parameters`}));var u=gi((s-t+2*i)/r+1,a);O(P(u),(function(){return`The output # of rows (`+u+`) must be an integer. Change the stride and/or zero pad parameters`}));var d=gi((c-t+2*i)/r+1,a);return O(P(d),(function(){return`The output # of columns (`+d+`) must be an integer. Change the stride and/or zero pad parameters`})),[l,u,d,n]}([t,n,r,1],s,1,i,e,u);f=h[0],p=h[1],m=h[2]}else if(e===`same`){f=Math.ceil(t/i),p=Math.ceil(n/a),m=Math.ceil(r/o);var g=(f-1)*i+s-t,_=(p-1)*a+c-n,v=(m-1)*o+l-r,y=Math.floor(g/2),b=g-y,x=Math.floor(_/2),S=_-x,C=Math.floor(v/2);d={top:x,bottom:S,left:C,right:v-C,front:y,back:b,type:`SAME`}}else{if(e!==`valid`)throw Error(`Unknown padding parameter: `+e);d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:`VALID`},f=Math.ceil((t-s+1)/i),p=Math.ceil((n-c+1)/a),m=Math.ceil((r-l+1)/o)}return{padInfo:d,outDepth:f,outHeight:p,outWidth:m}}(i,u,d,f,b,x,S,D,k,A,s),M=j.padInfo,N=j.outDepth,F=j.outHeight,I=j.outWidth,ee=a?v*p:v;return o===`channelsFirst`?m=[l,ee,N,F,I]:o===`channelsLast`&&(m=[l,N,F,I,ee]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:d,inWidth:f,inChannels:p,outDepth:N,outHeight:F,outWidth:I,outChannels:ee,padInfo:M,strideDepth:b,strideHeight:x,strideWidth:S,filterDepth:h,filterHeight:g,filterWidth:_,effectiveFilterDepth:D,effectiveFilterHeight:k,effectiveFilterWidth:A,dilationDepth:w,dilationHeight:T,dilationWidth:E,inShape:e,outShape:m,filterShape:t}}function fi(e,t,n,r){r===void 0&&(r=1);var i=hi(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)}function pi(e){return typeof e==`number`?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function mi(e){return typeof e==`number`?[e,e,e]:e}function hi(e,t){return t<=1?e:e+(e-1)*(t-1)}function gi(e,t){if(!t)return e;switch(t){case`round`:return Math.round(e);case`ceil`:return Math.ceil(e);case`floor`:return Math.floor(e);default:throw Error(`Unknown roundingMode `+t)}}function _i(e){var t=pi(e),n=t[0],r=t[1],i=t[2];return n===1&&r===1&&i===1}function vi(e,t){return _i(e)||_i(t)}function yi(e){if(e===`NHWC`)return`channelsLast`;if(e===`NCHW`)return`channelsFirst`;throw Error(`Unknown dataFormat `+e)}function bi(e,t,n){if(t===`complex64`){if(e.dtype===`complex64`)return e.clone();var r=Rn(e.shape),i=e.toFloat(),a=n.complex(i,r);return r.dispose(),i.dispose(),a}if(!ce(e.dtype,t))return z.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype===`complex64`){var o=n.real(e);return a=o.cast(t),o.dispose(),a}if(t===`int32`)return n.int(e);if(t===`bool`){var s=G(0,e.dtype);return a=n.notEqual(e,s),s.dispose(),a}throw Error(`Error in Cast: failed to cast `+e.dtype+` to `+t)}function xi(e,t){return z.makeTensorFromDataId(e.dataId,t,e.dtype)}function Si(e,t,n){var r=(t-e)/(n-1),i=Se(n,`float32`);i[0]=e;for(var a=1;a<i.length;a++)i[a]=i[a-1]+r;return An(i,`float32`)}Object.freeze({castTensor:bi,reshapeTensor:xi,linspaceImpl:Si,upcastType:Ye,axesAreInnerMostDims:hn,combineLocations:gn,computeOutAndReduceShapes:_n,expandShapeToKeepDim:vn,assertAxesAreInnerMostDims:yn,getAxesPermutation:bn,getUndoAxesPermutation:xn,getInnerMostAxes:Sn,getBroadcastDims:oi,getReductionAxes:si,assertAndGetBroadcastShape:J,assertParamsConsistent:Cn,computeOutShape:wn,computePool2DInfo:ci,computePool3DInfo:li,computeConv2DInfo:ui,computeConv3DInfo:di,computeDefaultPad:fi,tupleValuesAreOne:_i,eitherStridesOrDilationsAreOne:vi,convertConv2DDataFormat:yi,PARALLELIZE_THRESHOLD:Hr,computeOptimalWindowSize:Ur});function Ci(e,t){if(e.length!==t.length)throw Error(`Cannot merge real and imag arrays of different lengths. real:`+e.length+`, imag: `+t.length+`.`);for(var n=new Float32Array(2*e.length),r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function wi(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Ti(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function Ei(e,t,n){var r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}function Di(e,t,n){var r=function(e,t,n){return function(e,t,n){for(var r=0,i=e.length,a=0,o=!1;r<i;){var s=n(t,e[a=r+(i-r>>>1)]);s>0?r=a+1:(i=a,o=!s)}return o?r:-r-1}(e,t,n||Oi)}(e,t,n),i=r<0?-(r+1):r;e.splice(i,0,t)}function Oi(e,t){return e>t?1:e<t?-1:0}function ki(e,t,n,r,i){return ji(e,t,n,r,i,0).selectedIndices}function Ai(e,t,n,r,i,a){var o=ji(e,t,n,r,i,a,!0);return o.numValidOutputs.dispose(),{selectedIndices:o.selectedIndices,selectedScores:o.selectedScores}}function ji(e,t,n,r,i,a,o,s){o===void 0&&(o=!1),s===void 0&&(s=!1);for(var c=Array.from(t).map((function(e,t){return{score:e,boxIndex:t,suppressBeginIndex:0}})).filter((function(e){return e.score>i})).sort(Pi),l=a>0?-.5/a:0,u=[],d=[];u.length<n&&c.length>0;){var f=c.pop(),p=f.score,m=f.boxIndex,h=f.suppressBeginIndex;if(p<i)break;for(var g=!1,_=u.length-1;_>=h;--_){var v=Mi(e,m,u[_]);if(v>=r){g=!0;break}if(f.score*=Ni(r,l,v),f.score<=i)break}f.suppressBeginIndex=u.length,g||(f.score===p?(u.push(m),d.push(f.score)):f.score>i&&Di(c,f,Pi))}var y=u.length;return s&&(u.fill(0,y),d.fill(0,y)),{selectedIndices:An(u,`int32`),selectedScores:An(d,`float32`),numValidOutputs:G(y,`int32`)}}function Mi(e,t,n){var r=e.subarray(4*t,4*t+4),i=e.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),u=Math.min(i[1],i[3]),d=Math.max(i[0],i[2]),f=Math.max(i[1],i[3]),p=(s-a)*(c-o),m=(d-l)*(f-u);if(p<=0||m<=0)return 0;var h=Math.max(a,l),g=Math.max(o,u),_=Math.min(s,d),v=Math.min(c,f),y=Math.max(_-h,0)*Math.max(v-g,0);return y/(p+m-y)}function Ni(e,t,n){var r=Math.exp(t*n*n);return n<=e?r:0}function Pi(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}function Fi(e,t,n){var r=Array(e.rank).fill(0),i=e.shape.slice();return t.map((function(t){i[n]=t;var a=e.slice(r,i);return r[n]+=t,a}))}function Ii(e,t){for(var n=Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];var i=K(n,e.dtype);for(r=0;r<i.values.length;++r){for(var a=i.indexToLoc(r),o=Array(e.rank),s=0;s<o.length;s++)o[s]=a[s]%e.shape[s];var c=e.locToIndex(o);i.values[r]=e.values[c]}return i.toTensor()}function Li(e,t,n,r,i){for(var a=t[t.length-1],o=[e.length/a,a],s=o[0],c=o[1],l=ie(n,s*r),u=ie(`int32`,s*r),d=0;d<s;d++){for(var f=d*c,p=e.subarray(f,f+c),m=[],h=0;h<p.length;h++)m.push({value:p[h],index:h});m.sort((function(e,t){return t.value-e.value}));var g=d*r,_=l.subarray(g,g+r),v=u.subarray(g,g+r);for(h=0;h<r;h++)_[h]=m[h].value,v[h]=m[h].index}var y=t.slice();return y[y.length-1]=r,[On(l,y,n),On(u,y,`int32`)]}function Ri(e,t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(r);var i=K(e,`int32`),a=K([n.length,e.length],`int32`);for(r=0;r<n.length;r++){var o=i.indexToLoc(n[r]),s=r*e.length;a.values.set(o,s)}return a.toTensor()}var zi=function(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((function(e,t){return`T`+t}));var n=[];this.variableNames.forEach((function(e){n.push(`float v`+e+` = get`+e+`AtOutCoords();`)}));var r=this.variableNames.map((function(e){return`v`+e})).join(` + `);this.userCode=`
|
|
14
|
+
`+r.shape})),I(o%(t*t)==0,(function(){return`Dimension size must be evenly divisible by `+t*t+` but is `+o+` for depthToSpace with input shape `+r.shape})),V.runKernelFunc((function(e){return e.depthToSpace(r,t,n)}),{$x:r})}}),Dr=K({expandDims_:function(e,t){t===void 0&&(t=0);var n=G(e,`x`,`expandDims`,null);I(t<=n.rank,(function(){return`Axis must be <= rank of the tensor`}));var r=n.shape.slice();return t<0&&(I(-(n.rank+1)<=t,(function(){return`Axis must be in the interval [`+-(n.rank+1)+`, `+n.rank+`]`})),t=n.rank+t+1),r.splice(t,0,1),Br(n,r)}}),Or=K({eye_:function(e,t,n,r){r===void 0&&(r=`float32`),t??=e;for(var i=J([e,t],r),a=e<=t?e:t,o=0;o<a;++o)i.set(1,o,o);var s=i.toTensor().as2D(e,t);if(n==null)return s;if(n.length===1)return Wr(Dr(s,0),[n[0],1,1]);if(n.length===2)return Wr(Dr(Dr(s,0),0),[n[0],n[1],1,1]);if(n.length===3)return Wr(Dr(Dr(Dr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw Error(`eye() currently supports only 1D and 2D batchShapes, but received `+n.length+`D.`)}}),kr=K({multinomial_:function(e,t,n,r){r===void 0&&(r=!1);var i=G(e,`logits`,`multinomial`),a=i.size,o=i.rank;if(a<2)throw Error(`Error in multinomial: you need at least 2 outcomes, but got `+a+`.`);if(o>2)throw Error(`Rank of probabilities must be 1 or 2, but is `+o);n||=Math.random();var s=o===1?i.as2D(1,-1):i,c=V.runKernelFunc((function(e){return e.multinomial(s,r,t,n)}),{logits2D:s});return o===1?c.as1D():c}}),Ar=K({oneHot_:function(e,t,n,r){if(n===void 0&&(n=1),r===void 0&&(r=0),t<2)throw Error(`Error in oneHot: depth must be >=2, but it is `+t);var i=G(e,`indices`,`oneHot`,`int32`),a=i.shape.concat([t]);return i=i.flatten(),V.runKernelFunc((function(e){return e.oneHot(i,t,n,r)}),{$indices:i},(function(e){return{$indices:function(){return Xn(i.shape,`float32`)}}})).reshape(a)}}),jr=K({pad_:function(e,t,n){n===void 0&&(n=0);var r=G(e,`x`,`pad`);if(r.rank===0)throw Error(`pad(scalar) is not defined. Pass non-scalar to pad`);var i={paddings:t,constantValue:n};return V.runKernelFunc((function(e){return e.pad(r,t,n)}),{x:r},(function(e){var n=t.map((function(e){return e[0]}));return{x:function(){return e.slice(n,r.shape)}}}),`PadV2`,i)}}),Mr=K({pad1d_:function(e,t,n){return n===void 0&&(n=0),I(t.length===2,(function(){return`Invalid number of paddings. Must be length of 2.`})),jr(e,[t],n)}}),Nr=K({pad2d_:function(e,t,n){return n===void 0&&(n=0),I(t.length===2&&t[0].length===2&&t[1].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),jr(e,t,n)}}),Pr=K({pad3d_:function(e,t,n){return n===void 0&&(n=0),I(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),jr(e,t,n)}}),Fr=K({pad4d_:function(e,t,n){return n===void 0&&(n=0),I(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,(function(){return`Invalid number of paddings. Must be length of 2 each.`})),jr(e,t,n)}}),Ir=K({rand_:function(e,t,n){var r=R(e),i=null;if(n==null||n===`float32`)i=new Float32Array(r);else if(n===`int32`)i=new Int32Array(r);else{if(n!==`bool`)throw Error(`Unknown data type `+n);i=new Uint8Array(r)}for(var a=0;a<r;a++)i[a]=t();return V.makeTensor(i,e,n)}}),Lr=K({randomNormal_:function(e,t,n,r,i){if(t===void 0&&(t=0),n===void 0&&(n=1),r!=null&&r===`bool`)throw Error(`Unsupported data type `+r);for(var a=new _r(t,n,r,!1,i),o=J(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Rr=K({randomGamma_:function(e,t,n,r,i){if(n===void 0&&(n=1),r===void 0&&(r=`float32`),n??=1,r??=`float32`,r!==`float32`&&r!==`int32`)throw Error(`Unsupported data type `+r);for(var a=new vr(t,n,r,i),o=J(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),zr=K({randomUniform_:function(e,t,n,r,i){t===void 0&&(t=0),n===void 0&&(n=1),r===void 0&&(r=`float32`);for(var a=J(e,r),o=new yr(t,n,null,i),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),Br=K({reshape_:function(e,t){var n=G(e,`x`,`reshape`,null);t=pe(t,n.size),I(n.size===R(t),(function(){return`new shape and old shape must have the same number of elements.`}));var r={shape:t};return V.runKernelFunc((function(e){return e.reshape(n,t)}),{x:n},(function(e){return{x:function(){return e.reshape(n.shape)}}}),`Reshape`,r)}}),Vr=K({spaceToBatchND_:function(e,t,n){var r=G(e,`x`,`spaceToBatchND`);return I(r.rank>=1+t.length,(function(){return`input rank `+r.rank+` should be > than [blockShape] `+t.length})),I(n.length===t.length,(function(){return`paddings.shape[0] `+n.length+` must be equal to [blockShape] `+t.length})),I(r.shape.reduce((function(e,r,i){return i>0&&i<=t.length?e&&(r+n[i-1][0]+n[i-1][1])%t[i-1]==0:e}),!0),(function(){return`input spatial dimensions `+r.shape.slice(1)+` with paddings `+n.toString()+` must be divisible by blockShapes `+t.toString()})),V.runKernelFunc((function(e){return e.spaceToBatchND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}}))}}),Hr=K({squeeze_:function(e,t){var n=G(e,`x`,`squeeze`);return Br(n,he(n.shape,t).newShape)}}),Ur=K({stack_:function(e,t){t===void 0&&(t=0);var n=En(e,`tensors`,`stack`);if(I(n.length>=1,(function(){return`Pass at least one tensor to tf.stack`})),n.length===1)return n[0].expandDims(t);var r=n[0].rank,i=n[0].shape,a=n[0].dtype;return I(t<=r,(function(){return`Axis must be <= rank of the tensor`})),n.forEach((function(e){L(i,e.shape,`All tensors passed to stack must have matching shapes`)})),n.forEach((function(e){I(a===e.dtype,(function(){return`All tensors passed to stack must have matching dtypes`}))})),nr(n.map((function(e){return e.expandDims(t)})),t)}}),Wr=K({tile_:function(e,t){var n=G(e,`x`,`tile`,null);I(n.rank===t.length,(function(){return`Error in transpose: rank of input `+n.rank+` must match length of reps `+t+`.`}));var r=[n],i={reps:t};return V.runKernelFunc((function(e,r){var i=e.tile(n,t);return r([n]),i}),{x:n},(function(e,n){var r=n[0];return{x:function(){var n=tr(r);if(r.rank===1)for(var i=0;i<t[0];++i)n=n.add(e.slice([i*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(i=0;i<t[0];++i)for(var a=0;a<t[1];++a)n=n.add(e.slice([i*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(i=0;i<t[0];++i)for(a=0;a<t[1];++a)for(var o=0;o<t[2];++o)n=n.add(e.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(r.rank!==4)throw Error(`Gradient for tile operation is not implemented for rank-`+r.rank+` tensors yet.`);for(i=0;i<t[0];++i)for(a=0;a<t[1];++a)for(o=0;o<t[2];++o)for(var s=0;s<t[3];++s)n=n.add(e.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),`Tile`,i,r)}}),Gr=K({truncatedNormal_:function(e,t,n,r,i){if(t===void 0&&(t=0),n===void 0&&(n=1),r!=null&&r===`bool`)throw Error(`Unsupported data type `+r);for(var a=new _r(t,n,r,!0,i),o=J(e,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Kr=K({unstack_:function(e,t){t===void 0&&(t=0),t||=0;var n=G(e,`x`,`unstack`);I(t>=-n.shape.length&&t<n.shape.length,(function(){return`Axis = `+t+` is not in [-`+n.shape.length+`, `+n.shape.length+`)`})),t<0&&(t+=n.shape.length);var r={axis:t};return V.runKernelFunc((function(e){return e.unstack(n,t)}),{x:n},(function(e){return{x:function(){return Ur(e,t)}}}),`Unpack`,r)}}),qr=function(e,t){return w(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u,d;return T(this,(function(f){switch(f.label){case 0:return n=G(e,`x`,`setdiff1d`),r=G(t,`y`,`setdiff1d`),I(n.dtype===r.dtype,(function(){return`x and y should have the same dtype, but got x (`+n.dtype+`) and y (`+r.dtype+`).`})),I(n.rank===1,(function(){return`x should be 1D tensor, but got x (`+n.shape+`).`})),I(r.rank===1,(function(){return`y should be 1D tensor, but got y (`+r.shape+`).`})),[4,n.data()];case 1:return i=f.sent(),[4,r.data()];case 2:for(a=f.sent(),o=new Set(a),s=0,u=0;u<i.length;u++)o.has(i[u])||s++;for(c=new Xe([s],n.dtype),l=new Xe([s],`int32`),u=0,d=0;u<i.length;u++)o.has(i[u])||(c.values[d]=i[u],l.values[d]=u,d++);return[2,[c.toTensor(),l.toTensor()]]}}))}))};function Jr(e,t,n,r){r===void 0&&(r=!0);var i=[];if(r)(i=i.concat(t.slice(0))).push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);for(var a=t.length,o=0;o<a;++o)i=i.concat([e[o+1]/t[o],t[o]]);i=i.concat(e.slice(a+1))}return i}function Yr(e,t,n){n===void 0&&(n=!0);var r=[];if(n){r.push(t);for(var i=t+1;i<e;++i)i<=2*t?(r.push(i),r.push(i-(t+1))):r.push(i)}else{var a=[],o=[];for(i=1;i<e;++i)i>=2*t+1||i%2==1?o.push(i):a.push(i);r.push.apply(r,a),r.push(0),r.push.apply(r,o)}return r}function Xr(e,t,n,r){r===void 0&&(r=!0);var i=[];r?i.push(e[0]/n):i.push(e[0]*n);for(var a=1;a<e.length;++a)a<=t.length?r?i.push(t[a-1]*e[a]):i.push(e[a]/t[a-1]):i.push(e[a]);return i}function Zr(e,t){for(var n=[0],r=0;r<t;++r)n.push(e[r][0]);return n}function Qr(e,t,n){for(var r=e.slice(0,1),i=0;i<n;++i)r.push(e[i+1]-t[i][0]-t[i][1]);return r}function $r(e,t){if(e.rank<1)throw Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was `+e.rank+`.`);if(t.rank<1)throw Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was `+t.rank+`.`);if(t.dtype!==`int32`)throw Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was `+t.dtype+`.`);if(t.shape[t.rank-1]>e.rank)throw Error(`index innermost dimension length must be <= tensor rank; saw: `+t.shape[t.rank-1]+` vs. `+e.rank);if(e.size===0)throw Error(`Requested more than 0 entries, but input is empty. Input shape: `+e.shape+`.`);for(var n=t.shape,r=n[n.length-1],i=1,a=0;a<n.length-1;++a)i*=n[a];var o=e.shape,s=n.slice();s.pop();var c=1;for(a=r;a<e.rank;++a)c*=o[a],s.push(o[a]);var l=Ae(e.shape).map((function(e){return e/c})).concat([1]).slice(0,r);return[s,i,c,l]}Object.freeze({prepareAndValidate:$r});var ei=30;function ti(e){return e<=ei?e:ke(e,Math.floor(Math.sqrt(e)))}function ni(e,t,n){var r=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: `+n.shape+`, indices.shape: `+t.shape+`, shape: `+e+`, sliceDim: `+r+`, and batchDim: `+i+`.`;if(n.rank<i)throw Error(a+` update.rank < `+i+`. `);if(e.length<r+(n.rank-i))throw Error(a+` Output shape length < `+(r+(n.rank-i)));if(n.rank!==i+e.length-r)throw Error(a+` update.rank != `+(i+e.length-r));for(var o=0;o<i;++o)if(n.shape[o]!==t.shape[o])throw Error(a+` updates.shape[`+o+`] (`+n.shape[o]+`) != indices.shape[`+o+`] (`+t.shape[o]+`).`);for(o=0;o<n.rank-i;++o)if(n.shape[o+i]!==e[o+r])throw Error(a+` updates.shape[`+(o+i)+`] (`+n.shape[o+i]+`) != shape[`+(o+i)+`] (`+e[o+i]+`)`)}function ri(e,t,n){if(t.rank<1)throw Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was `+t.rank+`.`);if(e.rank<1)throw Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was `+e.rank+`.`);if(t.dtype!==`int32`)throw Error(`The dtype of 'indices' should be int32, but got dtype: `+t.dtype);if(n.length<1)throw Error(`Output rank must be greater or equal to 1, but got shape: `+n);if(n.length===0){if(t.size===0)throw Error(`Indices specified for empty output. indices shape: `+t.shape);if(e.size===0)throw Error(`Updates specified for empty output. updates shape: `+e.shape)}ni(n,t,e)}function ii(e,t,n){for(var r=t.shape.length,i=r>1?t.shape[r-1]:1,a=n.length,o=1,s=i;s<a;++s)o*=n[s];var c=i<1?1:i;return{sliceRank:i,numUpdates:R(t.shape)/c,sliceSize:o,strides:Ae(n.slice(0,i)).concat([1]),outputSize:R(n)}}Object.freeze({validateUpdateShape:ni,validateInput:ri,calculateShapes:ii});function ai(e,t,n){I(e.rank===t.length,(function(){return`Error in slice`+e.rank+`D: Length of begin `+t+` must match the rank of the array (`+e.rank+`).`})),I(e.rank===n.length,(function(){return`Error in slice`+e.rank+`D: Length of size `+n+` must match the rank of the array (`+e.rank+`).`}));for(var r=function(r){I(t[r]+n[r]<=e.shape[r],(function(){return`Error in slice`+e.rank+`D: begin[`+r+`] + size[`+r+`] (`+(t[r]+n[r])+`) would overflow input.shape[`+r+`] (`+e.shape[r]+`)`}))},i=0;i<e.rank;++i)r(i)}function oi(e){for(var t=[],n=0;e>0;)1&e&&t.push(n),e/=2,n++;return t}function si(e,t,n){for(var r=[],i=0;i<e.length;i++)r[i]=Math.ceil((t[i]-e[i])/n[i]);return r}function ci(e,t,n,r,i){var a=t[i],o=n[i]||1;(e&1<<i||a==null)&&(a=o>0?-(2**53-1):2**53-1);var s=r[i];return a<0&&(a+=s),a=re(0,a,s-1)}function li(e,t,n,r,i){var a=t[i],o=n[i]||1;(e&1<<i||a==null)&&(a=o>0?2**53-1:-(2**53-1));var s=r[i];return a<0&&(a+=s),a=o>0?re(0,a,s):re(-1,a,s-1)}function ui(e,t,n){for(var r=n.length,i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(i=r+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function di(e,t){for(var n=e.length>0?e[e.length-1]:1,r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}Object.freeze({assertParamsValid:ai,maskToAxes:oi,computeOutShape:si,startForAxis:ci,stopForAxis:li,isSliceContinous:ui,computeFlatOffset:di});function fi(e,t){I(Oe(e),(function(){return`The f passed in variableGrads(f) must be a function`})),I(t==null||Array.isArray(t)&&t.every((function(e){return e instanceof at})),(function(){return`The varList passed in variableGrads(f, varList) must be an array of variables`}));var n=t!=null;if(!n)for(var r in t=[],V.registeredVariables)t.push(V.registeredVariables[r]);var i=n?t.filter((function(e){return!e.trainable})):null,a=t.length;I((t=t.filter((function(e){return e.trainable}))).length>0,(function(){return`variableGrads() expects at least one of the input variables to be trainable, but none of the `+a+` variables is trainable.`}));var o=V.gradients(e,t,null,!0),s=o.value,c=o.grads;I(c.some((function(e){return e!=null})),(function(){return`Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().`})),I(s.rank===0,(function(){return`The f passed in variableGrads(f) must return a scalar, but it returned a rank-`+s.rank+` tensor`}));var l={};return t.forEach((function(e,t){c[t]!=null&&(l[e.name]=c[t])})),i?.forEach((function(e){return l[e.name]=null})),{value:s,grads:l}}function pi(e){return V.customGrad(e)}var mi=K({softmax_:function(e,t){t===void 0&&(t=-1);var n=G(e,`logits`,`softmax`,`float32`);if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank `+n.rank+` and dim was `+t);return V.runKernelFunc((function(e,r){var i=e.softmax(n,t);return r([i]),i}),{logits:n},(function(e,n){var r=n[0],i=e.mul(r);return{logits:function(){return i.sub(i.sum([t],!0).mul(r))}}}),`Softmax`,{dim:t},[],[!0])}}),hi=K({logSoftmax_:function(e,t){t===void 0&&(t=-1);var n=G(e,`logits`,`logSoftmax`);if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank `+n.rank+` and axis was `+t);return pi((function(e,n){var r=e.max(t,!0),i=e.sub(r),a=i.toFloat().sub(i.exp().sum(t,!0).log());return n([a]),{value:a,gradFunc:function(e,n){var r=n[0].exp();return e.sub(e.sum(t,!0).mul(r))}}}))(n)}}),gi=function(){function e(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}return e.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},e.prototype.set=function(e,t){this.dataIdsCount++,this.data.set(e,t)},e.prototype.has=function(e){return this.data.has(e)},e.prototype.delete=function(e){return this.dataIdsCount--,this.data.delete(e)},e.prototype.numDataIds=function(){return this.dataIdsCount},e}(),_i=function(){function e(){}return e.prototype.time=function(e){return Y(`time`)},e.prototype.read=function(e){return Y(`read`)},e.prototype.readSync=function(e){return Y(`readSync`)},e.prototype.numDataIds=function(){return Y(`numDataIds`)},e.prototype.disposeData=function(e){return Y(`disposeData`)},e.prototype.write=function(e,t,n){return Y(`write`)},e.prototype.move=function(e,t,n,r){return Y(`move`)},e.prototype.memory=function(){return Y(`memory`)},e.prototype.floatPrecision=function(){return Y(`floatPrecision`)},e.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},e.prototype.batchMatMul=function(e,t,n,r){return Y(`batchMatMul`)},e.prototype.fusedBatchMatMul=function(e){return e.a,e.b,e.transposeA,e.transposeB,e.bias,e.activation,e.preluActivationWeights,Y(`fusedBatchMatMul`)},e.prototype.slice=function(e,t,n){return Y(`slice`)},e.prototype.stridedSlice=function(e,t,n,r){return Y(`stridedSlice`)},e.prototype.unstack=function(e,t){return Y(`unstack`)},e.prototype.reverse=function(e,t){return Y(`reverse`)},e.prototype.concat=function(e,t){return Y(`concat`)},e.prototype.neg=function(e){return Y(`neg`)},e.prototype.add=function(e,t){return Y(`add`)},e.prototype.addN=function(e){return Y(`addN`)},e.prototype.subtract=function(e,t){return Y(`subtract`)},e.prototype.multiply=function(e,t){return Y(`multiply`)},e.prototype.realDivide=function(e,t){return Y(`realDivide`)},e.prototype.floorDiv=function(e,t){return Y(`floorDiv`)},e.prototype.sum=function(e,t){return Y(`sum`)},e.prototype.prod=function(e,t){return Y(`prod`)},e.prototype.unsortedSegmentSum=function(e,t,n){return Y(`unsortedSegmentSum`)},e.prototype.argMin=function(e,t){return Y(`argMin`)},e.prototype.argMax=function(e,t){return Y(`argMax`)},e.prototype.equal=function(e,t){return Y(`equal`)},e.prototype.notEqual=function(e,t){return Y(`notEqual`)},e.prototype.less=function(e,t){return Y(`less`)},e.prototype.lessEqual=function(e,t){return Y(`lessEqual`)},e.prototype.greater=function(e,t){return Y(`greater`)},e.prototype.greaterEqual=function(e,t){return Y(`greaterEqual`)},e.prototype.logicalNot=function(e){return Y(`logicalNot`)},e.prototype.logicalAnd=function(e,t){return Y(`logicalAnd`)},e.prototype.logicalOr=function(e,t){return Y(`logicalOr`)},e.prototype.where=function(e){return Y(`where`)},e.prototype.select=function(e,t,n){return Y(`select`)},e.prototype.topk=function(e,t,n){return Y(`topk`)},e.prototype.min=function(e,t){return Y(`min`)},e.prototype.minimum=function(e,t){return Y(`minimum`)},e.prototype.mod=function(e,t){return Y(`mod`)},e.prototype.max=function(e,t){return Y(`max`)},e.prototype.maximum=function(e,t){return Y(`maximum`)},e.prototype.all=function(e,t){return Y(`all`)},e.prototype.any=function(e,t){return Y(`any`)},e.prototype.squaredDifference=function(e,t){return Y(`squaredDifference`)},e.prototype.ceil=function(e){return Y(`ceil`)},e.prototype.floor=function(e){return Y(`floor`)},e.prototype.round=function(e){return Y(`round`)},e.prototype.sign=function(e){return Y(`sign`)},e.prototype.isNaN=function(e){return Y(`isNaN`)},e.prototype.isInf=function(e){return Y(`isInf`)},e.prototype.isFinite=function(e){return Y(`isFinite`)},e.prototype.pow=function(e,t){return Y(`pow`)},e.prototype.exp=function(e){return Y(`exp`)},e.prototype.expm1=function(e){return Y(`expm1`)},e.prototype.softmax=function(e,t){return Y(`softmax`)},e.prototype.log=function(e){return Y(`log`)},e.prototype.log1p=function(e){return Y(`log1p`)},e.prototype.sqrt=function(e){return Y(`sqrt`)},e.prototype.rsqrt=function(e){return Y(`rsqrt`)},e.prototype.square=function(e){return Y(`square`)},e.prototype.reciprocal=function(e){return Y(`reciprocal`)},e.prototype.relu=function(e){return Y(`relu`)},e.prototype.relu6=function(e){return Y(`relu6`)},e.prototype.prelu=function(e,t){return Y(`prelu`)},e.prototype.elu=function(e){return Y(`elu`)},e.prototype.eluDer=function(e,t){return Y(`eluDer`)},e.prototype.selu=function(e){return Y(`selu`)},e.prototype.int=function(e){return Y(`int`)},e.prototype.clip=function(e,t,n){return Y(`clip`)},e.prototype.abs=function(e){return Y(`abs`)},e.prototype.complexAbs=function(e){return Y(`complexAbs`)},e.prototype.sigmoid=function(e){return Y(`sigmoid`)},e.prototype.softplus=function(e){return Y(`softplus`)},e.prototype.sin=function(e){return Y(`sin`)},e.prototype.cos=function(e){return Y(`cos`)},e.prototype.tan=function(e){return Y(`tan`)},e.prototype.asin=function(e){return Y(`asin`)},e.prototype.acos=function(e){return Y(`acos`)},e.prototype.atan=function(e){return Y(`atan`)},e.prototype.atan2=function(e,t){return Y(`atan2`)},e.prototype.sinh=function(e){return Y(`sinh`)},e.prototype.cosh=function(e){return Y(`cosh`)},e.prototype.tanh=function(e){return Y(`tanh`)},e.prototype.asinh=function(e){return Y(`asinh`)},e.prototype.acosh=function(e){return Y(`acosh`)},e.prototype.atanh=function(e){return Y(`atanh`)},e.prototype.erf=function(e){return Y(`erf`)},e.prototype.step=function(e,t){return Y(`step`)},e.prototype.fusedConv2d=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,Y(`fusedConv2d`)},e.prototype.conv2d=function(e,t,n){return Y(`conv2d`)},e.prototype.conv2dDerInput=function(e,t,n){return Y(`conv2dDerInput`)},e.prototype.conv2dDerFilter=function(e,t,n){return Y(`conv2dDerFilter`)},e.prototype.fusedDepthwiseConv2D=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,Y(`fusedDepthwiseConv2D`)},e.prototype.depthwiseConv2D=function(e,t,n){return Y(`depthwiseConv2D`)},e.prototype.depthwiseConv2DDerInput=function(e,t,n){return Y(`depthwiseConv2DDerInput`)},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){return Y(`depthwiseConv2DDerFilter`)},e.prototype.conv3d=function(e,t,n){return Y(`conv3d`)},e.prototype.conv3dDerInput=function(e,t,n){return Y(`conv3dDerInput`)},e.prototype.conv3dDerFilter=function(e,t,n){return Y(`conv3dDerFilter`)},e.prototype.maxPool=function(e,t){return Y(`maxPool`)},e.prototype.maxPoolBackprop=function(e,t,n,r){return Y(`maxPoolBackprop`)},e.prototype.avgPool=function(e,t){return Y(`avgPool`)},e.prototype.avgPoolBackprop=function(e,t,n){return Y(`avgPoolBackprop`)},e.prototype.avgPool3d=function(e,t){return Y(`avgPool3d`)},e.prototype.avgPool3dBackprop=function(e,t,n){return Y(`avgPool3dBackprop`)},e.prototype.maxPool3d=function(e,t){return Y(`maxPool3d`)},e.prototype.maxPool3dBackprop=function(e,t,n,r){return Y(`maxPool3dBackprop`)},e.prototype.reshape=function(e,t){return Y(`reshape`)},e.prototype.cast=function(e,t){return Y(`cast`)},e.prototype.tile=function(e,t){return Y(`tile`)},e.prototype.pad=function(e,t,n){return Y(`pad`)},e.prototype.transpose=function(e,t){return Y(`transpose`)},e.prototype.gather=function(e,t,n){return Y(`gather`)},e.prototype.gatherND=function(e,t){return Y(`gatherND`)},e.prototype.scatterND=function(e,t,n){return Y(`scatterND`)},e.prototype.batchToSpaceND=function(e,t,n){return Y(`batchToSpaceND`)},e.prototype.spaceToBatchND=function(e,t,n){return Y(`spaceToBatchND`)},e.prototype.resizeBilinear=function(e,t,n,r){return Y(`resizeBilinear`)},e.prototype.resizeBilinearBackprop=function(e,t,n){return Y(`resizeBilinearBackprop`)},e.prototype.resizeNearestNeighbor=function(e,t,n,r){return Y(`resizeNearestNeighbor`)},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){return Y(`resizeNearestNeighborBackprop`)},e.prototype.batchNormalization=function(e,t,n,r,i,a){return Y(`batchNormalization`)},e.prototype.localResponseNormalization4D=function(e,t,n,r,i){return Y(`localResponseNormalization4D`)},e.prototype.LRNGrad=function(e,t,n,r,i,a,o){return Y(`LRNGrad`)},e.prototype.multinomial=function(e,t,n,r){return Y(`multinomial`)},e.prototype.oneHot=function(e,t,n,r){return Y(`oneHot`)},e.prototype.cumsum=function(e,t,n,r){return Y(`cumsum`)},e.prototype.nonMaxSuppression=function(e,t,n,r,i){return Y(`nonMaxSuppression`)},e.prototype.fft=function(e){return Y(`fft`)},e.prototype.ifft=function(e){return Y(`ifft`)},e.prototype.complex=function(e,t){return Y(`complex`)},e.prototype.real=function(e){return Y(`real`)},e.prototype.imag=function(e){return Y(`imag`)},e.prototype.cropAndResize=function(e,t,n,r,i,a){return Y(`cropAndResize`)},e.prototype.depthToSpace=function(e,t,n){return Y(`depthToSpace`)},e.prototype.split=function(e,t,n){return Y(`split`)},e.prototype.sparseToDense=function(e,t,n,r){return Y(`sparseToDense`)},e.prototype.diag=function(e){return Y(`diag`)},e.prototype.fill=function(e,t,n){return Y(`fill`)},e.prototype.onesLike=function(e){return Y(`onesLike`)},e.prototype.zerosLike=function(e){return Y(`zerosLike`)},e.prototype.linspace=function(e,t,n){return Y(`linspace`)},e.prototype.dispose=function(){return Y(`dispose`)},e}();function Y(e){throw Error(`'`+e+`' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}function vi(e,t){for(var n=e.length,r=[],i=0;i<n;i++){var a=n-1-i,o=e[a]||1;(t[t.length-1-i]||1)>1&&o===1&&r.unshift(a)}return r}function yi(e,t){for(var n=[],r=0;r<t.length;r++){var i=e[e.length-r-1],a=t.length-r-1,o=t[a];(i==null||i===1&&o>1)&&n.unshift(a)}return n}function bi(e,t){for(var n=[],r=Math.max(e.length,t.length),i=0;i<r;i++){var a=e[e.length-i-1];a??=1;var o=t[t.length-i-1];if(o??=1,a===1)n.unshift(o);else if(o===1)n.unshift(a);else{if(a!==o)throw Error(`Operands could not be broadcast together with shapes `+e+` and `+t+`.`);n.unshift(a)}}return n}function xi(e,t,n,r,i,a,o){o===void 0&&(o=`channelsLast`);var s,c=Ei(t),l=c[0],u=c[1];if(o===`channelsLast`)s=[l,u,e[3],e[3]];else{if(o!==`channelsFirst`)throw Error(`Unknown dataFormat `+o);s=[l,u,e[1],e[1]]}return Ci(e,s,n,r,i,a,!1,o)}function Si(e,t,n,r,i,a,o){o===void 0&&(o=`NDHWC`);var s,c,l=Di(t),u=l[0],d=l[1],f=l[2];if(o===`NDHWC`)c=`channelsLast`,s=[u,d,f,e[4],e[4]];else{if(o!==`NCDHW`)throw Error(`Unknown dataFormat `+o);c=`channelsFirst`,s=[u,d,f,e[1],e[1]]}return wi(e,s,n,r,i,!1,c,a)}function Ci(e,t,n,r,i,a,o,s){o===void 0&&(o=!1),s===void 0&&(s=`channelsLast`);var c=[-1,-1,-1,-1],l=c[0],u=c[1],d=c[2],f=c[3];if(s===`channelsLast`)l=e[0],u=e[1],d=e[2],f=e[3];else{if(s!==`channelsFirst`)throw Error(`Unknown dataFormat `+s);l=e[0],f=e[1],u=e[2],d=e[3]}var p,m=t[0],h=t[1],g=t[3],_=Ei(n),v=_[0],y=_[1],b=Ei(r),x=b[0],S=b[1],C=Oi(m,x),w=Oi(h,S),T=function(e,t,n,r,i,a,o,s){var c,l,u;if(typeof e==`number`){c={top:e,bottom:e,left:e,right:e,type:e===0?`VALID`:`NUMBER`};var d=function(e,t,n,r,i){r??=Ti(e,t,n);var a=e[0],o=e[1],s=ki((a-t+2*r)/n+1,i);I(ce(s),(function(){return`The output # of rows (`+s+`) must be an integer. Change the stride and/or zero pad parameters`}));var c=ki((o-t+2*r)/n+1,i);return I(ce(c),(function(){return`The output # of columns (`+c+`) must be an integer. Change the stride and/or zero pad parameters`})),[s,c]}([t,n],a,r,e,s);l=d[0],u=d[1]}else if(e===`same`){l=Math.ceil(t/r),u=Math.ceil(n/i);var f=Math.max(0,(l-1)*r+a-t),p=Math.max(0,(u-1)*i+o-n),m=Math.floor(f/2),h=f-m,g=Math.floor(p/2);c={top:m,bottom:h,left:g,right:p-g,type:`SAME`}}else{if(e!==`valid`)throw Error(`Unknown padding parameter: `+e);c={top:0,bottom:0,left:0,right:0,type:`VALID`},l=Math.ceil((t-a+1)/r),u=Math.ceil((n-o+1)/i)}return{padInfo:c,outHeight:l,outWidth:u}}(i,u,d,v,y,C,w,a),E=T.padInfo,D=T.outHeight,O=T.outWidth,k=o?g*f:g;return s===`channelsFirst`?p=[l,k,D,O]:s===`channelsLast`&&(p=[l,D,O,k]),{batchSize:l,dataFormat:s,inHeight:u,inWidth:d,inChannels:f,outHeight:D,outWidth:O,outChannels:k,padInfo:E,strideHeight:v,strideWidth:y,filterHeight:m,filterWidth:h,effectiveFilterHeight:C,effectiveFilterWidth:w,dilationHeight:x,dilationWidth:S,inShape:e,outShape:p,filterShape:t}}function wi(e,t,n,r,i,a,o,s){a===void 0&&(a=!1),o===void 0&&(o=`channelsLast`);var c=[-1,-1,-1,-1,-1],l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];if(o===`channelsLast`)l=e[0],u=e[1],d=e[2],f=e[3],p=e[4];else{if(o!==`channelsFirst`)throw Error(`Unknown dataFormat `+o);l=e[0],p=e[1],u=e[2],d=e[3],f=e[4]}var m,h=t[0],g=t[1],_=t[2],v=t[4],y=Di(n),b=y[0],x=y[1],S=y[2],C=Di(r),w=C[0],T=C[1],E=C[2],D=Oi(h,w),O=Oi(g,T),k=Oi(_,E),A=function(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,m;if(typeof e==`number`){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?`VALID`:`NUMBER`};var h=function(e,t,n,r,i,a){i??=Ti(e,t,r);var o=e[0],s=e[1],c=e[2],l=ki((o-t+2*i)/r+1,a);I(ce(l),(function(){return`The output # of depths (`+l+`) must be an integer. Change the stride and/or zero pad parameters`}));var u=ki((s-t+2*i)/r+1,a);I(ce(u),(function(){return`The output # of rows (`+u+`) must be an integer. Change the stride and/or zero pad parameters`}));var d=ki((c-t+2*i)/r+1,a);return I(ce(d),(function(){return`The output # of columns (`+d+`) must be an integer. Change the stride and/or zero pad parameters`})),[l,u,d,n]}([t,n,r,1],s,1,i,e,u);f=h[0],p=h[1],m=h[2]}else if(e===`same`){f=Math.ceil(t/i),p=Math.ceil(n/a),m=Math.ceil(r/o);var g=(f-1)*i+s-t,_=(p-1)*a+c-n,v=(m-1)*o+l-r,y=Math.floor(g/2),b=g-y,x=Math.floor(_/2),S=_-x,C=Math.floor(v/2);d={top:x,bottom:S,left:C,right:v-C,front:y,back:b,type:`SAME`}}else{if(e!==`valid`)throw Error(`Unknown padding parameter: `+e);d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:`VALID`},f=Math.ceil((t-s+1)/i),p=Math.ceil((n-c+1)/a),m=Math.ceil((r-l+1)/o)}return{padInfo:d,outDepth:f,outHeight:p,outWidth:m}}(i,u,d,f,b,x,S,D,O,k,s),j=A.padInfo,M=A.outDepth,N=A.outHeight,P=A.outWidth,F=a?v*p:v;return o===`channelsFirst`?m=[l,F,M,N,P]:o===`channelsLast`&&(m=[l,M,N,P,F]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:d,inWidth:f,inChannels:p,outDepth:M,outHeight:N,outWidth:P,outChannels:F,padInfo:j,strideDepth:b,strideHeight:x,strideWidth:S,filterDepth:h,filterHeight:g,filterWidth:_,effectiveFilterDepth:D,effectiveFilterHeight:O,effectiveFilterWidth:k,dilationDepth:w,dilationHeight:T,dilationWidth:E,inShape:e,outShape:m,filterShape:t}}function Ti(e,t,n,r){r===void 0&&(r=1);var i=Oi(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)}function Ei(e){return typeof e==`number`?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Di(e){return typeof e==`number`?[e,e,e]:e}function Oi(e,t){return t<=1?e:e+(e-1)*(t-1)}function ki(e,t){if(!t)return e;switch(t){case`round`:return Math.round(e);case`ceil`:return Math.ceil(e);case`floor`:return Math.floor(e);default:throw Error(`Unknown roundingMode `+t)}}function Ai(e){var t=Ei(e),n=t[0],r=t[1],i=t[2];return n===1&&r===1&&i===1}function ji(e,t){return Ai(e)||Ai(t)}function Mi(e){if(e===`NHWC`)return`channelsLast`;if(e===`NCHW`)return`channelsFirst`;throw Error(`Unknown dataFormat `+e)}function Ni(e,t,n){if(t===`complex64`){if(e.dtype===`complex64`)return e.clone();var r=Xn(e.shape),i=e.toFloat(),a=n.complex(i,r);return r.dispose(),i.dispose(),a}if(!be(e.dtype,t))return V.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype===`complex64`){var o=n.real(e);return a=o.cast(t),o.dispose(),a}if(t===`int32`)return n.int(e);if(t===`bool`){var s=q(0,e.dtype);return a=n.notEqual(e,s),s.dispose(),a}throw Error(`Error in Cast: failed to cast `+e.dtype+` to `+t)}function Pi(e,t){return V.makeTensorFromDataId(e.dataId,t,e.dtype)}function Fi(e,t,n){var r=(t-e)/(n-1),i=Pe(n,`float32`);i[0]=e;for(var a=1;a<i.length;a++)i[a]=i[a-1]+r;return Hn(i,`float32`)}Object.freeze({castTensor:Ni,reshapeTensor:Pi,linspaceImpl:Fi,upcastType:st,axesAreInnerMostDims:Dn,combineLocations:On,computeOutAndReduceShapes:kn,expandShapeToKeepDim:An,assertAxesAreInnerMostDims:jn,getAxesPermutation:Mn,getUndoAxesPermutation:Nn,getInnerMostAxes:Pn,getBroadcastDims:vi,getReductionAxes:yi,assertAndGetBroadcastShape:bi,assertParamsConsistent:Fn,computeOutShape:In,computePool2DInfo:xi,computePool3DInfo:Si,computeConv2DInfo:Ci,computeConv3DInfo:wi,computeDefaultPad:Ti,tupleValuesAreOne:Ai,eitherStridesOrDilationsAreOne:ji,convertConv2DDataFormat:Mi,PARALLELIZE_THRESHOLD:ei,computeOptimalWindowSize:ti});function Ii(e,t){if(e.length!==t.length)throw Error(`Cannot merge real and imag arrays of different lengths. real:`+e.length+`, imag: `+t.length+`.`);for(var n=new Float32Array(2*e.length),r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function Li(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Ri(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function zi(e,t,n){var r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}function Bi(e,t,n){var r=function(e,t,n){return function(e,t,n){for(var r=0,i=e.length,a=0,o=!1;r<i;){var s=n(t,e[a=r+(i-r>>>1)]);s>0?r=a+1:(i=a,o=!s)}return o?r:-r-1}(e,t,n||Vi)}(e,t,n),i=r<0?-(r+1):r;e.splice(i,0,t)}function Vi(e,t){return e>t?1:e<t?-1:0}function Hi(e,t,n,r,i){return Wi(e,t,n,r,i,0).selectedIndices}function Ui(e,t,n,r,i,a){var o=Wi(e,t,n,r,i,a,!0);return o.numValidOutputs.dispose(),{selectedIndices:o.selectedIndices,selectedScores:o.selectedScores}}function Wi(e,t,n,r,i,a,o,s){o===void 0&&(o=!1),s===void 0&&(s=!1);for(var c=Array.from(t).map((function(e,t){return{score:e,boxIndex:t,suppressBeginIndex:0}})).filter((function(e){return e.score>i})).sort(qi),l=a>0?-.5/a:0,u=[],d=[];u.length<n&&c.length>0;){var f=c.pop(),p=f.score,m=f.boxIndex,h=f.suppressBeginIndex;if(p<i)break;for(var g=!1,_=u.length-1;_>=h;--_){var v=Gi(e,m,u[_]);if(v>=r){g=!0;break}if(f.score*=Ki(r,l,v),f.score<=i)break}f.suppressBeginIndex=u.length,g||(f.score===p?(u.push(m),d.push(f.score)):f.score>i&&Bi(c,f,qi))}var y=u.length;return s&&(u.fill(0,y),d.fill(0,y)),{selectedIndices:Hn(u,`int32`),selectedScores:Hn(d,`float32`),numValidOutputs:q(y,`int32`)}}function Gi(e,t,n){var r=e.subarray(4*t,4*t+4),i=e.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),u=Math.min(i[1],i[3]),d=Math.max(i[0],i[2]),f=Math.max(i[1],i[3]),p=(s-a)*(c-o),m=(d-l)*(f-u);if(p<=0||m<=0)return 0;var h=Math.max(a,l),g=Math.max(o,u),_=Math.min(s,d),v=Math.min(c,f),y=Math.max(_-h,0)*Math.max(v-g,0);return y/(p+m-y)}function Ki(e,t,n){var r=Math.exp(t*n*n);return n<=e?r:0}function qi(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}function Ji(e,t,n){var r=Array(e.rank).fill(0),i=e.shape.slice();return t.map((function(t){i[n]=t;var a=e.slice(r,i);return r[n]+=t,a}))}function Yi(e,t){for(var n=Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];var i=J(n,e.dtype);for(r=0;r<i.values.length;++r){for(var a=i.indexToLoc(r),o=Array(e.rank),s=0;s<o.length;s++)o[s]=a[s]%e.shape[s];var c=e.locToIndex(o);i.values[r]=e.values[c]}return i.toTensor()}function Xi(e,t,n,r,i){for(var a=t[t.length-1],o=[e.length/a,a],s=o[0],c=o[1],l=ge(n,s*r),u=ge(`int32`,s*r),d=0;d<s;d++){for(var f=d*c,p=e.subarray(f,f+c),m=[],h=0;h<p.length;h++)m.push({value:p[h],index:h});m.sort((function(e,t){return t.value-e.value}));var g=d*r,_=l.subarray(g,g+r),v=u.subarray(g,g+r);for(h=0;h<r;h++)_[h]=m[h].value,v[h]=m[h].index}var y=t.slice();return y[y.length-1]=r,[Bn(l,y,n),Bn(u,y,`int32`)]}function Zi(e,t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(r);var i=J(e,`int32`),a=J([n.length,e.length],`int32`);for(r=0;r<n.length;r++){var o=i.indexToLoc(n[r]),s=r*e.length;a.values.set(o,s)}return a.toTensor()}var Qi=function(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((function(e,t){return`T`+t}));var n=[];this.variableNames.forEach((function(e){n.push(`float v`+e+` = get`+e+`AtOutCoords();`)}));var r=this.variableNames.map((function(e){return`v`+e})).join(` + `);this.userCode=`
|
|
15
15
|
void main() {
|
|
16
16
|
`+n.join(`
|
|
17
17
|
`)+`
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
float result = `+r+`;
|
|
20
20
|
setOutput(result);
|
|
21
21
|
}
|
|
22
|
-
`}
|
|
22
|
+
`},$i=function(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((function(e,t){return`T`+t}));var n=[];this.variableNames.forEach((function(e){n.push(`vec4 v`+e+` = get`+e+`AtOutCoords();`)}));var r=this.variableNames.map((function(e){return`v`+e})).join(` + `);this.userCode=`
|
|
23
23
|
void main() {
|
|
24
24
|
`+n.join(`
|
|
25
25
|
`)+`
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
vec4 result = `+r+`;
|
|
28
28
|
setOutput(result);
|
|
29
29
|
}
|
|
30
|
-
`},
|
|
30
|
+
`},ea=function(e,t,n){this.variableNames=[`A`];var r=e.windowSize,i=e.batchSize,a=e.inSize,o=Math.ceil(a/r);n||this.variableNames.push(`bestIndicesA`),this.outputShape=[i,o];var s=t===`max`?`>`:`<`,c=n?`inOffset + i;`:`round(getBestIndicesA(batch, inOffset + i));`;this.userCode=`
|
|
31
31
|
void main() {
|
|
32
32
|
ivec2 coords = getOutputCoords();
|
|
33
33
|
int batch = coords[0];
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
}
|
|
48
48
|
setOutput(float(bestIndex));
|
|
49
49
|
}
|
|
50
|
-
`};function
|
|
50
|
+
`};function ta(e,t){return[`x`,`y`,`z`,`w`,`u`,`v`].slice(0,t).map((function(t){return e+`.`+t}))}function na(e,t){return t===1?[e]:ta(e,t)}function ra(){var e,t,n,r,i,a,o,s,c,l;return O().getNumber(`WEBGL_VERSION`)===2?(e=`#version 300 es`,t=`in`,n=`out`,r=`in`,i=`texture`,a=`outputColor`,o=`out vec4 outputColor;`,s=`
|
|
51
51
|
bool isnan_custom(float val) {
|
|
52
52
|
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
|
|
53
53
|
}
|
|
@@ -92,11 +92,11 @@
|
|
|
92
92
|
ivec4 round(vec4 value) {
|
|
93
93
|
return ivec4(floor(value + vec4(0.5)));
|
|
94
94
|
}
|
|
95
|
-
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:i,output:a,defineOutput:o,defineSpecialNaN:s,defineSpecialInf:c,defineRound:l}}function
|
|
95
|
+
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:i,output:a,defineOutput:o,defineSpecialNaN:s,defineSpecialInf:c,defineRound:l}}function ia(e,t,n){n===void 0&&(n=`index`);var r=Ae(t);return r.map((function(t,i){return`int `+e[i]+` = `+n+` / `+t+`; `+(i===r.length-1?`int `+e[i+1]+` = `+n+` - `+e[i]+` * `+t:`index -= `+e[i]+` * `+t)+`;`})).join(``)}function aa(e){var t=Ae(e).map((function(e){return e.toString()}));return`
|
|
96
96
|
int getFlatIndex(ivec3 coords) {
|
|
97
97
|
return coords.x * `+t[0]+` + coords.y * `+t[1]+` + coords.z;
|
|
98
98
|
}
|
|
99
|
-
`}var
|
|
99
|
+
`}var oa=`
|
|
100
100
|
const float FLOAT_MAX = 1.70141184e38;
|
|
101
101
|
const float FLOAT_MIN = 1.17549435e-38;
|
|
102
102
|
|
|
@@ -135,9 +135,9 @@
|
|
|
135
135
|
|
|
136
136
|
return c / 255.0;
|
|
137
137
|
}
|
|
138
|
-
`;function
|
|
139
|
-
`),c=e.map((function(e){return function(e,t,n){n===void 0&&(n=!1);var r=``;r+=n?
|
|
140
|
-
`);var f=``;f=s<2&&o>0?`coords`:e.shapeInfo.logicalShape.map((function(e,t){return`coords.`+d[t+u]})).join(`, `);var p=`return outputValue;`,m=
|
|
138
|
+
`;function sa(e,t,n,r){var i=[];e.forEach((function(e){var t=R(e.shapeInfo.logicalShape);e.shapeInfo.isUniform?i.push(`uniform float `+e.name+(t>1?`[`+t+`]`:``)+`;`):(i.push(`uniform sampler2D `+e.name+`;`),i.push(`uniform int offset`+e.name+`;`))}));var a,o,s=i.join(`
|
|
139
|
+
`),c=e.map((function(e){return function(e,t,n){n===void 0&&(n=!1);var r=``;r+=n?la(e):ca(e);var i=e.shapeInfo.logicalShape,a=t.logicalShape;return i.length<=a.length&&(r+=n?function(e,t){var n,r=e.name,i=r.charAt(0).toUpperCase()+r.slice(1),a=`get`+i+`AtOutCoords`,o=e.shapeInfo.logicalShape.length,s=t.logicalShape.length,c=vi(e.shapeInfo.logicalShape,t.logicalShape),l=ga(s),u=s-o,d=[`x`,`y`,`z`,`w`,`u`,`v`];n=o===0?``:s<2&&c.length>=1?`coords = 0;`:c.map((function(e){return`coords.`+d[e+u]+` = 0;`})).join(`
|
|
140
|
+
`);var f=``;f=s<2&&o>0?`coords`:e.shapeInfo.logicalShape.map((function(e,t){return`coords.`+d[t+u]})).join(`, `);var p=`return outputValue;`,m=R(e.shapeInfo.logicalShape)===1,h=R(t.logicalShape)===1;if(o!==1||m||h){if(m&&!h)p=s===1?`
|
|
141
141
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
142
142
|
`:`
|
|
143
143
|
return vec4(outputValue.x);
|
|
@@ -150,11 +150,11 @@
|
|
|
150
150
|
vec4 outputValue = get`+i+`(`+f+`);
|
|
151
151
|
`+p+`
|
|
152
152
|
}
|
|
153
|
-
`}(e,t):function(e,t){var n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),i=`get`+r+`AtOutCoords`,a=t.texShape,o=e.shapeInfo.texShape,s=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&s===c&&e.shapeInfo.flatOffset==null&&
|
|
153
|
+
`}(e,t):function(e,t){var n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),i=`get`+r+`AtOutCoords`,a=t.texShape,o=e.shapeInfo.texShape,s=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&s===c&&e.shapeInfo.flatOffset==null&&z(o,a))return`
|
|
154
154
|
float `+i+`() {
|
|
155
155
|
return sampleTexture(`+n+`, resultUV);
|
|
156
156
|
}
|
|
157
|
-
`;var l,u=
|
|
157
|
+
`;var l,u=ga(c),d=vi(e.shapeInfo.logicalShape,t.logicalShape),f=c-s,p=[`x`,`y`,`z`,`w`,`u`,`v`];l=s===0?``:c<2&&d.length>=1?`coords = 0;`:d.map((function(e){return`coords.`+p[e+f]+` = 0;`})).join(`
|
|
158
158
|
`);var m=``;return m=c<2&&s>0?`coords`:e.shapeInfo.logicalShape.map((function(e,t){return`coords.`+p[t+f]})).join(`, `),`
|
|
159
159
|
float `+i+`() {
|
|
160
160
|
`+u+` coords = getOutputCoords();
|
|
@@ -162,7 +162,7 @@
|
|
|
162
162
|
return get`+r+`(`+m+`);
|
|
163
163
|
}
|
|
164
164
|
`}(e,t)),r}(e,t,r)})).join(`
|
|
165
|
-
`),l=t.texShape,u=
|
|
165
|
+
`),l=t.texShape,u=ra(),d=function(e){return`
|
|
166
166
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
167
167
|
return `+e.texture2D+`(textureSampler, uv).r;
|
|
168
168
|
}
|
|
@@ -221,9 +221,9 @@
|
|
|
221
221
|
return fract((p3.x + p3.y) * p3.z);
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
-
`+
|
|
225
|
-
`+
|
|
226
|
-
|
|
224
|
+
`+ua+`
|
|
225
|
+
`+da+`
|
|
226
|
+
`+fa+`
|
|
227
227
|
`}(u);return t.isPacked?(a=function(e,t){switch(e.length){case 0:return`
|
|
228
228
|
int getOutputCoords() {
|
|
229
229
|
return 0;
|
|
@@ -242,7 +242,7 @@
|
|
|
242
242
|
vec2(`+n[0]+`, `+n[1]+`));
|
|
243
243
|
return 2 * (resTexRC.x * `+n[1]+` + resTexRC.y);
|
|
244
244
|
}
|
|
245
|
-
`}(0,t);case 2:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(
|
|
245
|
+
`}(0,t);case 2:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(z(e,t))return`
|
|
246
246
|
ivec2 getOutputCoords() {
|
|
247
247
|
return 2 * ivec2(resultUV.yx * vec2(`+n[0]+`, `+n[1]+`));
|
|
248
248
|
}
|
|
@@ -312,7 +312,7 @@
|
|
|
312
312
|
vec2(`+t[0]+`, `+t[1]+`));
|
|
313
313
|
return resTexRC.x * `+t[1]+` + resTexRC.y;
|
|
314
314
|
}
|
|
315
|
-
`}(0,t);case 2:return function(e,t){return
|
|
315
|
+
`}(0,t);case 2:return function(e,t){return z(e,t)?`
|
|
316
316
|
ivec2 getOutputCoords() {
|
|
317
317
|
return ivec2(resultUV.yx * vec2(`+t[0]+`, `+t[1]+`));
|
|
318
318
|
}
|
|
@@ -339,7 +339,7 @@
|
|
|
339
339
|
int c = index - r * `+e[1]+`;
|
|
340
340
|
return ivec2(r, c);
|
|
341
341
|
}
|
|
342
|
-
`}(e,t);case 3:return n=t,r=
|
|
342
|
+
`}(e,t);case 3:return n=t,r=ia([`r`,`c`,`d`],e),`
|
|
343
343
|
ivec3 getOutputCoords() {
|
|
344
344
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
345
345
|
vec2(`+n[0]+`, `+n[1]+`));
|
|
@@ -347,7 +347,7 @@
|
|
|
347
347
|
`+r+`
|
|
348
348
|
return ivec3(r, c, d);
|
|
349
349
|
}
|
|
350
|
-
`;case 4:return function(e,t){var n=
|
|
350
|
+
`;case 4:return function(e,t){var n=ia([`r`,`c`,`d`,`d2`],e);return`
|
|
351
351
|
ivec4 getOutputCoords() {
|
|
352
352
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
353
353
|
vec2(`+t[0]+`, `+t[1]+`));
|
|
@@ -355,7 +355,7 @@
|
|
|
355
355
|
`+n+`
|
|
356
356
|
return ivec4(r, c, d, d2);
|
|
357
357
|
}
|
|
358
|
-
`}(e,t);case 5:return function(e,t){var n=
|
|
358
|
+
`}(e,t);case 5:return function(e,t){var n=ia([`r`,`c`,`d`,`d2`,`d3`],e);return`
|
|
359
359
|
ivec5 getOutputCoords() {
|
|
360
360
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+t[0]+`,
|
|
361
361
|
`+t[1]+`));
|
|
@@ -367,7 +367,7 @@
|
|
|
367
367
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
368
368
|
return outShape;
|
|
369
369
|
}
|
|
370
|
-
`}(e,t);case 6:return function(e,t){var n=
|
|
370
|
+
`}(e,t);case 6:return function(e,t){var n=ia([`r`,`c`,`d`,`d2`,`d3`,`d4`],e);return`
|
|
371
371
|
ivec6 getOutputCoords() {
|
|
372
372
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
373
373
|
vec2(`+t[0]+`, `+t[1]+`));
|
|
@@ -382,25 +382,25 @@
|
|
|
382
382
|
void setOutput(float val) {
|
|
383
383
|
`+e.output+` = vec4(val, 0, 0, 0);
|
|
384
384
|
}
|
|
385
|
-
`}(u)),r&&(f+=
|
|
386
|
-
`)}function
|
|
385
|
+
`}(u)),r&&(f+=pa),[f,d,o,s,a,c,n].join(`
|
|
386
|
+
`)}function ca(e){var t=e.shapeInfo.logicalShape;switch(t.length){case 0:return function(e){var t=e.name,n=`get`+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float `+n+`() {return `+t+`;}`;var r=e.shapeInfo.texShape,i=r[0],a=r[1];if(i===1&&a===1)return`
|
|
387
387
|
float `+n+`() {
|
|
388
388
|
return sampleTexture(`+t+`, halfCR);
|
|
389
389
|
}
|
|
390
|
-
`;var o=e.shapeInfo.texShape,s=o[0],c=o[1],l=
|
|
390
|
+
`;var o=e.shapeInfo.texShape,s=o[0],c=o[1],l=ma(t);return`
|
|
391
391
|
float `+n+`() {
|
|
392
392
|
vec2 uv = uvFromFlat(`+s+`, `+c+`, `+l+`);
|
|
393
393
|
return sampleTexture(`+t+`, uv);
|
|
394
394
|
}
|
|
395
395
|
`}(e);case 1:return function(e){var t=e.name,n=`get`+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
396
396
|
float `+n+`(int index) {
|
|
397
|
-
`+
|
|
397
|
+
`+ha(e)+`
|
|
398
398
|
}
|
|
399
399
|
`;var r=e.shapeInfo.texShape,i=r[0],a=r[1];if(a===1&&i===1)return`
|
|
400
400
|
float `+n+`(int index) {
|
|
401
401
|
return sampleTexture(`+t+`, halfCR);
|
|
402
402
|
}
|
|
403
|
-
`;var o=
|
|
403
|
+
`;var o=ma(t);return a===1?`
|
|
404
404
|
float `+n+`(int index) {
|
|
405
405
|
vec2 uv = vec2(0.5, (float(index + `+o+`) + 0.5) / `+i+`.0);
|
|
406
406
|
return sampleTexture(`+t+`, uv);
|
|
@@ -415,22 +415,22 @@
|
|
|
415
415
|
vec2 uv = uvFromFlat(`+i+`, `+a+`, index + `+o+`);
|
|
416
416
|
return sampleTexture(`+t+`, uv);
|
|
417
417
|
}
|
|
418
|
-
`}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&
|
|
418
|
+
`}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&z(t,i)){var a=i[0],o=i[1];return`
|
|
419
419
|
float `+r+`(int row, int col) {
|
|
420
420
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+o+`.0, `+a+`.0);
|
|
421
421
|
return sampleTexture(`+n+`, uv);
|
|
422
422
|
}
|
|
423
|
-
`}var s=
|
|
424
|
-
`+
|
|
423
|
+
`}var s=he(t),c=s.newShape,l=s.keptDims,u=c;if(u.length<t.length)return`
|
|
424
|
+
`+ca(_a(e,u))+`
|
|
425
425
|
float `+r+`(int row, int col) {
|
|
426
|
-
return `+r+`(`+
|
|
426
|
+
return `+r+`(`+va([`row`,`col`],l)+`);
|
|
427
427
|
}
|
|
428
428
|
`;if(e.shapeInfo.isUniform)return`
|
|
429
429
|
float `+r+`(int row, int col) {
|
|
430
430
|
int index = round(dot(vec2(row, col), vec2(`+t[1]+`, 1)));
|
|
431
|
-
`+
|
|
431
|
+
`+ha(e)+`
|
|
432
432
|
}
|
|
433
|
-
`;var d=i[0],f=i[1],p=
|
|
433
|
+
`;var d=i[0],f=i[1],p=ma(n);return f===1?`
|
|
434
434
|
float `+r+`(int row, int col) {
|
|
435
435
|
float index = dot(vec3(row, col, `+p+`), vec3(`+t[1]+`, 1, 1));
|
|
436
436
|
vec2 uv = vec2(0.5, (index + 0.5) / `+d+`.0);
|
|
@@ -449,16 +449,16 @@
|
|
|
449
449
|
vec2 uv = uvFromFlat(`+d+`, `+f+`, index);
|
|
450
450
|
return sampleTexture(`+n+`, uv);
|
|
451
451
|
}
|
|
452
|
-
`}(e);case 3:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],a=t[2],o=
|
|
453
|
-
`+
|
|
452
|
+
`}(e);case 3:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],a=t[2],o=he(t),s=o.newShape,c=o.keptDims,l=s;if(l.length<t.length)return`
|
|
453
|
+
`+ca(_a(e,l))+`
|
|
454
454
|
float `+r+`(int row, int col, int depth) {
|
|
455
|
-
return `+r+`(`+
|
|
455
|
+
return `+r+`(`+va([`row`,`col`,`depth`],c)+`);
|
|
456
456
|
}
|
|
457
457
|
`;if(e.shapeInfo.isUniform)return`
|
|
458
458
|
float `+r+`(int row, int col, int depth) {
|
|
459
459
|
int index = round(dot(vec3(row, col, depth),
|
|
460
460
|
vec3(`+i+`, `+a+`, 1)));
|
|
461
|
-
`+
|
|
461
|
+
`+ha(e)+`
|
|
462
462
|
}
|
|
463
463
|
`;var u=e.shapeInfo.texShape,d=u[0],f=u[1],p=e.shapeInfo.flatOffset;if(f===i&&p==null)return`
|
|
464
464
|
float `+r+`(int row, int col, int depth) {
|
|
@@ -475,23 +475,23 @@
|
|
|
475
475
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+f+`.0, `+d+`.0);
|
|
476
476
|
return sampleTexture(`+n+`, uv);
|
|
477
477
|
}
|
|
478
|
-
`;var m=
|
|
478
|
+
`;var m=ma(n);return`
|
|
479
479
|
float `+r+`(int row, int col, int depth) {
|
|
480
480
|
// Explicitly use integer operations as dot() only works on floats.
|
|
481
481
|
int index = row * `+i+` + col * `+a+` + depth + `+m+`;
|
|
482
482
|
vec2 uv = uvFromFlat(`+d+`, `+f+`, index);
|
|
483
483
|
return sampleTexture(`+n+`, uv);
|
|
484
484
|
}
|
|
485
|
-
`}(e);case 4:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],a=t[2]*i,o=t[1]*a,s=
|
|
486
|
-
`+
|
|
485
|
+
`}(e);case 4:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],a=t[2]*i,o=t[1]*a,s=he(t),c=s.newShape,l=s.keptDims;if(c.length<t.length)return`
|
|
486
|
+
`+ca(_a(e,c))+`
|
|
487
487
|
float `+r+`(int row, int col, int depth, int depth2) {
|
|
488
|
-
return `+r+`(`+
|
|
488
|
+
return `+r+`(`+va([`row`,`col`,`depth`,`depth2`],l)+`);
|
|
489
489
|
}
|
|
490
490
|
`;if(e.shapeInfo.isUniform)return`
|
|
491
491
|
float `+r+`(int row, int col, int depth, int depth2) {
|
|
492
492
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
493
493
|
vec4(`+o+`, `+a+`, `+i+`, 1)));
|
|
494
|
-
`+
|
|
494
|
+
`+ha(e)+`
|
|
495
495
|
}
|
|
496
496
|
`;var u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,f=d[0],p=d[1];if(p===o&&u==null)return`
|
|
497
497
|
float `+r+`(int row, int col, int depth, int depth2) {
|
|
@@ -512,7 +512,7 @@
|
|
|
512
512
|
vec2(`+p+`.0, `+f+`.0);
|
|
513
513
|
return sampleTexture(`+n+`, uv);
|
|
514
514
|
}
|
|
515
|
-
`;var m=
|
|
515
|
+
`;var m=ma(n);return`
|
|
516
516
|
float `+r+`(int row, int col, int depth, int depth2) {
|
|
517
517
|
// Explicitly use integer operations as dot() only works on floats.
|
|
518
518
|
int index = row * `+o+` + col * `+a+` +
|
|
@@ -520,10 +520,10 @@
|
|
|
520
520
|
vec2 uv = uvFromFlat(`+f+`, `+p+`, index + `+m+`);
|
|
521
521
|
return sampleTexture(`+n+`, uv);
|
|
522
522
|
}
|
|
523
|
-
`}(e);case 5:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],a=t[3]*i,o=t[2]*a,s=t[1]*o,c=
|
|
524
|
-
`+
|
|
523
|
+
`}(e);case 5:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],a=t[3]*i,o=t[2]*a,s=t[1]*o,c=he(t),l=c.newShape,u=c.keptDims;if(l.length<t.length)return`
|
|
524
|
+
`+ca(_a(e,l))+`
|
|
525
525
|
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
|
|
526
|
-
return `+r+`(`+
|
|
526
|
+
return `+r+`(`+va([`row`,`col`,`depth`,`depth2`,`depth3`],u)+`);
|
|
527
527
|
}
|
|
528
528
|
`;if(e.shapeInfo.isUniform)return`
|
|
529
529
|
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
|
|
@@ -531,7 +531,7 @@
|
|
|
531
531
|
vec4(row, col, depth, depth2),
|
|
532
532
|
vec4(`+s+`, `+o+`, `+a+`, `+i+`)) +
|
|
533
533
|
depth3;
|
|
534
|
-
`+
|
|
534
|
+
`+ha(e)+`
|
|
535
535
|
}
|
|
536
536
|
`;var d=e.shapeInfo.flatOffset,f=e.shapeInfo.texShape,p=f[0],m=f[1];if(m===s&&d==null)return`
|
|
537
537
|
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
|
|
@@ -553,7 +553,7 @@
|
|
|
553
553
|
vec2(`+m+`.0, `+p+`.0);
|
|
554
554
|
return sampleTexture(`+n+`, uv);
|
|
555
555
|
}
|
|
556
|
-
`;var h=
|
|
556
|
+
`;var h=ma(n);return`
|
|
557
557
|
float `+r+`(int row, int col, int depth, int depth2, int depth3) {
|
|
558
558
|
// Explicitly use integer operations as dot() only works on floats.
|
|
559
559
|
int index = row * `+s+` + col * `+o+` + depth * `+a+` +
|
|
@@ -561,11 +561,11 @@
|
|
|
561
561
|
vec2 uv = uvFromFlat(`+p+`, `+m+`, index);
|
|
562
562
|
return sampleTexture(`+n+`, uv);
|
|
563
563
|
}
|
|
564
|
-
`}(e);case 6:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=
|
|
565
|
-
`+
|
|
564
|
+
`}(e);case 6:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=he(t),a=i.newShape,o=i.keptDims;if(a.length<t.length)return`
|
|
565
|
+
`+ca(_a(e,a))+`
|
|
566
566
|
float `+r+`(int row, int col, int depth,
|
|
567
567
|
int depth2, int depth3, int depth4) {
|
|
568
|
-
return `+r+`(`+
|
|
568
|
+
return `+r+`(`+va([`row`,`col`,`depth`,`depth2`,`depth3`,`depth4`],o)+`);
|
|
569
569
|
}
|
|
570
570
|
`;var s=t[5],c=t[4]*s,l=t[3]*c,u=t[2]*l,d=t[1]*u;if(e.shapeInfo.isUniform)return`
|
|
571
571
|
float `+r+`(int row, int col, int depth,
|
|
@@ -576,7 +576,7 @@
|
|
|
576
576
|
dot(
|
|
577
577
|
vec2(depth3, depth4),
|
|
578
578
|
vec2(`+s+`, 1)));
|
|
579
|
-
`+
|
|
579
|
+
`+ha(e)+`
|
|
580
580
|
}
|
|
581
581
|
`;var f=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,m=p[0],h=p[1];if(h===d&&f==null)return`
|
|
582
582
|
float `+r+`(int row, int col, int depth,
|
|
@@ -602,7 +602,7 @@
|
|
|
602
602
|
vec2(`+h+`.0, `+m+`.0);
|
|
603
603
|
return sampleTexture(`+n+`, uv);
|
|
604
604
|
}
|
|
605
|
-
`;var g=
|
|
605
|
+
`;var g=ma(n);return`
|
|
606
606
|
float `+r+`(int row, int col, int depth,
|
|
607
607
|
int depth2, int depth3, int depth4) {
|
|
608
608
|
// Explicitly use integer operations as dot() only works on floats.
|
|
@@ -611,17 +611,17 @@
|
|
|
611
611
|
vec2 uv = uvFromFlat(`+m+`, `+h+`, index);
|
|
612
612
|
return sampleTexture(`+n+`, uv);
|
|
613
613
|
}
|
|
614
|
-
`}(e);default:throw Error(t.length+`-D input sampling is not yet supported`)}}function
|
|
614
|
+
`}(e);default:throw Error(t.length+`-D input sampling is not yet supported`)}}function la(e){var t,n,r;switch(e.shapeInfo.logicalShape.length){case 0:return t=e.name,n=`get`+t.charAt(0).toUpperCase()+t.slice(1),r=ra(),`
|
|
615
615
|
vec4 `+n+`() {
|
|
616
616
|
return `+r.texture2D+`(`+t+`, halfCR);
|
|
617
617
|
}
|
|
618
|
-
`;case 1:return function(e){var t=e.name,n=`get`+t.charAt(0).toUpperCase()+t.slice(1),r=e.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=
|
|
618
|
+
`;case 1:return function(e){var t=e.name,n=`get`+t.charAt(0).toUpperCase()+t.slice(1),r=e.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=ra();return`
|
|
619
619
|
vec4 `+n+`(int index) {
|
|
620
620
|
vec2 uv = packedUVfrom1D(
|
|
621
621
|
`+i[0]+`, `+i[1]+`, index);
|
|
622
622
|
return `+a.texture2D+`(`+t+`, uv);
|
|
623
623
|
}
|
|
624
|
-
`}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,a=i[0],o=i[1],s=
|
|
624
|
+
`}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,a=i[0],o=i[1],s=ra();if(i!=null&&z(t,i))return`
|
|
625
625
|
vec4 `+r+`(int row, int col) {
|
|
626
626
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(`+o+`.0, `+a+`.0);
|
|
627
627
|
|
|
@@ -633,17 +633,17 @@
|
|
|
633
633
|
return `+s.texture2D+`(`+n+`, uv);
|
|
634
634
|
}
|
|
635
635
|
`}(e);case 3:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r=`get`+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1)return`
|
|
636
|
-
`+
|
|
636
|
+
`+la(_a(e,t.slice(1)))+`
|
|
637
637
|
vec4 `+r+`(int b, int row, int col) {
|
|
638
|
-
return `+r+`(`+
|
|
638
|
+
return `+r+`(`+va([`b`,`row`,`col`],[1,2])+`);
|
|
639
639
|
}
|
|
640
|
-
`;var o=a[0],s=a[1],c=Math.ceil(t[2]/2),l=c*Math.ceil(t[1]/2),u=
|
|
640
|
+
`;var o=a[0],s=a[1],c=Math.ceil(t[2]/2),l=c*Math.ceil(t[1]/2),u=ra();return`
|
|
641
641
|
vec4 `+r+`(int b, int row, int col) {
|
|
642
642
|
vec2 uv = packedUVfrom3D(
|
|
643
643
|
`+o+`, `+s+`, `+l+`, `+c+`, b, row, col);
|
|
644
644
|
return `+u.texture2D+`(`+n+`, uv);
|
|
645
645
|
}
|
|
646
|
-
`}(e);default:return function(e){for(var t=e.shapeInfo.logicalShape,n=t.length,r=e.name,i=`get`+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=o[0],c=o[1],l=Math.ceil(t[n-1]/2),u=l*Math.ceil(t[n-2]/2),d=`int b, int row, int col`,f=`b * `+u+` + (row / 2) * `+l+` + (col / 2)`,p=2;p<n-1;p++)d=`int b`+p+`, `+d,u*=t[n-p-1],f=`b`+p+` * `+u+` + `+f;var m=
|
|
646
|
+
`}(e);default:return function(e){for(var t=e.shapeInfo.logicalShape,n=t.length,r=e.name,i=`get`+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=o[0],c=o[1],l=Math.ceil(t[n-1]/2),u=l*Math.ceil(t[n-2]/2),d=`int b, int row, int col`,f=`b * `+u+` + (row / 2) * `+l+` + (col / 2)`,p=2;p<n-1;p++)d=`int b`+p+`, `+d,u*=t[n-p-1],f=`b`+p+` * `+u+` + `+f;var m=ra();return`
|
|
647
647
|
vec4 `+i+`(`+d+`) {
|
|
648
648
|
int index = `+f+`;
|
|
649
649
|
int texR = index / `+c+`;
|
|
@@ -651,7 +651,7 @@
|
|
|
651
651
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(`+c+`, `+s+`);
|
|
652
652
|
return `+m.texture2D+`(`+r+`, uv);
|
|
653
653
|
}
|
|
654
|
-
`}(e)}}var
|
|
654
|
+
`}(e)}}var ua=`
|
|
655
655
|
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
|
|
656
656
|
int texR = index / texNumC;
|
|
657
657
|
int texC = index - texR * texNumC;
|
|
@@ -663,7 +663,7 @@ vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
|
|
|
663
663
|
int texC = texelIndex - texR * texNumC;
|
|
664
664
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
665
665
|
}
|
|
666
|
-
`,
|
|
666
|
+
`,da=`
|
|
667
667
|
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
|
|
668
668
|
int texNumC, int row, int col) {
|
|
669
669
|
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
|
|
@@ -671,7 +671,7 @@ vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
|
|
|
671
671
|
int texC = texelIndex - texR * texNumC;
|
|
672
672
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
673
673
|
}
|
|
674
|
-
|
|
674
|
+
`,fa=`
|
|
675
675
|
vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
676
676
|
int texelsInBatch, int texelsInLogicalRow, int b,
|
|
677
677
|
int row, int col) {
|
|
@@ -680,7 +680,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
680
680
|
int texC = index - texR * texNumC;
|
|
681
681
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
682
682
|
}
|
|
683
|
-
`,
|
|
683
|
+
`,pa=`
|
|
684
684
|
float getChannel(vec4 frag, vec2 innerDims) {
|
|
685
685
|
vec2 modCoord = mod(innerDims, 2.);
|
|
686
686
|
return modCoord.x == 0. ?
|
|
@@ -691,13 +691,13 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
691
691
|
float modCoord = mod(float(dim), 2.);
|
|
692
692
|
return modCoord == 0. ? frag.r : frag.g;
|
|
693
693
|
}
|
|
694
|
-
`;function
|
|
694
|
+
`;function ma(e){return`offset`+e}function ha(e){var t=e.name,n=R(e.shapeInfo.logicalShape);return n<2?`return `+t+`;`:`
|
|
695
695
|
for (int i = 0; i < `+n+`; i++) {
|
|
696
696
|
if (i == index) {
|
|
697
697
|
return `+t+`[i];
|
|
698
698
|
}
|
|
699
699
|
}
|
|
700
|
-
`}function
|
|
700
|
+
`}function ga(e){if(e<=1)return`int`;if(e===2)return`ivec2`;if(e===3)return`ivec3`;if(e===4)return`ivec4`;if(e===5)return`ivec5`;if(e===6)return`ivec6`;throw Error(`GPU for rank `+e+` is not yet supported`)}function _a(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function va(e,t){return t.map((function(t){return e[t]})).join(`, `)}var ya=function(e,t,n,r){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,I(e.length>2,(function(){return`Packed arg`+(n.charAt(0).toUpperCase()+n.slice(1))+` supports only inputs with rank above 2.`}));var i=e[e.length-1],a=Math.ceil(i/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push(`bestIndicesA`);var o,s,c=this.outputShape,l=c.length,u=ga(l),d=na(`coords`,l);if(a===1){var f=ga(s=l+1);o=`
|
|
701
701
|
`+f+` sourceLocR = `+f+`(`+d.join()+`, 0);
|
|
702
702
|
++`+d[l-1]+`;
|
|
703
703
|
`+f+` sourceLocG = `+f+`(`+d.join()+`, 0);
|
|
@@ -713,7 +713,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
713
713
|
`+u+` sourceLocA = coords;
|
|
714
714
|
--`+d[l-1]+`;
|
|
715
715
|
`+u+` sourceLocB = coords;
|
|
716
|
-
--`+d[l-2]+`;`;var p=[`x`,`y`,`z`,`w`,`u`,`v`].slice(0,s),m=`.`+p[s-1],h=p.map((function(e){return`int `+e})),g=
|
|
716
|
+
--`+d[l-2]+`;`;var p=[`x`,`y`,`z`,`w`,`u`,`v`].slice(0,s),m=`.`+p[s-1],h=p.map((function(e){return`int `+e})),g=na(`sourceLocR`,s-1).concat(`inIdx.r`),_=na(`sourceLocG`,s-1).concat(`inIdx.g`),v=na(`sourceLocB`,s-1).concat(`inIdx.b`),y=na(`sourceLocA`,s-1).concat(`inIdx.a`),b=n===`max`?`greaterThan`:`lessThan`,x=r?``:`
|
|
717
717
|
inIdx = round(vec4(getBestIndicesAChannel(`+g.join()+`),
|
|
718
718
|
getBestIndicesAChannel(`+_.join()+`),
|
|
719
719
|
getBestIndicesAChannel(`+v.join()+`),
|
|
@@ -759,7 +759,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
759
759
|
}
|
|
760
760
|
setOutput(bestIndex);
|
|
761
761
|
}
|
|
762
|
-
`},
|
|
762
|
+
`},ba=function(e){this.variableNames=[`dy`],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=s-1-e.padInfo.top,u=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
|
|
763
763
|
const ivec2 pads = ivec2(`+l+`, `+u+`);
|
|
764
764
|
const float avgMultiplier = float(`+d+`);
|
|
765
765
|
|
|
@@ -801,7 +801,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
801
801
|
}
|
|
802
802
|
setOutput(dotProd);
|
|
803
803
|
}
|
|
804
|
-
`},
|
|
804
|
+
`},xa=function(e){this.variableNames=[`dy`],this.outputShape=e.inShape;var t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,i=e.strideDepth,a=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,p=u-1-e.padInfo.front,m=d-1-e.padInfo.top,h=f-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
|
|
805
805
|
const ivec3 pads = ivec3(`+p+`, `+m+`, `+h+`);
|
|
806
806
|
const float avgMultiplier = float(`+g+`);
|
|
807
807
|
|
|
@@ -857,7 +857,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
857
857
|
}
|
|
858
858
|
setOutput(dotProd);
|
|
859
859
|
}
|
|
860
|
-
`},
|
|
860
|
+
`},Sa=function(e,t,n,r,i,a){this.outputShape=[],this.variableNames=[`x`,`mean`,`variance`],bi(e,t),bi(e,n);var o=`0.0`;r!=null&&(bi(e,r),this.variableNames.push(`offset`),o=`getOffsetAtOutCoords()`);var s=`1.0`;i!=null&&(bi(e,i),this.variableNames.push(`scale`),s=`getScaleAtOutCoords()`),this.outputShape=e,this.userCode=`
|
|
861
861
|
void main() {
|
|
862
862
|
float x = getXAtOutCoords();
|
|
863
863
|
float mean = getMeanAtOutCoords();
|
|
@@ -867,7 +867,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
867
867
|
float inv = scale * inversesqrt(variance + float(`+a+`));
|
|
868
868
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
869
869
|
}
|
|
870
|
-
`},
|
|
870
|
+
`},Ca=function(e,t,n,r,i,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=[`x`,`mean`,`variance`],bi(e,t),bi(e,n);var o=`vec4(0.0)`;r!=null&&(bi(e,r),this.variableNames.push(`offset`),o=`getOffsetAtOutCoords()`);var s=`vec4(1.0)`;i!=null&&(bi(e,i),this.variableNames.push(`scale`),s=`getScaleAtOutCoords()`),this.outputShape=e,this.userCode=`
|
|
871
871
|
void main() {
|
|
872
872
|
vec4 offset = `+o+`;
|
|
873
873
|
vec4 scale = `+s+`;
|
|
@@ -880,7 +880,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
880
880
|
|
|
881
881
|
setOutput((x - mean) * inv + offset);
|
|
882
882
|
}
|
|
883
|
-
`},
|
|
883
|
+
`},wa=`return areal * breal - aimag * bimag;`,Ta=`return areal * bimag + aimag * breal;`,Ea=function(e,t,n){this.variableNames=[`AReal`,`AImag`,`BReal`,`BImag`],this.outputShape=bi(t,n),this.userCode=`
|
|
884
884
|
float binaryOpComplex(
|
|
885
885
|
float areal, float aimag, float breal, float bimag) {
|
|
886
886
|
`+e+`
|
|
@@ -893,7 +893,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
893
893
|
float bimag = getBImagAtOutCoords();
|
|
894
894
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
895
895
|
}
|
|
896
|
-
`},
|
|
896
|
+
`},Da=`return a + b;`,Oa=`return a - b;`,ka=`return a * b;`,Aa=`return (a < 0.) ? b * a : a;`,ja=function(e,t,n){this.variableNames=[`A`,`B`],this.outputShape=bi(t,n),this.userCode=`
|
|
897
897
|
float binaryOperation(float a, float b) {
|
|
898
898
|
`+e+`
|
|
899
899
|
}
|
|
@@ -903,20 +903,20 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
903
903
|
float b = getBAtOutCoords();
|
|
904
904
|
setOutput(binaryOperation(a, b));
|
|
905
905
|
}
|
|
906
|
-
`},
|
|
906
|
+
`},Ma=`
|
|
907
907
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
908
908
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
909
|
-
`,
|
|
909
|
+
`,Na=function(e,t,n,r){r===void 0&&(r=!1),this.variableNames=[`A`,`B`],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=bi(t,n);var i=this.outputShape.length,a=``;if(r)if(i===0||R(this.outputShape)===1)a=`
|
|
910
910
|
result.y = 0.;
|
|
911
911
|
result.z = 0.;
|
|
912
912
|
result.w = 0.;
|
|
913
913
|
`;else if(a=`
|
|
914
|
-
`+
|
|
914
|
+
`+ga(i)+` coords = getOutputCoords();
|
|
915
915
|
`,i===1)a+=`
|
|
916
916
|
result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y;
|
|
917
917
|
result.z = 0.;
|
|
918
918
|
result.w = 0.;
|
|
919
|
-
`;else{var o=
|
|
919
|
+
`;else{var o=na(`coords`,i);a+=`
|
|
920
920
|
bool nextRowOutOfBounds =
|
|
921
921
|
(`+o[i-2]+` + 1) >= `+this.outputShape[i-2]+`;
|
|
922
922
|
bool nextColOutOfBounds =
|
|
@@ -938,7 +938,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
938
938
|
|
|
939
939
|
setOutput(result);
|
|
940
940
|
}
|
|
941
|
-
`},
|
|
941
|
+
`},Pa=function(){function e(e){this.variableNames=[`A`],this.outputShape=e,this.userCode=`
|
|
942
942
|
uniform float minVal;
|
|
943
943
|
uniform float maxVal;
|
|
944
944
|
|
|
@@ -951,7 +951,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
951
951
|
|
|
952
952
|
setOutput(clamp(value, minVal, maxVal));
|
|
953
953
|
}
|
|
954
|
-
`}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){n.minLoc??(n.minLoc=r.getUniformLocationNoThrow(i,`minVal`),n.maxLoc=r.getUniformLocationNoThrow(i,`maxVal`)),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),
|
|
954
|
+
`}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){n.minLoc??(n.minLoc=r.getUniformLocationNoThrow(i,`minVal`),n.maxLoc=r.getUniformLocationNoThrow(i,`maxVal`)),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),Fa=function(){function e(e){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
|
|
955
955
|
uniform float minVal;
|
|
956
956
|
uniform float maxVal;
|
|
957
957
|
|
|
@@ -965,7 +965,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
965
965
|
|
|
966
966
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
967
967
|
}
|
|
968
|
-
`}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){n.minLoc??(n.minLoc=r.getUniformLocationNoThrow(i,`minVal`),n.maxLoc=r.getUniformLocationNoThrow(i,`maxVal`)),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),
|
|
968
|
+
`}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){n.minLoc??(n.minLoc=r.getUniformLocationNoThrow(i,`minVal`),n.maxLoc=r.getUniformLocationNoThrow(i,`maxVal`)),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),Ia=function(e){this.variableNames=[`real`,`imag`],this.outputShape=e,this.userCode=`
|
|
969
969
|
void main() {
|
|
970
970
|
float re = abs(getRealAtOutCoords());
|
|
971
971
|
float im = abs(getImagAtOutCoords());
|
|
@@ -978,7 +978,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
978
978
|
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
|
|
979
979
|
);
|
|
980
980
|
}
|
|
981
|
-
`},
|
|
981
|
+
`},La=function(e){this.outputShape=[],this.outputShape=In(e,1),this.variableNames=e.map((function(e,t){return`T`+t}));var t=Array(e.length-1);t[0]=e[0][1];for(var n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];var r=[`if (yC < `+t[0]+`) setOutput(getT0(yR, yC));`];for(n=1;n<t.length;n++){var i=t[n-1];r.push(`else if (yC < `+t[n]+`) setOutput(getT`+n+`(yR, yC-`+i+`));`)}var a=t.length,o=t[t.length-1];r.push(`else setOutput(getT`+a+`(yR, yC-`+o+`));`),this.userCode=`
|
|
982
982
|
void main() {
|
|
983
983
|
ivec2 coords = getOutputCoords();
|
|
984
984
|
int yR = coords.x;
|
|
@@ -987,18 +987,18 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
987
987
|
`+r.join(`
|
|
988
988
|
`)+`
|
|
989
989
|
}
|
|
990
|
-
`},
|
|
990
|
+
`},Ra=function(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=In(e,t);var n=this.outputShape,r=n.length,i=ga(r),a=na(`coords`,r),o=[`x`,`y`,`z`,`w`,`u`,`v`].slice(0,r);this.variableNames=e.map((function(e,t){return`T`+t}));var s=Array(e.length-1);s[0]=e[0][t];for(var c=1;c<s.length;c++)s[c]=s[c-1]+e[c][t];var l=o[t],u=o.slice(-2),d=o.join(),f=`if (`+l+` < `+s[0]+`) {
|
|
991
991
|
return getChannel(
|
|
992
992
|
getT0(`+d+`), vec2(`+u.join()+`));
|
|
993
993
|
}`;for(c=1;c<s.length;c++){var p=s[c-1];f+=`
|
|
994
994
|
if (`+l+` < `+s[c]+` && `+l+` >= `+s[c-1]+`) {
|
|
995
995
|
return getChannel(
|
|
996
|
-
getT`+c+`(`+
|
|
997
|
-
vec2(`+
|
|
996
|
+
getT`+c+`(`+za(o,l,p)+`),
|
|
997
|
+
vec2(`+za(u,l,p)+`));
|
|
998
998
|
}`}var m=s.length,h=s[s.length-1];f+=`
|
|
999
999
|
return getChannel(
|
|
1000
|
-
getT`+m+`(`+
|
|
1001
|
-
vec2(`+
|
|
1000
|
+
getT`+m+`(`+za(o,l,h)+`),
|
|
1001
|
+
vec2(`+za(u,l,h)+`));`,this.userCode=`
|
|
1002
1002
|
float getValue(`+o.map((function(e){return`int `+e}))+`) {
|
|
1003
1003
|
`+f+`
|
|
1004
1004
|
}
|
|
@@ -1024,7 +1024,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1024
1024
|
}
|
|
1025
1025
|
setOutput(result);
|
|
1026
1026
|
}
|
|
1027
|
-
`};function
|
|
1027
|
+
`};function za(e,t,n){var r=e.indexOf(t);return e.map((function(e,t){return t===r?e+` - `+n:e})).join()}var Ba=function(e){this.variableNames=[`x`,`dy`],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left,a=e.dataFormat===`channelsLast`;this.userCode=`
|
|
1028
1028
|
void main() {
|
|
1029
1029
|
ivec4 coords = getOutputCoords();
|
|
1030
1030
|
int wR = coords.x;
|
|
@@ -1066,7 +1066,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1066
1066
|
}
|
|
1067
1067
|
setOutput(dotProd);
|
|
1068
1068
|
}
|
|
1069
|
-
`},
|
|
1069
|
+
`},Va=function(e){this.variableNames=[`dy`,`W`],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,a=e.dataFormat===`channelsLast`,o=t-1-e.padInfo.top,s=n-1-e.padInfo.left,c=a?1:2,l=a?2:3,u=a?3:1;this.userCode=`
|
|
1070
1070
|
const ivec2 pads = ivec2(`+o+`, `+s+`);
|
|
1071
1071
|
|
|
1072
1072
|
void main() {
|
|
@@ -1119,7 +1119,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1119
1119
|
}
|
|
1120
1120
|
setOutput(dotProd);
|
|
1121
1121
|
}
|
|
1122
|
-
`},
|
|
1122
|
+
`},Ha=function(e){this.variableNames=[`x`,`dy`],this.outputShape=e.filterShape;var t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,i=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
|
|
1123
1123
|
void main() {
|
|
1124
1124
|
ivec5 coords = getOutputCoords();
|
|
1125
1125
|
int wF = coords.x;
|
|
@@ -1161,7 +1161,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1161
1161
|
}
|
|
1162
1162
|
setOutput(dotProd);
|
|
1163
1163
|
}
|
|
1164
|
-
`},
|
|
1164
|
+
`},Ua=function(e){this.variableNames=[`dy`,`W`],this.outputShape=e.inShape;var t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,i=e.strideDepth,a=e.strideHeight,o=e.strideWidth,s=t-1-e.padInfo.front,c=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`
|
|
1165
1165
|
const ivec3 pads = ivec3(`+s+`, `+c+`, `+l+`);
|
|
1166
1166
|
|
|
1167
1167
|
void main() {
|
|
@@ -1218,7 +1218,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1218
1218
|
}
|
|
1219
1219
|
setOutput(dotProd);
|
|
1220
1220
|
}
|
|
1221
|
-
`},
|
|
1221
|
+
`},Wa=function(e){this.variableNames=[`x`,`dy`],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left;this.userCode=`
|
|
1222
1222
|
void main() {
|
|
1223
1223
|
ivec4 coords = getOutputCoords();
|
|
1224
1224
|
int wR = coords.x;
|
|
@@ -1253,7 +1253,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1253
1253
|
}
|
|
1254
1254
|
setOutput(dotProd);
|
|
1255
1255
|
}
|
|
1256
|
-
`},
|
|
1256
|
+
`},Ga=function(e){this.variableNames=[`dy`,`W`],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`
|
|
1257
1257
|
const ivec2 pads = ivec2(`+a+`, `+o+`);
|
|
1258
1258
|
|
|
1259
1259
|
void main() {
|
|
@@ -1298,7 +1298,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1298
1298
|
}
|
|
1299
1299
|
setOutput(dotProd);
|
|
1300
1300
|
}
|
|
1301
|
-
`},
|
|
1301
|
+
`},Ka=function(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=null),r===void 0&&(r=!1),this.variableNames=[`x`,`W`],this.outputShape=e.outShape;var i=e.padInfo.top,a=e.padInfo.left,o=e.strideHeight,s=e.strideWidth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterHeight,d=e.filterWidth,f=4*Math.floor(e.inChannels/4),p=e.inChannels%4,m=e.dataFormat===`channelsLast`,h=m?1:2,g=m?2:3,_=m?3:1,v=``,y=``;n&&(v=r?`float activation(float a) {
|
|
1302
1302
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
1303
1303
|
`+n+`
|
|
1304
1304
|
}`:`
|
|
@@ -1429,7 +1429,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1429
1429
|
`+y+`
|
|
1430
1430
|
setOutput(result);
|
|
1431
1431
|
}
|
|
1432
|
-
`},
|
|
1432
|
+
`},qa=function(e){this.variableNames=[`x`,`W`],this.outputShape=e.outShape;var t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,i=e.strideDepth,a=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,f=e.filterWidth,p=4*Math.floor(e.inChannels/4),m=e.inChannels%4;this.userCode=`
|
|
1433
1433
|
const ivec3 strides = ivec3(`+i+`, `+a+`, `+o+`);
|
|
1434
1434
|
const ivec3 pads = ivec3(`+t+`, `+n+`, `+r+`);
|
|
1435
1435
|
|
|
@@ -1517,7 +1517,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1517
1517
|
}
|
|
1518
1518
|
setOutput(dotProd);
|
|
1519
1519
|
}
|
|
1520
|
-
`},
|
|
1520
|
+
`},Ja=function(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=null),r===void 0&&(r=!1),this.variableNames=[`x`,`W`],this.outputShape=e.outShape;var i=e.inHeight,a=e.inWidth,o=e.padInfo.top,s=e.padInfo.left,c=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,d=e.dilationWidth,f=e.filterHeight,p=e.filterWidth,m=e.outChannels/e.inChannels,h=``,g=``;n&&(h=r?`float activation(float a) {
|
|
1521
1521
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
1522
1522
|
`+n+`
|
|
1523
1523
|
}`:`
|
|
@@ -1570,7 +1570,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1570
1570
|
`+g+`
|
|
1571
1571
|
setOutput(result);
|
|
1572
1572
|
}
|
|
1573
|
-
`},
|
|
1573
|
+
`},Ya=function(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=null),r===void 0&&(r=!1),this.variableNames=[`x`,`W`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;for(var i=e.inHeight,a=e.inWidth,o=e.padInfo.top,s=e.padInfo.left,c=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,d=e.dilationWidth,f=e.filterHeight,p=e.filterWidth,m=p,h=`int xR; int xC; int xCOffset;`,g=0;g<f;g++)for(var _=0;_<p;_++)h+=`
|
|
1574
1574
|
vec4 xTexelR`+g+`C`+2*_+` = vec4(0.);
|
|
1575
1575
|
vec4 wR`+g+`C`+_+` = vec4(0.);
|
|
1576
1576
|
vec4 xR`+g+`C`+_+` = vec4(0.);`;for(g=0;g<f;g++)for(var v=0;v<m;v++){if(h+=`
|
|
@@ -1612,7 +1612,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1612
1612
|
}
|
|
1613
1613
|
|
|
1614
1614
|
xR`+g+`C`+_+` = xTexelR`+g+`C`+_+`;
|
|
1615
|
-
`,_+1<p)){var y=s%2==0?
|
|
1615
|
+
`,_+1<p)){var y=s%2==0?ie(d):d;d%2==0&&s%2==1||d%2!=0&&s%2!=1?(h+=`
|
|
1616
1616
|
xCOffset = xC + `+s%2+` + `+y+`;
|
|
1617
1617
|
|
|
1618
1618
|
if(xR >= 0 && xR < `+i+` &&
|
|
@@ -1720,7 +1720,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1720
1720
|
`+x+`
|
|
1721
1721
|
setOutput(result);
|
|
1722
1722
|
}
|
|
1723
|
-
`},
|
|
1723
|
+
`},Xa=function(e,t,n,r,i){this.variableNames=[`Image`,`Boxes`,`BoxInd`],this.outputShape=[];var a=e[0],o=e[1],s=e[2],c=e[3],l=t[0],u=n[0],d=n[1];this.outputShape=[l,u,d,c];var f=r===`bilinear`?1:0,p=[o-1+`.0`,s-1+`.0`],m=p[0],h=p[1],g=u>1?[``+(o-1)/(u-1),`(y2-y1) * height_ratio`,`y1*`+m+` + float(y)*(height_scale)`]:[`0.0`,`0.0`,`0.5 * (y1+y2) * `+m],_=g[0],v=g[1],y=g[2],b=d>1?[``+(s-1)/(d-1),`(x2-x1) * width_ratio`,`x1*`+h+` + float(x)*(width_scale)`]:[`0.0`,`0.0`,`0.5 * (x1+x2) * `+h],x=b[0],S=b[1],C=b[2];this.userCode=`
|
|
1724
1724
|
const float height_ratio = float(`+_+`);
|
|
1725
1725
|
const float width_ratio = float(`+x+`);
|
|
1726
1726
|
void main() {
|
|
@@ -1781,14 +1781,14 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1781
1781
|
setOutput(newValue);
|
|
1782
1782
|
}
|
|
1783
1783
|
}
|
|
1784
|
-
`},
|
|
1784
|
+
`},Za=function(e,t,n){this.variableNames=[`x`],this.outputShape=e;var r=e.length,i=e[e.length-1],a=n?`<`:`>`;this.userCode=`
|
|
1785
1785
|
int getIndex(int i) {
|
|
1786
1786
|
`+(n?`return `+i+` -i - 1;`:`return i;`)+`
|
|
1787
1787
|
}
|
|
1788
1788
|
|
|
1789
1789
|
void main() {
|
|
1790
|
-
`+
|
|
1791
|
-
int end = `+
|
|
1790
|
+
`+ga(r)+` coords = getOutputCoords();
|
|
1791
|
+
int end = `+Qa(r,`coords`)+`;
|
|
1792
1792
|
float val = 0.0;
|
|
1793
1793
|
for (int i = `+i+` - 1; i >= 0; i -= 1) {
|
|
1794
1794
|
int idx = getIndex(i);
|
|
@@ -1798,14 +1798,14 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1798
1798
|
if (idx == end && `+t+`) {
|
|
1799
1799
|
continue;
|
|
1800
1800
|
}
|
|
1801
|
-
`+
|
|
1801
|
+
`+Qa(r,`coords`)+` = idx;
|
|
1802
1802
|
val += getX(`+function(e,t){if(e===1)return``+t;if(e===2)return t+`.x, `+t+`.y`;if(e===3)return t+`.x, `+t+`.y, `+t+`.z`;if(e===4)return t+`.x, `+t+`.y, `+t+`.z, `+t+`.w`;throw Error(`Cumulative sum for rank `+e+` is not yet supported`)}(r,`coords`)+`);
|
|
1803
1803
|
}
|
|
1804
1804
|
setOutput(val);
|
|
1805
1805
|
}
|
|
1806
|
-
`};function
|
|
1806
|
+
`};function Qa(e,t){if(e===1)return``+t;if(e===2)return t+`.y`;if(e===3)return t+`.z`;if(e===4)return t+`.w`;throw Error(`Cumulative sum for rank `+e+` is not yet supported`)}var $a=function(e){this.variableNames=[`A`],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=_t.DENSE;var t=Tt(e),n=ra();this.outputShape=e,this.userCode=`
|
|
1807
1807
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
1808
|
-
`+
|
|
1808
|
+
`+ia([`r`,`c`,`d`],e)+`
|
|
1809
1809
|
return ivec3(r, c, d);
|
|
1810
1810
|
}
|
|
1811
1811
|
|
|
@@ -1824,9 +1824,9 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1824
1824
|
|
|
1825
1825
|
`+n.output+` = result;
|
|
1826
1826
|
}
|
|
1827
|
-
`},
|
|
1827
|
+
`},eo=function(e){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=_t.DENSE;var t=Tt(e),n=ra();this.outputShape=e,this.userCode=`
|
|
1828
1828
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
1829
|
-
`+
|
|
1829
|
+
`+ia([`r`,`c`,`d`],e)+`
|
|
1830
1830
|
return ivec3(r, c, d);
|
|
1831
1831
|
}
|
|
1832
1832
|
|
|
@@ -1845,7 +1845,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1845
1845
|
|
|
1846
1846
|
`+n.output+` = result;
|
|
1847
1847
|
}
|
|
1848
|
-
`},
|
|
1848
|
+
`},to=function(){function e(e,t,n){this.variableNames=[`x`],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
|
|
1849
1849
|
void main() {
|
|
1850
1850
|
ivec4 coords = getOutputCoords();
|
|
1851
1851
|
int b = coords[0];
|
|
@@ -1864,29 +1864,29 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1864
1864
|
float result = `+this.getInputSamplingString()+`;
|
|
1865
1865
|
setOutput(result);
|
|
1866
1866
|
}
|
|
1867
|
-
`}return e.prototype.getHeightCoordString=function(){return this.dataFormat===`NHWC`?`coords[1]`:`coords[2]`},e.prototype.getWidthCoordString=function(){return this.dataFormat===`NHWC`?`coords[2]`:`coords[3]`},e.prototype.getDepthCoordString=function(){return this.dataFormat===`NHWC`?`coords[3]`:`coords[1]`},e.prototype.getOutputDepthSize=function(){return this.dataFormat===`NHWC`?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return this.dataFormat===`NHWC`?`getX(b, in_h, in_w, in_d)`:`getX(b, in_d, in_h, in_w)`},e}(),
|
|
1867
|
+
`}return e.prototype.getHeightCoordString=function(){return this.dataFormat===`NHWC`?`coords[1]`:`coords[2]`},e.prototype.getWidthCoordString=function(){return this.dataFormat===`NHWC`?`coords[2]`:`coords[3]`},e.prototype.getDepthCoordString=function(){return this.dataFormat===`NHWC`?`coords[3]`:`coords[1]`},e.prototype.getOutputDepthSize=function(){return this.dataFormat===`NHWC`?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return this.dataFormat===`NHWC`?`getX(b, in_h, in_w, in_d)`:`getX(b, in_d, in_h, in_w)`},e}(),no=function(e){this.variableNames=[`X`],this.outputShape=[e,e],this.userCode=`
|
|
1868
1868
|
void main() {
|
|
1869
1869
|
ivec2 coords = getOutputCoords();
|
|
1870
1870
|
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
|
|
1871
1871
|
setOutput(val);
|
|
1872
1872
|
}
|
|
1873
|
-
`},
|
|
1874
|
-
`+
|
|
1873
|
+
`},ro=function(e){this.variableNames=[`A`],this.outTexUsage=vt.DOWNLOAD;var t=ra();this.outputShape=e,this.userCode=`
|
|
1874
|
+
`+oa+`
|
|
1875
1875
|
|
|
1876
1876
|
void main() {
|
|
1877
1877
|
float x = getAAtOutCoords();
|
|
1878
1878
|
`+t.output+` = encode_float(x);
|
|
1879
1879
|
}
|
|
1880
|
-
`},
|
|
1881
|
-
`+
|
|
1880
|
+
`},io=function(e){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=vt.DOWNLOAD;var t=ra();this.outputShape=e,this.userCode=`
|
|
1881
|
+
`+oa+`
|
|
1882
1882
|
|
|
1883
1883
|
void main() {
|
|
1884
1884
|
ivec3 coords = getOutputCoords();
|
|
1885
1885
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
1886
1886
|
`+t.output+` = encode_float(x);
|
|
1887
1887
|
}
|
|
1888
|
-
`},
|
|
1889
|
-
`+
|
|
1888
|
+
`},ao=function(e,t,n){n===void 0&&(n=!1),this.variableNames=[`A`];var r=ra(),i=t[0],a=t[1];this.outputShape=e;var o=`result`;n&&(o=`floor(result * 255. + 0.5)`),this.userCode=`
|
|
1889
|
+
`+aa(e)+`
|
|
1890
1890
|
|
|
1891
1891
|
void main() {
|
|
1892
1892
|
ivec3 coords = getOutputCoords();
|
|
@@ -1915,7 +1915,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1915
1915
|
|
|
1916
1916
|
`+r.output+` = vec4(`+o+`, 0., 0., 0.);
|
|
1917
1917
|
}
|
|
1918
|
-
`},
|
|
1918
|
+
`},oo=function(e,t,n){n===void 0&&(n=!1),this.variableNames=[`A`],this.packedInputs=!1,this.packedOutput=!0;var r=ra(),i=t[0],a=t[1];this.outputShape=e;var o=``,s=`result`;n&&(s=`floor(result * 255. + 0.5)`);for(var c=0;c<=1;c++)for(var l=0;l<=1;l++){var u=2*c+l;o+=`
|
|
1919
1919
|
localCoords = coords;
|
|
1920
1920
|
if(localCoords[2] + `+l+` < `+e[2]+`) {
|
|
1921
1921
|
localCoords[2] += `+l+`;
|
|
@@ -1944,7 +1944,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1944
1944
|
}
|
|
1945
1945
|
}
|
|
1946
1946
|
`}this.userCode=`
|
|
1947
|
-
`+
|
|
1947
|
+
`+aa(e)+`
|
|
1948
1948
|
|
|
1949
1949
|
void main() {
|
|
1950
1950
|
ivec3 coords = getOutputCoords();
|
|
@@ -1959,7 +1959,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1959
1959
|
|
|
1960
1960
|
`+r.output+` = `+s+`;
|
|
1961
1961
|
}
|
|
1962
|
-
`},
|
|
1962
|
+
`},so=`return real * expR - imag * expI;`,co=`return real * expI + imag * expR;`,lo=function(e,t,n){this.variableNames=[`real`,`imag`];var r=t[1];this.outputShape=t;var i=n?`2.0 * `+Math.PI:`-2.0 * `+Math.PI,a=n?r+`.0`:`1.0`;this.userCode=`
|
|
1963
1963
|
const float exponentMultiplier = `+i+`;
|
|
1964
1964
|
|
|
1965
1965
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
@@ -1992,18 +1992,18 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
1992
1992
|
ivec2 coords = getOutputCoords();
|
|
1993
1993
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
1994
1994
|
}
|
|
1995
|
-
`},
|
|
1995
|
+
`},uo=function(){function e(e,t){this.outputShape=[],this.variableNames=[`x`],this.outputShape=e,this.userCode=`
|
|
1996
1996
|
uniform float value;
|
|
1997
1997
|
void main() {
|
|
1998
1998
|
// Input can be obtained from uniform value.
|
|
1999
1999
|
setOutput(value);
|
|
2000
2000
|
}
|
|
2001
|
-
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){t.valueLoc??=n.getUniformLocationNoThrow(r,`value`),n.gl.uniform1f(t.valueLoc,e)}},e}(),
|
|
2001
|
+
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){t.valueLoc??=n.getUniformLocationNoThrow(r,`value`),n.gl.uniform1f(t.valueLoc,e)}},e}(),fo=function(e,t,n){this.variableNames=[`A`,`indices`];var r=e.slice();r[n]=t,this.outputShape=r,this.rank=r.length;var i=ga(this.rank),a=function(e,t){var n=e.length;if(n>4)throw Error(`Gather for rank `+n+` is not yet supported`);if(n===1)return`int(getIndices(resRC))`;for(var r=[`resRC.x`,`resRC.y`,`resRC.z`,`resRC.w`],i=[],a=0;a<e.length;a++)a===t?i.push(`int(getIndices(`+r[a]+`))`):i.push(``+r[a]);return i.join()}(e,n);this.userCode=`
|
|
2002
2002
|
void main() {
|
|
2003
2003
|
`+i+` resRC = getOutputCoords();
|
|
2004
2004
|
setOutput(getA(`+a+`));
|
|
2005
2005
|
}
|
|
2006
|
-
`}
|
|
2006
|
+
`},po=function(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=[`x`,`indices`],this.outputShape=n;var r=ga(t.length),i=ga(n.length),a=this.sliceDim>1?`strides[j]`:`strides`;this.userCode=`
|
|
2007
2007
|
`+r+` strides = `+r+`(`+this.strides+`);
|
|
2008
2008
|
void main() {
|
|
2009
2009
|
`+i+` coords = getOutputCoords();
|
|
@@ -2014,7 +2014,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2014
2014
|
}
|
|
2015
2015
|
setOutput(getX(flattenIndex, coords[1]));
|
|
2016
2016
|
}
|
|
2017
|
-
`};function
|
|
2017
|
+
`};function mo(e,t){var n=ra();return Nt(e,t,n.version+`
|
|
2018
2018
|
precision highp float;
|
|
2019
2019
|
`+n.attribute+` vec3 clipSpacePos;
|
|
2020
2020
|
`+n.attribute+` vec2 uv;
|
|
@@ -2023,7 +2023,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2023
2023
|
void main() {
|
|
2024
2024
|
gl_Position = vec4(clipSpacePos, 1);
|
|
2025
2025
|
resultUV = uv;
|
|
2026
|
-
}`)}function to(e,t){return kt(e,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function no(e,t){return At(e,t,new Uint16Array([0,1,2,2,1,3]))}function ro(e,t,n,r,i,a,o){Mt(n,r);var s=jt(e,t),c=e.TEXTURE_2D;return B(e,t,(function(){return e.bindTexture(c,s)})),B(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)})),B(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)})),B(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)})),B(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)})),B(e,t,(function(){return e.texImage2D(c,0,i,n,r,0,a,o,null)})),B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)})),s}function io(e,t,n,r,i){var a=ft(n,r);return ro(e,t,a[0],a[1],i.internalFormatFloat,i.textureFormatFloat,e.FLOAT)}function ao(e,t,n,r,i){var a=ft(n,r);return ro(e,t,a[0],a[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function oo(e,t,n,r,i){var a=ft(n,r);return ro(e,t,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function so(e,t,n,r,i){var a=mt(n,r);return ro(e,t,a[0],a[1],i.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function co(e,t,n,r,i){var a=mt(n,r);return ro(e,t,a[0],a[1],i.internalFormatPackedHalfFloat,e.RGBA,i.textureTypeHalfFloat)}function lo(e,t,n,r){return B(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),Pt(e,t,n,`clipSpacePos`,r,3,20,0)&&Pt(e,t,n,`uv`,r,2,20,12)}function uo(e,t,n,r,i,a,o){var s,c,l;B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),a instanceof Uint8Array?(s=new Uint8Array(r*i*4),c=e.UNSIGNED_BYTE,l=e.RGBA):(s=new Float32Array(r*i*4),c=e.FLOAT,l=o.internalFormatPackedFloat),s.set(a),B(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,l,r,i,0,e.RGBA,c,s)})),B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function fo(e,t,n,r){B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),r.data instanceof Uint8Array?B(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)})):B(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)})),B(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function po(e,t,n,r,i){var a=e.createBuffer();B(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,a)}));var o=16*n*r;return B(e,t,(function(){return e.bufferData(e.PIXEL_PACK_BUFFER,o,e.STREAM_READ)})),B(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,0)})),B(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,null)})),a}function mo(e,t,n){var r=e,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function ho(e,t,n,r,i){var a=ft(n,r),o=a[0],s=a[1],c=new Uint8Array(n*r*4);return B(e,t,(function(){return e.readPixels(0,0,o,s,i.downloadTextureFormat,e.UNSIGNED_BYTE,c)})),new Float32Array(c.buffer)}function go(e,t,n,r,i,a,o,s){var c=e,l=new Float32Array(function(e,t){var n=mt(e,t);return n[0]*n[1]*4}(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function _o(e,t,n,r){var i=new Float32Array(n*r*4);return B(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,i)})),i}var vo=Object.freeze({createVertexShader:eo,createVertexBuffer:to,createIndexBuffer:no,createFloat32MatrixTexture:io,createFloat16MatrixTexture:ao,createUnsignedBytesMatrixTexture:oo,createPackedMatrixTexture:so,createFloat16PackedMatrixTexture:co,bindVertexProgramAttributeStreams:lo,uploadDenseMatrixToTexture:uo,uploadPixelDataToTexture:fo,createBufferFromOutputTexture:po,downloadFloat32MatrixFromBuffer:mo,downloadByteEncodedFloatMatrixFromOutputTexture:ho,downloadPackedMatrixFromBuffer:go,downloadMatrixFromPackedOutputTexture:_o}),yo=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var t=m().getNumber(`WEBGL_VERSION`);e==null?this.gl=dt(t):(this.gl=e,ut(t,e));var n=`WEBGL_color_buffer_float`;if(m().getNumber(`WEBGL_VERSION`)===1){if(this.textureFloatExtension=bt(this.gl,this.debug,`OES_texture_float`),en(this.gl,`OES_texture_half_float`))this.textureHalfFloatExtension=bt(this.gl,this.debug,`OES_texture_half_float`);else if(m().get(`WEBGL_FORCE_F16_TEXTURES`))throw Error(`GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.`);if(this.colorBufferFloatExtension=this.gl.getExtension(n),en(this.gl,`EXT_color_buffer_half_float`))this.colorBufferHalfFloatExtension=bt(this.gl,this.debug,`EXT_color_buffer_half_float`);else if(m().get(`WEBGL_FORCE_F16_TEXTURES`))throw Error(`GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.`)}else if(n=`EXT_color_buffer_float`,en(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!en(this.gl,`EXT_color_buffer_half_float`))throw Error(`GL context does not support color renderable floats`);this.colorBufferHalfFloatExtension=this.gl.getExtension(`EXT_color_buffer_half_float`)}this.vertexBuffer=to(this.gl,this.debug),this.indexBuffer=no(this.gl,this.debug),this.framebuffer=Nt(this.gl,this.debug),this.textureConfig=ht(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,`debug`,{get:function(){return m().getBool(`DEBUG`)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=this;if(!this.disposed){this.program!=null&&console.warn(`Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing.`),this.outputTexture!=null&&console.warn(`Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.`);var t=this.gl;B(t,this.debug,(function(){return t.finish()})),B(t,this.debug,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),B(t,this.debug,(function(){return t.deleteFramebuffer(e.framebuffer)})),B(t,this.debug,(function(){return t.bindBuffer(t.ARRAY_BUFFER,null)})),B(t,this.debug,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)})),B(t,this.debug,(function(){return t.deleteBuffer(e.indexBuffer)})),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),io(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),ao(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),oo(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),fo(this.gl,this.debug,e,t)},e.prototype.uploadDenseMatrixToTexture=function(e,t,n,r){this.throwIfDisposed(),uo(this.gl,this.debug,e,t,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(e,t){return this.throwIfDisposed(),co(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),so(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(Bt(this.gl,this.debug,this.framebuffer),this.outputTexture=null),B(this.gl,this.debug,(function(){return t.gl.deleteTexture(e)}))},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return ho(r.gl,r.debug,t,n,r.textureConfig)}))},e.prototype.downloadPackedMatrixFromBuffer=function(e,t,n,r,i,a){return go(this.gl,e,0,0,0,i,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(e,t){return mo(this.gl,e,t)},e.prototype.createBufferFromTexture=function(e,t,n){this.bindTextureToFrameBuffer(e);var r=po(this.gl,this.debug,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(e){var t,n,r=this;if(m().getBool(`WEBGL_FENCE_API_ENABLED`)){var i=e,a=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=function(){var e=i.clientWaitSync(a,0,0);return e===i.ALREADY_SIGNALED||e===i.CONDITION_SATISFIED},t=a}else m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)>0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return _o(r.gl,r.debug,t,n)}))},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=St(t,this.debug,e),r=eo(t,this.debug),i=Et(t,this.debug);return B(t,this.debug,(function(){return t.attachShader(i,r)})),B(t,this.debug,(function(){return t.attachShader(i,n)})),Dt(t,this.debug,i),this.debug&&Ot(t,this.debug,i),this.vertexAttrsAreBound||=(this.setProgram(i),lo(t,this.debug,this.program,this.vertexBuffer)),i},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&B(this.gl,this.debug,(function(){return t.gl.deleteProgram(e)}))},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Ot(this.gl,this.debug,this.program),B(this.gl,this.debug,(function(){return t.gl.useProgram(e)}))},e.prototype.getUniformLocation=function(e,t,n){return n===void 0&&(n=!0),this.throwIfDisposed(),n?It(this.gl,this.debug,e,t):Lt(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),B(this.gl,this.debug,(function(){return n.gl.getAttribLocation(e,t)}))},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Rt(this.gl,this.debug,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=mt(t,n),i=r[0],a=r[1];this.setOutputMatrixTextureDriver(e,i,a)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw Error(`setOutputPackedMatrixWriteRegion not implemented.`)},e.prototype.debugValidate=function(){this.program!=null&&Ot(this.gl,this.debug,this.program),Vt(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.debug&&this.debugValidate(),B(e,this.debug,(function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)}))},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),B(this.gl,this.debug,(function(){return e.gl.finish()}))},e.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension??=bt(this.gl,this.debug,m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)===2?`EXT_disjoint_timer_query_webgl2`:`EXT_disjoint_timer_query`),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)===2){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},e.prototype.endQuery=function(){if(m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)!==2){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return u(this,void 0,void 0,(function(){var t=this;return d(this,(function(n){switch(n.label){case 0:return[4,te((function(){return t.disposed||t.isQueryAvailable(e,m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))}))];case 1:return n.sent(),[2,this.getQueryTime(e,m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))]}}))}))},e.prototype.getQueryTime=function(e,t){if(t===0)return null;if(t===2){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(t===0)return!0;if(t===2){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint??=this.gl.getParameter(r.GPU_DISJOINT_EXT),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),this.disjoint??=this.gl.getParameter(r.GPU_DISJOINT_EXT),i&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise((function(n){t.addItemToPoll((function(){return e.isFencePassed()}),(function(){return n()}))}))},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((function(e){return e.isDoneFn}))),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||te((function(){return n.pollItems(),n.itemsToPoll.length===0}))},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),zt(this.gl,this.debug,e,this.framebuffer),this.debug&&Vt(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture==null?Bt(this.gl,this.debug,this.framebuffer):(zt(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Vt(this.gl))},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;zt(r,this.debug,e,this.framebuffer),this.debug&&Vt(r),this.outputTexture=e,B(r,this.debug,(function(){return r.viewport(0,0,t,n)})),B(r,this.debug,(function(){return r.scissor(0,0,t,n)}))},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var i=this;this.throwIfDisposed(),B(this.gl,this.debug,(function(){return i.gl.scissor(e,t,n,r)}))},e.prototype.throwIfDisposed=function(){if(this.disposed)throw Error(`Attempted to use disposed GPGPUContext.`)},e.prototype.throwIfNoProgram=function(){if(this.program==null)throw Error(`No GPU program is currently set.`)},e}();function bo(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with `+e.length+` inputs, but was executed with `+t.length+` inputs`);e.forEach((function(e,n){var r=e.logicalShape,i=t[n],a=i.shape;if(!N(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes `+r+` and `+a+` must match`);if(!e.isUniform||!i.isUniform){var o=e.texShape,s=i.isUniform?null:i.texData.texShape;if(!N(o,s))throw Error(`Binary was compiled with different texture shapes than the current args. Shape `+o+` and `+s+` must match`)}}))}var xo=function(e,t,n){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var r=n.filterWidth,i=n.inChannels,a=n.strideWidth,o=n.strideHeight,s=n.padInfo,c=n.outWidth,l=n.dilationWidth,u=n.dilationHeight,d=n.dataFormat,f=s.left,p=s.top,m=i*r,h=Wi(),g=d===`channelsLast`,_=g?0:1,v=g?1:2,y=``,b=0;b<=1;b++)for(var x=0;x<=1;x++)y+=`
|
|
2026
|
+
}`)}function ho(e,t){return Vt(e,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function go(e,t){return Ht(e,t,new Uint16Array([0,1,2,2,1,3]))}function _o(e,t,n,r,i,a,o){Wt(n,r);var s=Ut(e,t),c=e.TEXTURE_2D;return H(e,t,(function(){return e.bindTexture(c,s)})),H(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)})),H(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)})),H(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)})),H(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)})),H(e,t,(function(){return e.texImage2D(c,0,i,n,r,0,a,o,null)})),H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)})),s}function vo(e,t,n,r,i){var a=wt(n,r);return _o(e,t,a[0],a[1],i.internalFormatFloat,i.textureFormatFloat,e.FLOAT)}function yo(e,t,n,r,i){var a=wt(n,r);return _o(e,t,a[0],a[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function bo(e,t,n,r,i){var a=wt(n,r);return _o(e,t,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function xo(e,t,n,r,i){var a=Et(n,r);return _o(e,t,a[0],a[1],i.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function So(e,t,n,r,i){var a=Et(n,r);return _o(e,t,a[0],a[1],i.internalFormatPackedHalfFloat,e.RGBA,i.textureTypeHalfFloat)}function Co(e,t,n,r){return H(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),Kt(e,t,n,`clipSpacePos`,r,3,20,0)&&Kt(e,t,n,`uv`,r,2,20,12)}function wo(e,t,n,r,i,a,o){var s,c,l;H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),a instanceof Uint8Array?(s=new Uint8Array(r*i*4),c=e.UNSIGNED_BYTE,l=e.RGBA):(s=new Float32Array(r*i*4),c=e.FLOAT,l=o.internalFormatPackedFloat),s.set(a),H(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,l,r,i,0,e.RGBA,c,s)})),H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function To(e,t,n,r){H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),r.data instanceof Uint8Array?H(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)})):H(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)})),H(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function Eo(e,t,n,r,i){var a=e.createBuffer();H(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,a)}));var o=16*n*r;return H(e,t,(function(){return e.bufferData(e.PIXEL_PACK_BUFFER,o,e.STREAM_READ)})),H(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,0)})),H(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,null)})),a}function Do(e,t,n){var r=e,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function Oo(e,t,n,r,i){var a=wt(n,r),o=a[0],s=a[1],c=new Uint8Array(n*r*4);return H(e,t,(function(){return e.readPixels(0,0,o,s,i.downloadTextureFormat,e.UNSIGNED_BYTE,c)})),new Float32Array(c.buffer)}function ko(e,t,n,r,i,a,o,s){var c=e,l=new Float32Array(function(e,t){var n=Et(e,t);return n[0]*n[1]*4}(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function Ao(e,t,n,r){var i=new Float32Array(n*r*4);return H(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,i)})),i}var jo=Object.freeze({createVertexShader:mo,createVertexBuffer:ho,createIndexBuffer:go,createFloat32MatrixTexture:vo,createFloat16MatrixTexture:yo,createUnsignedBytesMatrixTexture:bo,createPackedMatrixTexture:xo,createFloat16PackedMatrixTexture:So,bindVertexProgramAttributeStreams:Co,uploadDenseMatrixToTexture:wo,uploadPixelDataToTexture:To,createBufferFromOutputTexture:Eo,downloadFloat32MatrixFromBuffer:Do,downloadByteEncodedFloatMatrixFromOutputTexture:Oo,downloadPackedMatrixFromBuffer:ko,downloadMatrixFromPackedOutputTexture:Ao}),Mo=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var t=O().getNumber(`WEBGL_VERSION`);e==null?this.gl=Ct(t):(this.gl=e,St(t,e));var n=`WEBGL_color_buffer_float`;if(O().getNumber(`WEBGL_VERSION`)===1){if(this.textureFloatExtension=Mt(this.gl,this.debug,`OES_texture_float`),pn(this.gl,`OES_texture_half_float`))this.textureHalfFloatExtension=Mt(this.gl,this.debug,`OES_texture_half_float`);else if(O().get(`WEBGL_FORCE_F16_TEXTURES`))throw Error(`GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.`);if(this.colorBufferFloatExtension=this.gl.getExtension(n),pn(this.gl,`EXT_color_buffer_half_float`))this.colorBufferHalfFloatExtension=Mt(this.gl,this.debug,`EXT_color_buffer_half_float`);else if(O().get(`WEBGL_FORCE_F16_TEXTURES`))throw Error(`GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.`)}else if(n=`EXT_color_buffer_float`,pn(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!pn(this.gl,`EXT_color_buffer_half_float`))throw Error(`GL context does not support color renderable floats`);this.colorBufferHalfFloatExtension=this.gl.getExtension(`EXT_color_buffer_half_float`)}this.vertexBuffer=ho(this.gl,this.debug),this.indexBuffer=go(this.gl,this.debug),this.framebuffer=Gt(this.gl,this.debug),this.textureConfig=Dt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,`debug`,{get:function(){return O().getBool(`DEBUG`)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=this;if(!this.disposed){this.program!=null&&console.warn(`Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing.`),this.outputTexture!=null&&console.warn(`Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.`);var t=this.gl;H(t,this.debug,(function(){return t.finish()})),H(t,this.debug,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),H(t,this.debug,(function(){return t.deleteFramebuffer(e.framebuffer)})),H(t,this.debug,(function(){return t.bindBuffer(t.ARRAY_BUFFER,null)})),H(t,this.debug,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)})),H(t,this.debug,(function(){return t.deleteBuffer(e.indexBuffer)})),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),vo(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),yo(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),bo(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),To(this.gl,this.debug,e,t)},e.prototype.uploadDenseMatrixToTexture=function(e,t,n,r){this.throwIfDisposed(),wo(this.gl,this.debug,e,t,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(e,t){return this.throwIfDisposed(),So(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),xo(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(Qt(this.gl,this.debug,this.framebuffer),this.outputTexture=null),H(this.gl,this.debug,(function(){return t.gl.deleteTexture(e)}))},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return Oo(r.gl,r.debug,t,n,r.textureConfig)}))},e.prototype.downloadPackedMatrixFromBuffer=function(e,t,n,r,i,a){return ko(this.gl,e,0,0,0,i,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(e,t){return Do(this.gl,e,t)},e.prototype.createBufferFromTexture=function(e,t,n){this.bindTextureToFrameBuffer(e);var r=Eo(this.gl,this.debug,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(e){var t,n,r=this;if(O().getBool(`WEBGL_FENCE_API_ENABLED`)){var i=e,a=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=function(){var e=i.clientWaitSync(a,0,0);return e===i.ALREADY_SIGNALED||e===i.CONDITION_SATISFIED},t=a}else O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)>0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return Ao(r.gl,r.debug,t,n)}))},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=Pt(t,this.debug,e),r=mo(t,this.debug),i=Rt(t,this.debug);return H(t,this.debug,(function(){return t.attachShader(i,r)})),H(t,this.debug,(function(){return t.attachShader(i,n)})),zt(t,this.debug,i),this.debug&&Bt(t,this.debug,i),this.vertexAttrsAreBound||=(this.setProgram(i),Co(t,this.debug,this.program,this.vertexBuffer)),i},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&H(this.gl,this.debug,(function(){return t.gl.deleteProgram(e)}))},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Bt(this.gl,this.debug,this.program),H(this.gl,this.debug,(function(){return t.gl.useProgram(e)}))},e.prototype.getUniformLocation=function(e,t,n){return n===void 0&&(n=!0),this.throwIfDisposed(),n?Jt(this.gl,this.debug,e,t):Yt(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),H(this.gl,this.debug,(function(){return n.gl.getAttribLocation(e,t)}))},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Xt(this.gl,this.debug,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=Et(t,n),i=r[0],a=r[1];this.setOutputMatrixTextureDriver(e,i,a)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw Error(`setOutputPackedMatrixWriteRegion not implemented.`)},e.prototype.debugValidate=function(){this.program!=null&&Bt(this.gl,this.debug,this.program),$t(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.debug&&this.debugValidate(),H(e,this.debug,(function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)}))},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),H(this.gl,this.debug,(function(){return e.gl.finish()}))},e.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension??=Mt(this.gl,this.debug,O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)===2?`EXT_disjoint_timer_query_webgl2`:`EXT_disjoint_timer_query`),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)===2){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},e.prototype.endQuery=function(){if(O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`)!==2){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return w(this,void 0,void 0,(function(){var t=this;return T(this,(function(n){switch(n.label){case 0:return[4,fe((function(){return t.disposed||t.isQueryAvailable(e,O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))}))];case 1:return n.sent(),[2,this.getQueryTime(e,O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION`))]}}))}))},e.prototype.getQueryTime=function(e,t){if(t===0)return null;if(t===2){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(t===0)return!0;if(t===2){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint??=this.gl.getParameter(r.GPU_DISJOINT_EXT),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),this.disjoint??=this.gl.getParameter(r.GPU_DISJOINT_EXT),i&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise((function(n){t.addItemToPoll((function(){return e.isFencePassed()}),(function(){return n()}))}))},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((function(e){return e.isDoneFn}))),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||fe((function(){return n.pollItems(),n.itemsToPoll.length===0}))},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),Zt(this.gl,this.debug,e,this.framebuffer),this.debug&&$t(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture==null?Qt(this.gl,this.debug,this.framebuffer):(Zt(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&$t(this.gl))},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;Zt(r,this.debug,e,this.framebuffer),this.debug&&$t(r),this.outputTexture=e,H(r,this.debug,(function(){return r.viewport(0,0,t,n)})),H(r,this.debug,(function(){return r.scissor(0,0,t,n)}))},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var i=this;this.throwIfDisposed(),H(this.gl,this.debug,(function(){return i.gl.scissor(e,t,n,r)}))},e.prototype.throwIfDisposed=function(){if(this.disposed)throw Error(`Attempted to use disposed GPGPUContext.`)},e.prototype.throwIfNoProgram=function(){if(this.program==null)throw Error(`No GPU program is currently set.`)},e}();function No(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with `+e.length+` inputs, but was executed with `+t.length+` inputs`);e.forEach((function(e,n){var r=e.logicalShape,i=t[n],a=i.shape;if(!z(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes `+r+` and `+a+` must match`);if(!e.isUniform||!i.isUniform){var o=e.texShape,s=i.isUniform?null:i.texData.texShape;if(!z(o,s))throw Error(`Binary was compiled with different texture shapes than the current args. Shape `+o+` and `+s+` must match`)}}))}var Po=function(e,t,n){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var r=n.filterWidth,i=n.inChannels,a=n.strideWidth,o=n.strideHeight,s=n.padInfo,c=n.outWidth,l=n.dilationWidth,u=n.dilationHeight,d=n.dataFormat,f=s.left,p=s.top,m=i*r,h=ra(),g=d===`channelsLast`,_=g?0:1,v=g?1:2,y=``,b=0;b<=1;b++)for(var x=0;x<=1;x++)y+=`
|
|
2027
2027
|
blockIndex = rc.y + `+x+`;
|
|
2028
2028
|
pos = rc.x + `+b+`;
|
|
2029
2029
|
|
|
@@ -2067,7 +2067,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2067
2067
|
|
|
2068
2068
|
`+h.output+` = result;
|
|
2069
2069
|
}
|
|
2070
|
-
`},
|
|
2070
|
+
`},Fo=function(e,t,n,r,i){this.variableNames=[`x`],this.outputShape=[];var a,o=t,s=e[3]-1;this.outputShape=e;var c=`float(`+n+`) + float(`+r+`) * sum`;a=i===.5?`inversesqrt(`+c+`)`:i===1?`1.0/(`+c+`)`:`exp(log(`+c+`) * float(-`+i+`));`,this.userCode=`
|
|
2071
2071
|
void main() {
|
|
2072
2072
|
ivec4 coords = getOutputCoords();
|
|
2073
2073
|
int b = coords[0];
|
|
@@ -2086,7 +2086,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2086
2086
|
float val = x * `+a+`;
|
|
2087
2087
|
setOutput(val);
|
|
2088
2088
|
}
|
|
2089
|
-
`},
|
|
2089
|
+
`},Io=function(e,t,n,r,i){this.variableNames=[`inputImage`,`outputImage`,`dy`],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=i,this.userCode=`
|
|
2090
2090
|
void main() {
|
|
2091
2091
|
ivec4 coords = getOutputCoords();
|
|
2092
2092
|
int b = coords[0];
|
|
@@ -2141,7 +2141,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2141
2141
|
}
|
|
2142
2142
|
setOutput(result);
|
|
2143
2143
|
}
|
|
2144
|
-
`},
|
|
2144
|
+
`},Lo=function(e,t,n,r,i){this.variableNames=[`x`],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,o=t,s=e[3]-1;this.outputShape=e;var c=`float(`+n+`) + float(`+r+`) * sum`;a=i===.5?`inversesqrt(`+c+`)`:i===1?`1.0/(`+c+`)`:`exp(log(`+c+`) * float(-`+i+`));`,this.userCode=`
|
|
2145
2145
|
void main() {
|
|
2146
2146
|
ivec4 coords = getOutputCoords();
|
|
2147
2147
|
int b = coords.x;
|
|
@@ -2203,7 +2203,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2203
2203
|
vec4 result = xAtOutputCoords * `+a+`;
|
|
2204
2204
|
setOutput(result);
|
|
2205
2205
|
}
|
|
2206
|
-
`},
|
|
2206
|
+
`},Ro=function(e){this.variableNames=[`dy`,`maxPos`],this.outputShape=e.inShape;var t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,i=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=i-1-e.padInfo.top,s=a-1-e.padInfo.left,c=i*a-1;this.userCode=`
|
|
2207
2207
|
const ivec2 pads = ivec2(`+o+`, `+s+`);
|
|
2208
2208
|
|
|
2209
2209
|
void main() {
|
|
@@ -2249,7 +2249,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2249
2249
|
}
|
|
2250
2250
|
setOutput(dotProd);
|
|
2251
2251
|
}
|
|
2252
|
-
`},
|
|
2252
|
+
`},zo=function(e){this.variableNames=[`dy`,`maxPos`],this.outputShape=e.inShape;var t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,i=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterDepth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=s-1-e.padInfo.front,d=c-1-e.padInfo.top,f=l-1-e.padInfo.left,p=s*c*l-1;this.userCode=`
|
|
2253
2253
|
const ivec3 pads = ivec3(`+u+`, `+d+`, `+f+`);
|
|
2254
2254
|
|
|
2255
2255
|
void main() {
|
|
@@ -2313,7 +2313,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2313
2313
|
}
|
|
2314
2314
|
setOutput(dotProd);
|
|
2315
2315
|
}
|
|
2316
|
-
`},
|
|
2316
|
+
`},Bo=function(e,t,n,r,i,a,o){n===void 0&&(n=!1),r===void 0&&(r=!1),i===void 0&&(i=!1),a===void 0&&(a=null),o===void 0&&(o=!1),this.variableNames=[`matrixA`,`matrixB`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=n?e[1]:e[2],c=Math.ceil(s/2),l=n?`i * 2, rc.y`:`rc.y, i * 2`,u=r?`rc.z, i * 2`:`i * 2, rc.z`,d=n?[`a.xxyy`,`a.zzww`]:[`a.xxzz`,`a.yyww`],f=r?[`b.xzxz`,`b.ywyw`]:[`b.xyxy`,`b.zwzw`],p=``,m=``;a&&(p=o?`vec4 activation(vec4 a) {
|
|
2317
2317
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
2318
2318
|
`+a+`
|
|
2319
2319
|
}`:`vec4 activation(vec4 x) {
|
|
@@ -2347,7 +2347,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2347
2347
|
|
|
2348
2348
|
setOutput(result);
|
|
2349
2349
|
}
|
|
2350
|
-
`},
|
|
2350
|
+
`},Vo=function(){function e(e,t,n){this.variableNames=[`probs`],this.outputShape=[e,n],this.userCode=`
|
|
2351
2351
|
uniform float seed;
|
|
2352
2352
|
|
|
2353
2353
|
void main() {
|
|
@@ -2369,18 +2369,18 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2369
2369
|
// If no other event happened, last event happened.
|
|
2370
2370
|
setOutput(float(`+(t-1)+`));
|
|
2371
2371
|
}
|
|
2372
|
-
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){t.seedLoc??=n.getUniformLocation(r,`seed`),n.gl.uniform1f(t.seedLoc,e)}},e}(),
|
|
2372
|
+
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){t.seedLoc??=n.getUniformLocation(r,`seed`),n.gl.uniform1f(t.seedLoc,e)}},e}(),Ho=function(e,t,n,r){this.variableNames=[`indices`],this.outputShape=[e,t],this.userCode=`
|
|
2373
2373
|
void main() {
|
|
2374
2374
|
ivec2 coords = getOutputCoords();
|
|
2375
2375
|
int index = round(getIndices(coords.x));
|
|
2376
2376
|
setOutput(mix(float(`+r+`), float(`+n+`),
|
|
2377
2377
|
float(index == coords.y)));
|
|
2378
2378
|
}
|
|
2379
|
-
`},
|
|
2379
|
+
`},Uo=function(e){this.variableNames=[`A`],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;var t=e.length;if(t===0)this.userCode=`
|
|
2380
2380
|
void main() {
|
|
2381
2381
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
2382
2382
|
}
|
|
2383
|
-
`;else{var n=
|
|
2383
|
+
`;else{var n=na(`rc`,t),r=ga(t),i=function(e,t,n){if(e===1)return`rc > `+t[0];for(var r=``,i=e-2;i<e;i++)r+=n[i]+` >= `+t[i],i<e-1&&(r+=`||`);return r}(t,e,n),a=function(e,t,n,r){if(e===1)return``;var i=r.slice(-2);return`
|
|
2384
2384
|
int r = `+i[0]+`;
|
|
2385
2385
|
int c = `+i[1]+`;
|
|
2386
2386
|
int rp1 = r + 1;
|
|
@@ -2405,7 +2405,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2405
2405
|
setOutput(vec4(`+o+`));
|
|
2406
2406
|
}
|
|
2407
2407
|
}
|
|
2408
|
-
`}},
|
|
2408
|
+
`}},Wo=function(e,t,n){this.variableNames=[`x`],this.outputShape=t.map((function(t,n){return t[0]+e[n]+t[1]}));var r=e.length,i=ga(r),a=t.map((function(e){return e[0]})).join(`,`),o=t.map((function(t,n){return t[0]+e[n]})).join(`,`),s=[`coords[0]`,`coords[1]`,`coords[2]`,`coords[3]`].slice(0,r);this.userCode=r===1?`
|
|
2409
2409
|
int start = `+a+`;
|
|
2410
2410
|
int end = `+o+`;
|
|
2411
2411
|
|
|
@@ -2430,7 +2430,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2430
2430
|
setOutput(getX(`+s+`));
|
|
2431
2431
|
}
|
|
2432
2432
|
}
|
|
2433
|
-
`},
|
|
2433
|
+
`},Go=function(e,t,n){this.variableNames=[`x`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((function(t,n){return t[0]+e[n]+t[1]}));for(var r=e.length,i=ga(r),a=t.map((function(e){return e[0]})).join(`,`),o=t.map((function(t,n){return t[0]+e[n]})).join(`,`),s=na(`rc`,r),c=na(`source`,r),l=s[r-1]+` < `+this.outputShape[r-1],u=r===1?`source`:`vec2(`+c.slice(-2).join()+`)`,d=[i+` rc = outputLoc;`,s[r-1]+` += 1;
|
|
2434
2434
|
if(`+l+`) {
|
|
2435
2435
|
`,r===1?``:`}
|
|
2436
2436
|
rc = outputLoc;
|
|
@@ -2454,7 +2454,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2454
2454
|
`+p+`
|
|
2455
2455
|
setOutput(result);
|
|
2456
2456
|
}
|
|
2457
|
-
`},
|
|
2457
|
+
`},Ko=function(e,t,n){if(this.variableNames=[`x`],t===`avg`&&n)throw Error(`Cannot compute positions for average pool.`);var r=e.filterWidth,i=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,s=e.dilationWidth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;var f=t===`avg`,p=`0.0`;if(f||(p=`-1.0 / 1e-20`),n)this.userCode=`
|
|
2458
2458
|
const ivec2 strides = ivec2(`+i+`, `+a+`);
|
|
2459
2459
|
const ivec2 pads = ivec2(`+u+`, `+d+`);
|
|
2460
2460
|
|
|
@@ -2595,7 +2595,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2595
2595
|
}
|
|
2596
2596
|
setOutput(`+m+`);
|
|
2597
2597
|
}
|
|
2598
|
-
`}},
|
|
2598
|
+
`}},qo=function(e,t,n){if(this.variableNames=[`x`],t===`avg`&&n)throw Error(`Cannot compute positions for average pool.`);var r=e.filterWidth,i=e.strideDepth,a=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,p=e.padInfo.front,m=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;var g=t===`avg`,_=`0.0`;if(g||(_=`-1.0 / 1e-20`),n)this.userCode=`
|
|
2599
2599
|
const ivec3 strides =
|
|
2600
2600
|
ivec3(`+i+`, `+a+`, `+o+`);
|
|
2601
2601
|
const ivec3 pads = ivec3(`+p+`, `+m+`, `+h+`);
|
|
@@ -2759,7 +2759,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2759
2759
|
setOutput(`+v+`);
|
|
2760
2760
|
}
|
|
2761
2761
|
}
|
|
2762
|
-
`}},
|
|
2762
|
+
`}},Jo=function(e,t){this.variableNames=[`x`];var n=e.windowSize,r=e.batchSize,i=e.inSize;this.outputShape=[r,Math.ceil(i/n)];var a=`0.0`,o=``;t===`prod`?a=`1.0`:t===`min`?(a=`1.0 / 1e-20`,o=`min`):t===`max`&&(a=`-1.0 / 1e-20`,o=`max`);var s=t+`(`+t+`(`+t+`(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t===`sum`?s=`sumValue`:t===`prod`?s=`prodValue`:t===`all`?s=`allValue`:t===`any`&&(s=`anyValue`);var c=4*Math.floor(n/4),l=n%4,u=`
|
|
2763
2763
|
if (`+(t===`sum`)+`) {
|
|
2764
2764
|
sumValue += dot(values, ones);
|
|
2765
2765
|
} else if (`+(t===`prod`)+`) {
|
|
@@ -2844,7 +2844,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2844
2844
|
}
|
|
2845
2845
|
setOutput(`+s+`);
|
|
2846
2846
|
}
|
|
2847
|
-
`},
|
|
2847
|
+
`},Yo=function(e,t){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var n=``,r=0;r<4;r++){var i=`thisRC = rc;`;r%2==1&&(i+=`thisRC.z += 1;`),r>1&&(i+=`thisRC.y += 1;`),n+=`
|
|
2848
2848
|
`+i+`
|
|
2849
2849
|
`+(r>0?`if(thisRC.y < rows && thisRC.z < cols){`:``)+`
|
|
2850
2850
|
int flatIndex = getFlatIndex(thisRC);
|
|
@@ -2858,11 +2858,11 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2858
2858
|
`}this.userCode=`
|
|
2859
2859
|
|
|
2860
2860
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
2861
|
-
`+
|
|
2861
|
+
`+ia([`r`,`c`,`d`],t)+`
|
|
2862
2862
|
return ivec3(r, c, d);
|
|
2863
2863
|
}
|
|
2864
2864
|
|
|
2865
|
-
`+
|
|
2865
|
+
`+aa(e)+`
|
|
2866
2866
|
|
|
2867
2867
|
void main() {
|
|
2868
2868
|
ivec3 rc = getOutputCoords();
|
|
@@ -2877,7 +2877,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2877
2877
|
|
|
2878
2878
|
setOutput(result);
|
|
2879
2879
|
}
|
|
2880
|
-
`},
|
|
2880
|
+
`},Xo=function(e,t,n){this.variableNames=[`dy`],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,i=r[1],a=r[2],o=e.shape,s=o[1],c=o[2],l=[n&&s>1?i-1:i,n&&c>1?a-1:a],u=[n&&s>1?s-1:s,n&&c>1?c-1:c],d=l[0]/u[0],f=l[1]/u[1],p=1/d,m=1/f,h=2*Math.ceil(p)+2,g=2*Math.ceil(m)+2;this.userCode=`
|
|
2881
2881
|
void main() {
|
|
2882
2882
|
ivec4 coords = getOutputCoords();
|
|
2883
2883
|
int b = coords[0];
|
|
@@ -2958,7 +2958,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2958
2958
|
|
|
2959
2959
|
setOutput(accumulator);
|
|
2960
2960
|
}
|
|
2961
|
-
`},
|
|
2961
|
+
`},Zo=function(e,t,n,r){this.variableNames=[`A`],this.outputShape=[];var i=e[0],a=e[1],o=e[2];this.outputShape=[i,t,n,e[3]];var s=[r&&t>1?a-1:a,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode=`
|
|
2962
2962
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
2963
2963
|
`+s[0]/c[0]+`,
|
|
2964
2964
|
`+s[1]/c[1]+`);
|
|
@@ -2991,7 +2991,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
2991
2991
|
|
|
2992
2992
|
setOutput(newValue);
|
|
2993
2993
|
}
|
|
2994
|
-
`},
|
|
2994
|
+
`},Qo=function(e,t,n,r){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var i=e[0],a=e[1],o=e[2],s=e[3];this.outputShape=[i,t,n,s];var c=[r&&t>1?a-1:a,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode=`
|
|
2995
2995
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
2996
2996
|
`+c[0]/l[0]+`,
|
|
2997
2997
|
`+c[1]/l[1]+`,
|
|
@@ -3068,7 +3068,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3068
3068
|
|
|
3069
3069
|
setOutput(newValue);
|
|
3070
3070
|
}
|
|
3071
|
-
`}
|
|
3071
|
+
`},$o=function(e,t,n){this.variableNames=[`dy`],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,i=r[1],a=r[2],o=e.shape,s=o[1],c=o[2],l=[n&&s>1?i-1:i,n&&c>1?a-1:a],u=[n&&s>1?s-1:s,n&&c>1?c-1:c],d=l[0]/u[0],f=l[1]/u[1],p=1/d,m=1/f,h=2*Math.ceil(p)+2,g=2*Math.ceil(m)+2;this.userCode=`
|
|
3072
3072
|
void main() {
|
|
3073
3073
|
ivec4 coords = getOutputCoords();
|
|
3074
3074
|
int b = coords[0];
|
|
@@ -3138,7 +3138,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3138
3138
|
|
|
3139
3139
|
setOutput(accumulator);
|
|
3140
3140
|
}
|
|
3141
|
-
`},
|
|
3141
|
+
`},es=function(e,t,n,r){this.variableNames=[`A`],this.outputShape=[];var i=e[0],a=e[1],o=e[2];this.outputShape=[i,t,n,e[3]];var s=[r&&t>1?a-1:a,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],l=r?`0.5`:`0.0`;this.userCode=`
|
|
3142
3142
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
3143
3143
|
`+s[0]/c[0]+`,
|
|
3144
3144
|
`+s[1]/c[1]+`);
|
|
@@ -3161,9 +3161,9 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3161
3161
|
|
|
3162
3162
|
setOutput(newValue);
|
|
3163
3163
|
}
|
|
3164
|
-
`},
|
|
3164
|
+
`},ts=function(e,t){this.variableNames=[`x`];var n=e.length;if(n>4)throw Error(`WebGL backend: Reverse of rank-`+n+` tensor is not yet supported`);if(this.outputShape=e,n!==1){var r=e.map((function(n,r){return function(n){return t.indexOf(n)!==-1&&e[n]!==1?e[n]+` - coords[`+n+`] - 1`:`coords[`+n+`]`}(r)})).join(`,`);this.userCode=`
|
|
3165
3165
|
void main() {
|
|
3166
|
-
`+
|
|
3166
|
+
`+ga(n)+` coords = getOutputCoords();
|
|
3167
3167
|
setOutput(getX(`+r+`));
|
|
3168
3168
|
}
|
|
3169
3169
|
`}else this.userCode=`
|
|
@@ -3171,7 +3171,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3171
3171
|
int coord = getOutputCoords();
|
|
3172
3172
|
setOutput(getX(`+e[0]+` - coord - 1));
|
|
3173
3173
|
}
|
|
3174
|
-
`},
|
|
3174
|
+
`},ns=function(e,t){this.variableNames=[`x`],this.packedInputs=!0,this.packedOutput=!0;var n=e.length;if(n>4)throw Error(`WebGL backend: Reverse of rank-`+n+` tensor is not yet supported`);this.outputShape=e;var r=na(`rc`,n),i=r[n-1]+` + 1 < `+this.outputShape[n-1],a=r[n-2]+` + 1 < `+this.outputShape[n-2],o=ga(n);function s(n){var r=e.map((function(r,i){return function(n,r){return t.indexOf(n)!==-1&&e[n]!==1?e[n]+` - `+r[n]+` - 1`:``+r[n]}(i,n)}));return`getChannel(getX(`+r.join(`,`)+`), vec2(`+r.slice(-2).join(`,`)+`))`}this.userCode=n===1?`
|
|
3175
3175
|
void main(){
|
|
3176
3176
|
int rc = getOutputCoords();
|
|
3177
3177
|
vec4 result = vec4(0.);
|
|
@@ -3199,7 +3199,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3199
3199
|
}
|
|
3200
3200
|
setOutput(result);
|
|
3201
3201
|
}
|
|
3202
|
-
`},
|
|
3202
|
+
`},rs=function(e,t,n,r,i,a,o){o===void 0&&(o=!0),this.variableNames=[`updates`,`indices`,`defaultValue`],this.outputShape=a;var s=ga(i.length),c=ga(a.length),l=``;n===1?l=`i`:n===2&&(l=`i, j`);var u=`getIndices(`+l+`)`,d=``;r===1?d=`i`:r===2&&(d=`i, coords[1]`);var f=`getUpdates(`+d+`)`,p=t>1?`strides[j]`:`strides`;this.userCode=`
|
|
3203
3203
|
`+s+` strides = `+s+`(`+i+`);
|
|
3204
3204
|
|
|
3205
3205
|
void main() {
|
|
@@ -3219,7 +3219,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3219
3219
|
}
|
|
3220
3220
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
3221
3221
|
}
|
|
3222
|
-
`},
|
|
3222
|
+
`},is=function(e,t){this.variableNames=[`x`,`segmentIds`];var n=e.windowSize,r=e.batchSize,i=e.inSize,a=e.numSegments;this.outputShape=[r,a*Math.ceil(i/n)];var o=4*Math.floor(n/4),s=n%4,c=`
|
|
3223
3223
|
sumValue += dot(values, segFilter);
|
|
3224
3224
|
`,l=``;i%n>0&&(l=`
|
|
3225
3225
|
if (inIdx < 0 || inIdx >= `+i+`) {
|
|
@@ -3325,9 +3325,9 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3325
3325
|
}
|
|
3326
3326
|
setOutput(sumValue);
|
|
3327
3327
|
}
|
|
3328
|
-
`},
|
|
3328
|
+
`},as=function(e,t,n){var r,i;if(this.variableNames=[`c`,`a`,`b`],this.outputShape=t,n>4)throw Error(`Where for rank `+n+` is not yet supported`);if(n===1)i=`resRC`,r=`resRC`;else{for(var a=[`resRC.x`,`resRC.y`,`resRC.z`,`resRC.w`],o=[],s=[],c=0;c<t.length;c++)s.push(``+a[c]),c<e&&o.push(``+a[c]);r=o.join(),i=s.join()}this.userCode=`
|
|
3329
3329
|
void main() {
|
|
3330
|
-
`+
|
|
3330
|
+
`+ga(n)+` resRC = getOutputCoords();
|
|
3331
3331
|
float cVal = getC(`+r+`);
|
|
3332
3332
|
if (cVal >= 1.0) {
|
|
3333
3333
|
setOutput(getA(`+i+`));
|
|
@@ -3335,10 +3335,10 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3335
3335
|
setOutput(getB(`+i+`));
|
|
3336
3336
|
}
|
|
3337
3337
|
}
|
|
3338
|
-
`},
|
|
3338
|
+
`},os=function(){function e(e){this.variableNames=[`source`],this.outputShape=e,this.rank=e.length;var t,n=ga(this.rank),r=`uniform int start[`+this.rank+`];`,i=function(e){if(e===1)return`sourceLoc`;if(e<=6)return ss.slice(0,e).map((function(e){return`sourceLoc.`+e})).join(`,`);throw Error(`Slicing for rank `+e+` is not yet supported`)}(this.rank);t=`
|
|
3339
3339
|
`+n+` sourceLoc;
|
|
3340
3340
|
`+n+` coords = getOutputCoords();
|
|
3341
|
-
`+e.map((function(e,t){return`sourceLoc.`+
|
|
3341
|
+
`+e.map((function(e,t){return`sourceLoc.`+ss[t]+` = start[`+t+`] + coords.`+ss[t]+`;`})).join(`
|
|
3342
3342
|
`)+`
|
|
3343
3343
|
`,this.userCode=`
|
|
3344
3344
|
`+r+`
|
|
@@ -3346,7 +3346,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3346
3346
|
`+t+`
|
|
3347
3347
|
setOutput(getSource(`+i+`));
|
|
3348
3348
|
}
|
|
3349
|
-
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error(`The rank (`+this.rank+`) of the program must match the length of start (`+e.length+`)`);return function(n,r){t.startLoc==null&&(t.startLoc=n.getUniformLocationNoThrow(r,`start`),t.startLoc==null)||n.gl.uniform1iv(t.startLoc,e)}},e}(),
|
|
3349
|
+
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error(`The rank (`+this.rank+`) of the program must match the length of start (`+e.length+`)`);return function(n,r){t.startLoc==null&&(t.startLoc=n.getUniformLocationNoThrow(r,`start`),t.startLoc==null)||n.gl.uniform1iv(t.startLoc,e)}},e}(),ss=[`x`,`y`,`z`,`w`,`u`,`v`],cs=function(){function e(e){this.variableNames=[`source`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;var t=ga(this.rank),n=na(`coords`,this.rank),r=na(`sourceLoc`,this.rank),i=this.rank===1?`sourceLoc`:`vec2(`+r.slice(-2).join()+`)`,a=`getChannel(getSource(`+r.join()+`), `+i+`)`,o=`
|
|
3350
3350
|
result.x = `+a+`;
|
|
3351
3351
|
if (++`+n[this.rank-1]+` < `+e[this.rank-1]+`) {
|
|
3352
3352
|
++`+r[this.rank-1]+`;
|
|
@@ -3376,7 +3376,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3376
3376
|
`+s+`
|
|
3377
3377
|
setOutput(result);
|
|
3378
3378
|
}
|
|
3379
|
-
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error(`The rank (`+this.rank+`) of the program must match the length of start (`+e.length+`)`);return function(n,r){t.startLoc==null&&(t.startLoc=n.getUniformLocationNoThrow(r,`start`),t.startLoc==null)||n.gl.uniform1iv(t.startLoc,e)}},e}(),
|
|
3379
|
+
`}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error(`The rank (`+this.rank+`) of the program must match the length of start (`+e.length+`)`);return function(n,r){t.startLoc==null&&(t.startLoc=n.getUniformLocationNoThrow(r,`start`),t.startLoc==null)||n.gl.uniform1iv(t.startLoc,e)}},e}(),ls=function(e,t,n){this.variableNames=[`x`],this.outputShape=n;var r=n.length,i=ga(n.length),a=ga(n.length),o=``;if(r===1)o=`coords * strides + begin`;else{var s=0;o=n.map((function(e,t){return s++,n.length===1?`coords * strides[`+t+`] + begin[`+t+`]`:`coords[`+(s-1)+`] * strides[`+t+`] + begin[`+t+`]`})).join(`,`)}this.userCode=`
|
|
3380
3380
|
`+i+` begin = `+i+`(`+e+`);
|
|
3381
3381
|
`+i+` strides = `+i+`(`+t+`);
|
|
3382
3382
|
|
|
@@ -3384,17 +3384,17 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3384
3384
|
`+a+` coords = getOutputCoords();
|
|
3385
3385
|
setOutput(getX(`+o+`));
|
|
3386
3386
|
}
|
|
3387
|
-
`},
|
|
3387
|
+
`},us=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t,n){var r,i=ds(t,n),a=fs(e,i,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}return this.numUsedTextures++,this.log(),i===yt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):i===yt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):i===yt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):i===yt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):i===yt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(r),r},e.prototype.releaseTexture=function(e,t,n,r){if(this.freeTextures!=null){var i=fs(t,ds(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[i],o=a.indexOf(e);if(o<0)throw Error(`Cannot release a texture that was never provided by this texture manager`);a.splice(o,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log(`Free/Used`,this.numFreeTextures+` / `+this.numUsedTextures,`(`+e+`)`)}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(this.freeTextures!=null){for(var t in this.freeTextures)this.freeTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));for(var t in this.usedTextures)this.usedTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function ds(e,t){if(e===vt.UPLOAD)return yt.PACKED_2X2_FLOAT32;if(e===vt.RENDER||e==null)return function(e){return O().getBool(`WEBGL_RENDER_FLOAT32_ENABLED`)?e?yt.PACKED_2X2_FLOAT32:yt.UNPACKED_FLOAT32:e?yt.PACKED_2X2_FLOAT16:yt.UNPACKED_FLOAT16}(t);if(e===vt.DOWNLOAD||e===vt.PIXELS)return yt.PACKED_4X1_UNSIGNED_BYTE;throw Error(`Unknown logical texture type `+e)}function fs(e,t,n){return e[0]+`_`+e[1]+`_`+t+`_`+n}var ps=function(e,t){this.variableNames=[`A`];for(var n=Array(e.length),r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.rank=n.length;var i=ga(this.rank),a=function(e){var t=e.length;if(t>5)throw Error(`Tile for rank `+t+` is not yet supported`);if(t===1)return`imod(resRC, `+e[0]+`)`;for(var n=[`resRC.x`,`resRC.y`,`resRC.z`,`resRC.w`,`resRC.u`],r=[],i=0;i<e.length;i++)r.push(`imod(`+n[i]+`, `+e[i]+`)`);return r.join()}(e);this.userCode=`
|
|
3388
3388
|
void main() {
|
|
3389
3389
|
`+i+` resRC = getOutputCoords();
|
|
3390
3390
|
setOutput(getA(`+a+`));
|
|
3391
3391
|
}
|
|
3392
|
-
`},
|
|
3392
|
+
`},ms=function(e,t){this.variableNames=[`A`];for(var n=Array(e.length),r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;var i=ga(this.rank),a=function(e){var t=e.length;if(t>6)throw Error(`Transpose for rank `+t+` is not yet supported`);for(var n=[`resRC.x`,`resRC.y`,`resRC.z`,`resRC.w`,`resRC.u`,`resRC.v`],r=Array(t),i=0;i<e.length;i++)r[e[i]]=n[i];return r.join()}(t);this.userCode=`
|
|
3393
3393
|
void main() {
|
|
3394
3394
|
`+i+` resRC = getOutputCoords();
|
|
3395
3395
|
setOutput(getA(`+a+`));
|
|
3396
3396
|
}
|
|
3397
|
-
`},
|
|
3397
|
+
`},hs=function(e,t){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0;for(var n=Array(e.length),r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank `+this.rank+` is not yet supported.`);var i=ga(this.rank),a=ta(`rc`,this.rank),o=Array(this.rank);for(r=0;r<t.length;r++)o[t[r]]=a[r];var s=`vec2(`+o.slice(-2).join()+`)`,c=`++`+a[this.rank-1]+` < `+n[this.rank-1],l=`getChannel(getA(`+o.join()+`), `+s+`)`;this.userCode=`
|
|
3398
3398
|
void main() {
|
|
3399
3399
|
`+i+` rc = getOutputCoords();
|
|
3400
3400
|
vec4 result = vec4(0.);
|
|
@@ -3411,7 +3411,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3411
3411
|
}
|
|
3412
3412
|
setOutput(result);
|
|
3413
3413
|
}
|
|
3414
|
-
`},
|
|
3414
|
+
`},gs=1.7580993408473768,_s=1.0507009873554805,vs=function(e,t){this.variableNames=[`A`],this.outputShape=e,this.userCode=`
|
|
3415
3415
|
float unaryOperation(float x) {
|
|
3416
3416
|
`+t+`
|
|
3417
3417
|
}
|
|
@@ -3422,37 +3422,37 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3422
3422
|
|
|
3423
3423
|
setOutput(y);
|
|
3424
3424
|
}
|
|
3425
|
-
`},
|
|
3425
|
+
`},ys=`if (isnan(x)) return x;`,bs=`return x;`,xs=`return abs(x);`,Ss=ys+`
|
|
3426
3426
|
return (x < 0.0) ? 0.0 : x;
|
|
3427
|
-
`,
|
|
3427
|
+
`,Cs=ys+`
|
|
3428
3428
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
3429
|
-
`,
|
|
3429
|
+
`,ws=`return (x >= 0.0) ? x : (exp(x) - 1.0);`,Ts=`
|
|
3430
3430
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
3431
3431
|
// see: https://arxiv.org/abs/1706.02515
|
|
3432
|
-
float scaleAlpha = `+
|
|
3433
|
-
float scale = `+
|
|
3432
|
+
float scaleAlpha = `+gs+`;
|
|
3433
|
+
float scale = `+_s+`;
|
|
3434
3434
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
3435
|
-
`,
|
|
3435
|
+
`,Es=`return -x;`,Ds=`return ceil(x);`,Os=`return floor(x);`,ks=`return exp(x);`,As=`return exp(x) - 1.0;`,js=ys+`
|
|
3436
3436
|
return sin(x);
|
|
3437
|
-
`,
|
|
3437
|
+
`,Ms=ys+`
|
|
3438
3438
|
return cos(x);
|
|
3439
|
-
`,ys
|
|
3439
|
+
`,Ns=ys+`
|
|
3440
3440
|
if (abs(x) > 1.) {
|
|
3441
3441
|
return NAN;
|
|
3442
3442
|
}
|
|
3443
3443
|
return asin(x);
|
|
3444
|
-
`,
|
|
3444
|
+
`,Ps=ys+`
|
|
3445
3445
|
if (abs(x) > 1.) {
|
|
3446
3446
|
return NAN;
|
|
3447
3447
|
}
|
|
3448
3448
|
return acos(x);
|
|
3449
|
-
`,
|
|
3449
|
+
`,Fs=ys+`
|
|
3450
3450
|
return atan(x);
|
|
3451
|
-
`,
|
|
3451
|
+
`,Is=ys+`return log(x + sqrt(x * x + 1.0));`,Ls=ys+`
|
|
3452
3452
|
if (x < 1.0) return NAN;
|
|
3453
|
-
return log(x + sqrt(x * x - 1.0));`,
|
|
3453
|
+
return log(x + sqrt(x * x - 1.0));`,Rs=ys+`
|
|
3454
3454
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
3455
|
-
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,
|
|
3455
|
+
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,zs=`return x;`,Bs=`return x;`,Vs=`
|
|
3456
3456
|
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
3457
3457
|
bvec4 isNaN = isnan(x);
|
|
3458
3458
|
|
|
@@ -3462,7 +3462,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3462
3462
|
result.a = isNaN.a ? x.a : result.a;
|
|
3463
3463
|
|
|
3464
3464
|
return result;
|
|
3465
|
-
`,
|
|
3465
|
+
`,Hs=`
|
|
3466
3466
|
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
3467
3467
|
bvec4 isNaN = isnan(x);
|
|
3468
3468
|
|
|
@@ -3472,7 +3472,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3472
3472
|
result.a = isNaN.a ? x.a : result.a;
|
|
3473
3473
|
|
|
3474
3474
|
return result;
|
|
3475
|
-
`,
|
|
3475
|
+
`,Us=`
|
|
3476
3476
|
vec4 result;
|
|
3477
3477
|
|
|
3478
3478
|
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
|
|
@@ -3481,7 +3481,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3481
3481
|
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
|
3482
3482
|
|
|
3483
3483
|
return result;
|
|
3484
|
-
`,
|
|
3484
|
+
`,Ws=function(e,t){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
|
|
3485
3485
|
vec4 unaryOperation(vec4 x) {
|
|
3486
3486
|
`+t+`
|
|
3487
3487
|
}
|
|
@@ -3492,35 +3492,35 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3492
3492
|
|
|
3493
3493
|
setOutput(y);
|
|
3494
3494
|
}
|
|
3495
|
-
`},
|
|
3495
|
+
`},Gs=function(e){this.variableNames=[`A`],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;var t=e.length,n=na(`rc`,t),r=ga(t),i=function(e,t){if(e===1)return`rc`;for(var n=``,r=0;r<e;r++)n+=t[r],r<e-1&&(n+=`,`);return n}(t,n),a=n.slice(-2),o=t<=1?`rc`:`vec2(`+a.join(`,`)+`)`;this.userCode=`
|
|
3496
3496
|
void main() {
|
|
3497
3497
|
`+r+` rc = getOutputCoords();
|
|
3498
3498
|
vec4 packedInput = getA(`+i+`);
|
|
3499
3499
|
|
|
3500
3500
|
setOutput(getChannel(packedInput, `+o+`));
|
|
3501
3501
|
}
|
|
3502
|
-
`},Ms={};function Ns(e,t){if(t===void 0&&(t=!1),e===`linear`)return t?Es:os;if(e===`relu`)return t?Ds:cs;if(e===`elu`)return t?ks:us;if(e===`relu6`)return t?Os:ls;if(e===`prelu`)return t?ya:_a;throw Error(`Activation `+e+` has not been implemented for the WebGL backend.`)}var Ps=600,Fs=function(e){function t(t){var n,r=e.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!m().getBool(`HAS_WEBGL`))throw Error(`WebGL is not supported on this device`);if(t==null){var i=dt(m().getNumber(`WEBGL_VERSION`));r.binaryCache=((n=m().getNumber(`WEBGL_VERSION`))in Ms||(Ms[n]={}),Ms[n]),r.gpgpu=new yo(i),r.canvas=i.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=t,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=t.gl.canvas;return r.textureManager=new Zo(r.gpgpu),r.numMBBeforeWarning=m().global.screen==null?1024:m().global.screen.height*m().global.screen.width*window.devicePixelRatio*Ps/1024/1024,r.texData=new ii(r,z),r}return l(t,e),t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,t,n){if(m().getBool(`DEBUG`)&&this.checkNumericalProblems(e),n===`complex64`&&e!=null)throw Error(`Cannot write to a complex64 dtype. Please use tf.complex(real, imag).`);var r={};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:ot.UPLOAD}),r},t.prototype.move=function(e,t,n,r){if(m().getBool(`DEBUG`)&&this.checkNumericalProblems(t),r===`complex64`)throw Error(`Cannot write to a complex64 dtype. Please use tf.complex(real, imag).`);this.texData.set(e,{shape:n,dtype:r,values:t,usage:ot.UPLOAD})},t.prototype.readSync=function(e){var t=this.texData.get(e),n=t.values,r=t.dtype,i=t.complexTensors,a=t.slice,o=t.shape,s=t.isPacked;if(a!=null){var c=void 0;c=s?new As(o,Ts):new Y(o,Ts);var l=this.runWebGLProgram(c,[{dataId:e,shape:o,dtype:r}],r),u=this.readSync(l.dataId);return this.disposeData(l.dataId),u}if(n!=null)return this.convertAndCacheOnCPU(e);if(r===`string`)return n;var d,f,p=this.activeTimers!=null;return p&&(d=Ce()),f=r===`complex64`?Ci(i.real.dataSync(),i.imag.dataSync()):this.getValuesFromTexture(e),p&&(this.downloadWaitMs+=Ce()-d),this.convertAndCacheOnCPU(e,f)},t.prototype.read=function(e){return u(this,void 0,void 0,(function(){var t,n,r,i,a,o,s,c,l,u,f,p,h,g,_,v,y,b,x,S,C,w;return d(this,(function(d){switch(d.label){case 0:if(this.pendingRead.has(e))return t=this.pendingRead.get(e),[2,new Promise((function(e){return t.push(e)}))];if(n=this.texData.get(e),r=n.values,i=n.shape,a=n.slice,o=n.dtype,s=n.complexTensors,c=n.isPacked,a!=null)return l=void 0,l=c?new As(i,Ts):new Y(i,Ts),u=this.runWebGLProgram(l,[{dataId:e,shape:i,dtype:o}],o),f=this.read(u.dataId),this.disposeData(u.dataId),[2,f];if(r!=null)return[2,this.convertAndCacheOnCPU(e)];if(!m().getBool(`WEBGL_DOWNLOAD_FLOAT_ENABLED`)&&m().getNumber(`WEBGL_VERSION`)===2)throw Error(`tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.`);return p=null,o!==`complex64`&&m().get(`WEBGL_BUFFER_SUPPORTED`)&&(h=this.decode(e),g=this.texData.get(h.dataId),p=(w=this.gpgpu).createBufferFromTexture.apply(w,[g.texture].concat(pt(i)))),this.pendingRead.set(e,[]),o===`complex64`?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:d.sent(),d.label=2;case 2:return o===`complex64`?[4,Promise.all([s.real.data(),s.imag.data()])]:[3,4];case 3:return v=d.sent(),y=v[0],b=v[1],_=Ci(y,b),[3,5];case 4:p==null?_=this.getValuesFromTexture(e):(x=M(i),_=this.gpgpu.downloadFloat32MatrixFromBuffer(p,x)),d.label=5;case 5:return h!=null&&this.disposeData(h.dataId),S=this.convertAndCacheOnCPU(e,_),C=this.pendingRead.get(e),this.pendingRead.delete(e),C.forEach((function(e){return e(S)})),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,S]}}))}))},t.prototype.checkNumericalProblems=function(e){if(e!=null)for(var t=0;t<e.length;t++){var n=e[t];if(!vt(n))throw m().getBool(`WEBGL_RENDER_FLOAT32_CAPABLE`)?Error(`The value `+n+` cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value `+n+` cannot be represented on this device.`)}},t.prototype.getValuesFromTexture=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,a=n.isPacked,o=M(r);if(m().getBool(`WEBGL_DOWNLOAD_FLOAT_ENABLED`)){var s=this.decode(e),c=this.texData.get(s.dataId),l=(t=this.gpgpu).downloadMatrixFromPackedTexture.apply(t,[c.texture].concat(pt(r))).subarray(0,o);return this.disposeData(s.dataId),l}var u=m().getBool(`WEBGL_PACK`)&&!0===a,d=u?qt(r):r,f=u?new Ga(d):new Wa(d),p=this.runWebGLProgram(f,[{shape:d,dtype:i,dataId:e}],`float32`),h=this.texData.get(p.dataId),g=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(h.texture,h.texShape[0],h.texShape[1]).subarray(0,o);return this.disposeData(p.dataId),g},t.prototype.time=function(e){return u(this,void 0,void 0,(function(){var t,n,r,i,a,o,s;return d(this,(function(c){switch(c.label){case 0:return t=this.activeTimers,n=[],r=!1,this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),i=j(this.activeTimers.map((function(e){return e.query}))).filter((function(e){return e!=null})),a=j(this.activeTimers.map((function(e){return e.name}))).filter((function(e){return e!=null})),this.activeTimers=t,r&&(this.programTimersStack=null),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?[4,Promise.all(i)]:[3,2];case 1:return s=c.sent(),o.kernelMs=D(s),o.getExtraProfileInfo=function(){return s.map((function(e,t){return{name:a[t],ms:e}})).map((function(e){return e.name+`: `+e.ms})).join(`, `)},[3,3];case 2:o.kernelMs={error:`WebGL query timers are not supported in this environment.`},c.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}}))}))},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?this.gpgpu.beginQuery():{startMs:Ce(),endMs:null}},t.prototype.endTimer=function(e){return m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?(this.gpgpu.endQuery(),e):(e.endMs=Ce(),e)},t.prototype.getQueryTime=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){return m().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]}))}))},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var t=this.texData.get(e),n=t.texture,r=t.dtype,i=t.texShape,a=t.usage,o=t.isPacked,s=t.slice,c=s&&s.origDataId||e,l=this.dataRefCount.get(c);l>1?this.dataRefCount.set(c,l-1):(this.dataRefCount.delete(c),n!=null&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,a,o)));var u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return m().getBool(`WEBGL_CPU_FORWARD`)?(this.cpuBackend??=z.findBackend(`cpu`),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,t){var n=this;return t===void 0&&(t=128),this.getCPUBackend()!=null&&e.every((function(e){return n.texData.get(e.dataId).texture==null&&e.size<t}))},t.prototype.getGPGPUContext=function(){return this.gpgpu},t.prototype.complex=function(e,t){var n=this.makeOutput(e.shape,`complex64`);return this.texData.get(n.dataId).complexTensors={real:z.keep(e.clone()),imag:z.keep(t.clone())},n},t.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,t,n);if(M(n)===0)return On([],n,e.dtype);var r=this.texData.get(e.dataId).isPacked,i=Qr(e.shape,t,n);if(r||!i){var a=m().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new Yo(n):new qo(n),o=a.getCustomSetupFunc(t);return this.compileAndRun(a,[e],null,o)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,n)},t.prototype.shallowSlice=function(e,t,n){var r=this.texData.get(e.dataId),i=this.makeOutput(n,e.dtype),a=this.texData.get(i.dataId);Object.assign(a,r),a.shape=n,a.dtype=e.dtype;var o=$r(t,e.strides);r.slice&&(o+=r.slice.flatOffset),a.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),i},t.prototype.stridedSlice=function(e,t,n,r){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,t,n,r);var i=Yr(t,n,r);if(i.some((function(e){return e===0})))return On([],i);var a=new Xo(t,r,i);return this.compileAndRun(a,[e])},t.prototype.reverse=function(e,t){var n=m().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new Uo(e.shape,t):new Ho(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.concat=function(e,t){if(e[0].dtype===`complex64`){var n=e.map((function(e){return En(e)})),r=e.map((function(e){return Dn(e)}));return Tn(this.concat(n,t),this.concat(r,t))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(e.length===1)return e[0];if(e.length>m().getNumber(`WEBGL_MAX_TEXTURES_IN_SHADER`)){var i=Math.floor(e.length/2),a=this.concat(e.slice(0,i),t),o=this.concat(e.slice(i),t);return this.concat([a,o],t)}if(m().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)&&e[0].rank>1){var s=new Ta(e.map((function(e){return e.shape})),t);return this.compileAndRun(s,e)}var c=wn(e.map((function(e){return e.shape})),t),l=e.map((function(e){return e.as2D(-1,M(e.shape.slice(t)))})),u=new wa(l.map((function(e){return e.shape})));return this.compileAndRun(u,l).reshape(c)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(m().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,fs,e.dtype);var t=new Y(e.shape,fs);return this.compileAndRun(t,[e])},t.prototype.batchMatMul=function(e,t,n,r){var i=n?e.shape[2]:e.shape[1],a=r?t.shape[1]:t.shape[2],o=n?e.shape[1]:e.shape[2],s=e.shape[0];if((i===1||a===1)&&o>1e3){n&&(e=e.transpose([0,2,1])),r&&(t=t.transpose([0,2,1]));var c=a===1?e:e.as3D(s,o,1),l=a===1?2:1,u=a===1?t.as3D(s,1,o):t;return this.multiply(c,u).sum(l,!0)}var d=Ye(e.dtype,t.dtype),f=new Do(e.shape,[s,i,a],n,r);return this.compileAndRun(f,[e,t],d)},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=r?t.shape[2]:t.shape[1],l=i?n.shape[1]:n.shape[2],u=t.shape[0],d=Ye(t.dtype,n.dtype),f=a!=null,p=s!=null,m=o?Ns(o,!0):null,h=new Do(t.shape,[u,c,l],r,i,f,m,p),g=[t,n];return a&&g.push(a),s&&g.push(s),this.compileAndRun(h,g,d)},t.prototype.multiply=function(e,t){if(e.dtype===`complex64`){var n=this.texData.get(e.dataId),r=this.texData.get(t.dataId),i=new pa(da,e.shape,t.shape),a=new pa(fa,e.shape,t.shape),o=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag),this.makeComplexComponentTensorInfo(t,r.complexTensors.real),this.makeComplexComponentTensorInfo(t,r.complexTensors.imag)],s=this.compileAndRun(i,o),c=this.compileAndRun(a,o),l=this.complex(s,c);return s.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(m().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,ga,e.dtype);var u=new va(ga,e.shape,t.shape);return this.compileAndRun(u,[e,t],e.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,a){var o=[e,t,n],s=null;a!=null&&(s=a.shape,o.push(a));var c=null;if(i!=null&&(c=i.shape,o.push(i)),m().getBool(`WEBGL_PACK_NORMALIZATION`)){var l=new ua(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(l,o)}var u=new la(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(u,o)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){var a=m().getBool(`WEBGL_PACK_NORMALIZATION`)?new wo(e.shape,t,n,r,i):new So(e.shape,t,n,r,i);return this.compileAndRun(a,[e])},t.prototype.LRNGrad=function(e,t,n,r,i,a,o){var s=new Co(t.shape,r,i,a,o);return this.compileAndRun(s,[t,n,e])},t.prototype.tile=function(e,t){if(e.dtype===`string`){var n=this.readSync(e.dataId).map((function(e){return Ee(e)}));return Ii(K(e.shape,e.dtype,n),t)}var r=new es(e.shape,t);return this.compileAndRun(r,[e])},t.prototype.pad=function(e,t,n){var r=m().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new Mo(e.shape,t,n):new jo(e.shape,t,n);return this.compileAndRun(r,[e])},t.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var n=m().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new ns(e.shape,t):new ts(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.gather=function(e,t,n){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,n);var r=new Qa(e.shape,t.size,n);return this.compileAndRun(r,[e,t])},t.prototype.batchToSpaceND=function(e,t,n){O(e.rank<=4,(function(){return`batchToSpaceND for rank > 4 with a WebGL backend not implemented yet`}));var r=t.reduce((function(e,t){return e*t})),i=Ir(e.shape,t,r),a=Lr(i.length,t.length),o=Rr(e.shape,t,r),s=zr(n,t.length),c=Br(o,n,t.length);return e.reshape(i).transpose(a).reshape(o).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){O(e.rank<=4,(function(){return`spaceToBatchND for rank > 4 with a WebGL backend not implemented yet`}));var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var a=1+t.length;a<e.shape.length;++a)i.push([0,0]);var o=e.pad(i),s=Ir(o.shape,t,r,!1),c=Lr(s.length,t.length,!1),l=Rr(o.shape,t,r,!1);return o.reshape(s).transpose(c).reshape(l)},t.prototype.reduce=function(e,t,n){var r=e.shape[0],i=e.shape[1],a=new Fo({windowSize:Ur(i),inSize:i,batchSize:r},t),o=this.compileAndRun(a,[e],n);return o.shape[1]===1?o:this.reduce(o,t,n)},t.prototype.argReduce=function(e,t,n){n===void 0&&(n=null);var r=e.shape[0],i=e.shape[1];n!=null&&(r=n.shape[0],i=n.shape[1]);var a=new Vi({windowSize:Ur(i),inSize:i,batchSize:r},t,n==null),o=[e];n!=null&&o.push(n);var s=this.compileAndRun(a,o,`int32`);return s.shape[1]===1?s:this.argReduce(e,t,s)},t.prototype.argReducePacked=function(e,t,n){n===void 0&&(n=null);var r=n==null?e.shape:n.shape,i=new oa(r,Ur(r[r.length-1]),t,n==null),a=n==null?[e]:[e,n],o=this.compileAndRun(i,a,`int32`);return o.rank===e.rank?this.argReducePacked(e,t,o):o},t.prototype.sum=function(e,t){yn(`sum`,t,e.rank);var n=_n(e.shape,t),r=n[0],i=M(n[1]),a=e.as2D(-1,i),o=Xe(e.dtype);return this.reduce(a,`sum`,o).reshape(r)},t.prototype.prod=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,t);var n=_n(e.shape,t),r=n[0],i=M(n[1]),a=e.as2D(-1,i),o=Xe(e.dtype);return this.reduce(a,`prod`,o).reshape(r)},t.prototype.unsortedSegmentSum=function(e,t,n){var r=0,i=bn([r],e.rank),a=e;i!=null&&(a=e.transpose(i),r=Sn(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],i=e.length,a=0;a<i;a++)a===t?r.push(n):r.push(e[a]);return r}(a.shape,r,n),s=M([a.shape[r]]),c=a.as2D(-1,s),l=Xe(e.dtype),u=this.segOpCompute(c,`unsortedSegmentSum`,t,l,n).reshape(o);return i!=null&&(u=u.transpose(xn(i))),u},t.prototype.segOpCompute=function(e,t,n,r,i){var a=e.shape[0],o=e.shape[1],s=function(e,t){var n,r=!1;for(e<=Hr?(n=e,r=!0):n=_e(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=_e(e,n+1);return n}(o,i),c=new Go({windowSize:s,inSize:o,batchSize:a,numSegments:i},t),l=this.compileAndRun(c,[e,n],r);return l.shape[1]===i?l:(n=Vn(0,i).tile([o/s]),this.segOpCompute(l,t,n,r,i))},t.prototype.argMinMaxReduce=function(e,t,n){var r=[t];if(yn(`arg`+n.charAt(0).toUpperCase()+n.slice(1),r,e.rank),!m().getBool(`WEBGL_PACK_REDUCE`)||e.rank<=2){var i=_n(e.shape,r),a=i[0],o=M(i[1]),s=e.as2D(-1,o);return this.argReduce(s,n).reshape(a)}return this.argReducePacked(e,n)},t.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,`min`)},t.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,`max`)},t.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw Error(`WebGL cumsum shader expects an inner-most axis=`+(e.rank-1)+` but got axis=`+t);var i=new Ra(e.shape,n,r);return this.compileAndRun(i,[e])},t.prototype.equal=function(e,t){if(m().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3502
|
+
`},Ks={};function qs(e,t){if(t===void 0&&(t=!1),e===`linear`)return t?Bs:bs;if(e===`relu`)return t?Vs:Ss;if(e===`elu`)return t?Us:ws;if(e===`relu6`)return t?Hs:Cs;if(e===`prelu`)return t?Ma:Aa;throw Error(`Activation `+e+` has not been implemented for the WebGL backend.`)}var Js=600,Ys=function(e){function t(t){var n,r=e.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!O().getBool(`HAS_WEBGL`))throw Error(`WebGL is not supported on this device`);if(t==null){var i=Ct(O().getNumber(`WEBGL_VERSION`));r.binaryCache=((n=O().getNumber(`WEBGL_VERSION`))in Ks||(Ks[n]={}),Ks[n]),r.gpgpu=new Mo(i),r.canvas=i.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=t,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=t.gl.canvas;return r.textureManager=new us(r.gpgpu),r.numMBBeforeWarning=O().global.screen==null?1024:O().global.screen.height*O().global.screen.width*window.devicePixelRatio*Js/1024/1024,r.texData=new gi(r,V),r}return C(t,e),t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,t,n){if(O().getBool(`DEBUG`)&&this.checkNumericalProblems(e),n===`complex64`&&e!=null)throw Error(`Cannot write to a complex64 dtype. Please use tf.complex(real, imag).`);var r={};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:vt.UPLOAD}),r},t.prototype.move=function(e,t,n,r){if(O().getBool(`DEBUG`)&&this.checkNumericalProblems(t),r===`complex64`)throw Error(`Cannot write to a complex64 dtype. Please use tf.complex(real, imag).`);this.texData.set(e,{shape:n,dtype:r,values:t,usage:vt.UPLOAD})},t.prototype.readSync=function(e){var t=this.texData.get(e),n=t.values,r=t.dtype,i=t.complexTensors,a=t.slice,o=t.shape,s=t.isPacked;if(a!=null){var c=void 0;c=s?new Ws(o,zs):new vs(o,zs);var l=this.runWebGLProgram(c,[{dataId:e,shape:o,dtype:r}],r),u=this.readSync(l.dataId);return this.disposeData(l.dataId),u}if(n!=null)return this.convertAndCacheOnCPU(e);if(r===`string`)return n;var d,f,p=this.activeTimers!=null;return p&&(d=Fe()),f=r===`complex64`?Ii(i.real.dataSync(),i.imag.dataSync()):this.getValuesFromTexture(e),p&&(this.downloadWaitMs+=Fe()-d),this.convertAndCacheOnCPU(e,f)},t.prototype.read=function(e){return w(this,void 0,void 0,(function(){var t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S;return T(this,(function(C){switch(C.label){case 0:if(this.pendingRead.has(e))return t=this.pendingRead.get(e),[2,new Promise((function(e){return t.push(e)}))];if(n=this.texData.get(e),r=n.values,i=n.shape,a=n.slice,o=n.dtype,s=n.complexTensors,c=n.isPacked,a!=null)return l=void 0,l=c?new Ws(i,zs):new vs(i,zs),u=this.runWebGLProgram(l,[{dataId:e,shape:i,dtype:o}],o),d=this.read(u.dataId),this.disposeData(u.dataId),[2,d];if(r!=null)return[2,this.convertAndCacheOnCPU(e)];if(!O().getBool(`WEBGL_DOWNLOAD_FLOAT_ENABLED`)&&O().getNumber(`WEBGL_VERSION`)===2)throw Error(`tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.`);return f=null,o!==`complex64`&&O().get(`WEBGL_BUFFER_SUPPORTED`)&&(p=this.decode(e),m=this.texData.get(p.dataId),f=(S=this.gpgpu).createBufferFromTexture.apply(S,[m.texture].concat(Tt(i)))),this.pendingRead.set(e,[]),o===`complex64`?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:C.sent(),C.label=2;case 2:return o===`complex64`?[4,Promise.all([s.real.data(),s.imag.data()])]:[3,4];case 3:return g=C.sent(),_=g[0],v=g[1],h=Ii(_,v),[3,5];case 4:f==null?h=this.getValuesFromTexture(e):(y=R(i),h=this.gpgpu.downloadFloat32MatrixFromBuffer(f,y)),C.label=5;case 5:return p!=null&&this.disposeData(p.dataId),b=this.convertAndCacheOnCPU(e,h),x=this.pendingRead.get(e),this.pendingRead.delete(e),x.forEach((function(e){return e(b)})),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,b]}}))}))},t.prototype.checkNumericalProblems=function(e){if(e!=null)for(var t=0;t<e.length;t++){var n=e[t];if(!At(n))throw O().getBool(`WEBGL_RENDER_FLOAT32_CAPABLE`)?Error(`The value `+n+` cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value `+n+` cannot be represented on this device.`)}},t.prototype.getValuesFromTexture=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,a=n.isPacked,o=R(r);if(O().getBool(`WEBGL_DOWNLOAD_FLOAT_ENABLED`)){var s=this.decode(e),c=this.texData.get(s.dataId),l=(t=this.gpgpu).downloadMatrixFromPackedTexture.apply(t,[c.texture].concat(Tt(r))).subarray(0,o);return this.disposeData(s.dataId),l}var u=O().getBool(`WEBGL_PACK`)&&!0===a,d=u?on(r):r,f=u?new io(d):new ro(d),p=this.runWebGLProgram(f,[{shape:d,dtype:i,dataId:e}],`float32`),m=this.texData.get(p.dataId),h=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,o);return this.disposeData(p.dataId),h},t.prototype.time=function(e){return w(this,void 0,void 0,(function(){var t,n,r,i,a,o,s;return T(this,(function(c){switch(c.label){case 0:return t=this.activeTimers,n=[],r=!1,this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),i=se(this.activeTimers.map((function(e){return e.query}))).filter((function(e){return e!=null})),a=se(this.activeTimers.map((function(e){return e.name}))).filter((function(e){return e!=null})),this.activeTimers=t,r&&(this.programTimersStack=null),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?[4,Promise.all(i)]:[3,2];case 1:return s=c.sent(),o.kernelMs=ae(s),o.getExtraProfileInfo=function(){return s.map((function(e,t){return{name:a[t],ms:e}})).map((function(e){return e.name+`: `+e.ms})).join(`, `)},[3,3];case 2:o.kernelMs={error:`WebGL query timers are not supported in this environment.`},c.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}}))}))},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?this.gpgpu.beginQuery():{startMs:Fe(),endMs:null}},t.prototype.endTimer=function(e){return O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?(this.gpgpu.endQuery(),e):(e.endMs=Fe(),e)},t.prototype.getQueryTime=function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){return O().getNumber(`WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE`)>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]}))}))},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var t=this.texData.get(e),n=t.texture,r=t.dtype,i=t.texShape,a=t.usage,o=t.isPacked,s=t.slice,c=s&&s.origDataId||e,l=this.dataRefCount.get(c);l>1?this.dataRefCount.set(c,l-1):(this.dataRefCount.delete(c),n!=null&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,a,o)));var u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return O().getBool(`WEBGL_CPU_FORWARD`)?(this.cpuBackend??=V.findBackend(`cpu`),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,t){var n=this;return t===void 0&&(t=128),this.getCPUBackend()!=null&&e.every((function(e){return n.texData.get(e.dataId).texture==null&&e.size<t}))},t.prototype.getGPGPUContext=function(){return this.gpgpu},t.prototype.complex=function(e,t){var n=this.makeOutput(e.shape,`complex64`);return this.texData.get(n.dataId).complexTensors={real:V.keep(e.clone()),imag:V.keep(t.clone())},n},t.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,t,n);if(R(n)===0)return Bn([],n,e.dtype);var r=this.texData.get(e.dataId).isPacked,i=ui(e.shape,t,n);if(r||!i){var a=O().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new cs(n):new os(n),o=a.getCustomSetupFunc(t);return this.compileAndRun(a,[e],null,o)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,n)},t.prototype.shallowSlice=function(e,t,n){var r=this.texData.get(e.dataId),i=this.makeOutput(n,e.dtype),a=this.texData.get(i.dataId);Object.assign(a,r),a.shape=n,a.dtype=e.dtype;var o=di(t,e.strides);r.slice&&(o+=r.slice.flatOffset),a.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),i},t.prototype.stridedSlice=function(e,t,n,r){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,t,n,r);var i=si(t,n,r);if(i.some((function(e){return e===0})))return Bn([],i);var a=new ls(t,r,i);return this.compileAndRun(a,[e])},t.prototype.reverse=function(e,t){var n=O().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new ns(e.shape,t):new ts(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.concat=function(e,t){if(e[0].dtype===`complex64`){var n=e.map((function(e){return Rn(e)})),r=e.map((function(e){return zn(e)}));return Ln(this.concat(n,t),this.concat(r,t))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(e.length===1)return e[0];if(e.length>O().getNumber(`WEBGL_MAX_TEXTURES_IN_SHADER`)){var i=Math.floor(e.length/2),a=this.concat(e.slice(0,i),t),o=this.concat(e.slice(i),t);return this.concat([a,o],t)}if(O().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)&&e[0].rank>1){var s=new Ra(e.map((function(e){return e.shape})),t);return this.compileAndRun(s,e)}var c=In(e.map((function(e){return e.shape})),t),l=e.map((function(e){return e.as2D(-1,R(e.shape.slice(t)))})),u=new La(l.map((function(e){return e.shape})));return this.compileAndRun(u,l).reshape(c)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,Es,e.dtype);var t=new vs(e.shape,Es);return this.compileAndRun(t,[e])},t.prototype.batchMatMul=function(e,t,n,r){var i=n?e.shape[2]:e.shape[1],a=r?t.shape[1]:t.shape[2],o=n?e.shape[1]:e.shape[2],s=e.shape[0];if((i===1||a===1)&&o>1e3){n&&(e=e.transpose([0,2,1])),r&&(t=t.transpose([0,2,1]));var c=a===1?e:e.as3D(s,o,1),l=a===1?2:1,u=a===1?t.as3D(s,1,o):t;return this.multiply(c,u).sum(l,!0)}var d=st(e.dtype,t.dtype),f=new Bo(e.shape,[s,i,a],n,r);return this.compileAndRun(f,[e,t],d)},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=r?t.shape[2]:t.shape[1],l=i?n.shape[1]:n.shape[2],u=t.shape[0],d=st(t.dtype,n.dtype),f=a!=null,p=s!=null,m=o?qs(o,!0):null,h=new Bo(t.shape,[u,c,l],r,i,f,m,p),g=[t,n];return a&&g.push(a),s&&g.push(s),this.compileAndRun(h,g,d)},t.prototype.multiply=function(e,t){if(e.dtype===`complex64`){var n=this.texData.get(e.dataId),r=this.texData.get(t.dataId),i=new Ea(wa,e.shape,t.shape),a=new Ea(Ta,e.shape,t.shape),o=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag),this.makeComplexComponentTensorInfo(t,r.complexTensors.real),this.makeComplexComponentTensorInfo(t,r.complexTensors.imag)],s=this.compileAndRun(i,o),c=this.compileAndRun(a,o),l=this.complex(s,c);return s.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,ka,e.dtype);var u=new ja(ka,e.shape,t.shape);return this.compileAndRun(u,[e,t],e.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,a){var o=[e,t,n],s=null;a!=null&&(s=a.shape,o.push(a));var c=null;if(i!=null&&(c=i.shape,o.push(i)),O().getBool(`WEBGL_PACK_NORMALIZATION`)){var l=new Ca(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(l,o)}var u=new Sa(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(u,o)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){var a=O().getBool(`WEBGL_PACK_NORMALIZATION`)?new Lo(e.shape,t,n,r,i):new Fo(e.shape,t,n,r,i);return this.compileAndRun(a,[e])},t.prototype.LRNGrad=function(e,t,n,r,i,a,o){var s=new Io(t.shape,r,i,a,o);return this.compileAndRun(s,[t,n,e])},t.prototype.tile=function(e,t){if(e.dtype===`string`){var n=this.readSync(e.dataId).map((function(e){return Re(e)}));return Yi(J(e.shape,e.dtype,n),t)}var r=new ps(e.shape,t);return this.compileAndRun(r,[e])},t.prototype.pad=function(e,t,n){var r=O().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new Go(e.shape,t,n):new Wo(e.shape,t,n);return this.compileAndRun(r,[e])},t.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var n=O().getBool(`WEBGL_PACK_ARRAY_OPERATIONS`)?new hs(e.shape,t):new ms(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.gather=function(e,t,n){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,n);var r=new fo(e.shape,t.size,n);return this.compileAndRun(r,[e,t])},t.prototype.batchToSpaceND=function(e,t,n){I(e.rank<=4,(function(){return`batchToSpaceND for rank > 4 with a WebGL backend not implemented yet`}));var r=t.reduce((function(e,t){return e*t})),i=Jr(e.shape,t,r),a=Yr(i.length,t.length),o=Xr(e.shape,t,r),s=Zr(n,t.length),c=Qr(o,n,t.length);return e.reshape(i).transpose(a).reshape(o).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){I(e.rank<=4,(function(){return`spaceToBatchND for rank > 4 with a WebGL backend not implemented yet`}));var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var a=1+t.length;a<e.shape.length;++a)i.push([0,0]);var o=e.pad(i),s=Jr(o.shape,t,r,!1),c=Yr(s.length,t.length,!1),l=Xr(o.shape,t,r,!1);return o.reshape(s).transpose(c).reshape(l)},t.prototype.reduce=function(e,t,n){var r=e.shape[0],i=e.shape[1],a=new Jo({windowSize:ti(i),inSize:i,batchSize:r},t),o=this.compileAndRun(a,[e],n);return o.shape[1]===1?o:this.reduce(o,t,n)},t.prototype.argReduce=function(e,t,n){n===void 0&&(n=null);var r=e.shape[0],i=e.shape[1];n!=null&&(r=n.shape[0],i=n.shape[1]);var a=new ea({windowSize:ti(i),inSize:i,batchSize:r},t,n==null),o=[e];n!=null&&o.push(n);var s=this.compileAndRun(a,o,`int32`);return s.shape[1]===1?s:this.argReduce(e,t,s)},t.prototype.argReducePacked=function(e,t,n){n===void 0&&(n=null);var r=n==null?e.shape:n.shape,i=new ya(r,ti(r[r.length-1]),t,n==null),a=n==null?[e]:[e,n],o=this.compileAndRun(i,a,`int32`);return o.rank===e.rank?this.argReducePacked(e,t,o):o},t.prototype.sum=function(e,t){jn(`sum`,t,e.rank);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i),o=ct(e.dtype);return this.reduce(a,`sum`,o).reshape(r)},t.prototype.prod=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,t);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i),o=ct(e.dtype);return this.reduce(a,`prod`,o).reshape(r)},t.prototype.unsortedSegmentSum=function(e,t,n){var r=0,i=Mn([r],e.rank),a=e;i!=null&&(a=e.transpose(i),r=Pn(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],i=e.length,a=0;a<i;a++)a===t?r.push(n):r.push(e[a]);return r}(a.shape,r,n),s=R([a.shape[r]]),c=a.as2D(-1,s),l=ct(e.dtype),u=this.segOpCompute(c,`unsortedSegmentSum`,t,l,n).reshape(o);return i!=null&&(u=u.transpose(Nn(i))),u},t.prototype.segOpCompute=function(e,t,n,r,i){var a=e.shape[0],o=e.shape[1],s=function(e,t){var n,r=!1;for(e<=ei?(n=e,r=!0):n=ke(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=ke(e,n+1);return n}(o,i),c=new is({windowSize:s,inSize:o,batchSize:a,numSegments:i},t),l=this.compileAndRun(c,[e,n],r);return l.shape[1]===i?l:(n=$n(0,i).tile([o/s]),this.segOpCompute(l,t,n,r,i))},t.prototype.argMinMaxReduce=function(e,t,n){var r=[t];if(jn(`arg`+n.charAt(0).toUpperCase()+n.slice(1),r,e.rank),!O().getBool(`WEBGL_PACK_REDUCE`)||e.rank<=2){var i=kn(e.shape,r),a=i[0],o=R(i[1]),s=e.as2D(-1,o);return this.argReduce(s,n).reshape(a)}return this.argReducePacked(e,n)},t.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,`min`)},t.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,`max`)},t.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw Error(`WebGL cumsum shader expects an inner-most axis=`+(e.rank-1)+` but got axis=`+t);var i=new Za(e.shape,n,r);return this.compileAndRun(i,[e])},t.prototype.equal=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3503
3503
|
return vec4(equal(a, b));
|
|
3504
|
-
`,`bool`);var n=new
|
|
3504
|
+
`,`bool`);var n=new ja(`return float(a == b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.notEqual=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3505
3505
|
return vec4(notEqual(a, b));
|
|
3506
|
-
`,`bool`);var n=new
|
|
3506
|
+
`,`bool`);var n=new ja(`return float(a != b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3507
3507
|
return vec4(lessThan(a, b));
|
|
3508
|
-
`,`bool`);var n=new
|
|
3508
|
+
`,`bool`);var n=new ja(`return float(a < b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.lessEqual=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3509
3509
|
return vec4(lessThanEqual(a, b));
|
|
3510
|
-
`,`bool`);var n=new
|
|
3510
|
+
`,`bool`);var n=new ja(`return float(a <= b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3511
3511
|
return vec4(greaterThan(a, b));
|
|
3512
|
-
`,`bool`);var n=new
|
|
3512
|
+
`,`bool`);var n=new ja(`return float(a > b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.greaterEqual=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3513
3513
|
return vec4(greaterThanEqual(a, b));
|
|
3514
|
-
`,`bool`);var n=new
|
|
3514
|
+
`,`bool`);var n=new ja(`return float(a >= b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.logicalNot=function(e){var t=new vs(e.shape,`return float(!(x >= 1.0));`);return this.compileAndRun(t,[e])},t.prototype.logicalAnd=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3515
3515
|
return vec4(
|
|
3516
3516
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
3517
3517
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
3518
|
-
`,`bool`);var n=new
|
|
3518
|
+
`,`bool`);var n=new ja(`return float(a >= 1.0 && b >= 1.0);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.logicalOr=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3519
3519
|
return min(
|
|
3520
3520
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
3521
3521
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
3522
3522
|
vec4(1.0));
|
|
3523
|
-
`,`bool`);var n=new
|
|
3523
|
+
`,`bool`);var n=new ja(`return float(a >= 1.0 || b >= 1.0);`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`bool`)},t.prototype.select=function(e,t,n){var r=new as(e.rank,t.shape,t.rank);return this.compileAndRun(r,[e,t,n],st(t.dtype,n.dtype))},t.prototype.where=function(e){Cn(`tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead`);var t=e.dataSync();return Zi(e.shape,t)},t.prototype.topk=function(e,t,n){return Xi(e.dataSync(),e.shape,e.dtype,t)},t.prototype.min=function(e,t){jn(`min`,t,e.rank);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i);return this.reduce(a,`min`,a.dtype).reshape(r)},t.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3524
3524
|
vec4 result = vec4(min(a, b));
|
|
3525
3525
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
3526
3526
|
|
|
@@ -3530,12 +3530,12 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3530
3530
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
3531
3531
|
|
|
3532
3532
|
return result;
|
|
3533
|
-
`,e.shape,t.shape):new
|
|
3533
|
+
`,e.shape,t.shape):new ja(`
|
|
3534
3534
|
if (isnan(a)) return a;
|
|
3535
3535
|
if (isnan(b)) return b;
|
|
3536
3536
|
|
|
3537
3537
|
return min(a, b);
|
|
3538
|
-
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.mod=function(e,t){var n=
|
|
3538
|
+
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.mod=function(e,t){var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3539
3539
|
vec4 result = mod(a, b);
|
|
3540
3540
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
3541
3541
|
|
|
@@ -3545,8 +3545,8 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3545
3545
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
3546
3546
|
|
|
3547
3547
|
return result;
|
|
3548
|
-
`,e.shape,t.shape):new
|
|
3549
|
-
return mod(a, b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);
|
|
3548
|
+
`,e.shape,t.shape):new ja(`if (b == 0.0) return NAN;
|
|
3549
|
+
return mod(a, b);`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);jn(`max`,t,e.rank);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i);return this.reduce(a,`max`,a.dtype).reshape(r)},t.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3550
3550
|
vec4 result = vec4(max(a, b));
|
|
3551
3551
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
3552
3552
|
|
|
@@ -3556,12 +3556,12 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3556
3556
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
3557
3557
|
|
|
3558
3558
|
return result;
|
|
3559
|
-
`,e.shape,t.shape):new
|
|
3559
|
+
`,e.shape,t.shape):new ja(`
|
|
3560
3560
|
if (isnan(a)) return a;
|
|
3561
3561
|
if (isnan(b)) return b;
|
|
3562
3562
|
|
|
3563
3563
|
return max(a, b);
|
|
3564
|
-
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.all=function(e,t){
|
|
3564
|
+
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.all=function(e,t){jn(`all`,t,e.rank);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i);return this.reduce(a,`all`,a.dtype).reshape(r)},t.prototype.any=function(e,t){jn(`any`,t,e.rank);var n=kn(e.shape,t),r=n[0],i=R(n[1]),a=e.as2D(-1,i);return this.reduce(a,`any`,a.dtype).reshape(r)},t.prototype.realDivide=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3565
3565
|
// vec4 one = vec4(equal(a, b));
|
|
3566
3566
|
// return one + (vec4(1.0) - one) * a / b;
|
|
3567
3567
|
vec4 result = a / b;
|
|
@@ -3579,11 +3579,11 @@ vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
|
3579
3579
|
}
|
|
3580
3580
|
|
|
3581
3581
|
return result;
|
|
3582
|
-
`,`float32`,!0);var n=new
|
|
3582
|
+
`,`float32`,!0);var n=new ja(`
|
|
3583
3583
|
if (a == b) {
|
|
3584
3584
|
return 1.0;
|
|
3585
3585
|
};
|
|
3586
|
-
return a / b;`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`float32`)},t.prototype.floorDiv=function(e,t){if(
|
|
3586
|
+
return a / b;`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`float32`)},t.prototype.floorDiv=function(e,t){if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,`
|
|
3587
3587
|
ivec4 ia = round(a);
|
|
3588
3588
|
ivec4 ib = round(b);
|
|
3589
3589
|
bvec4 cond = notEqual(ib, ivec4(0));
|
|
@@ -3604,7 +3604,7 @@ return a / b;`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`float32`)},t.
|
|
|
3604
3604
|
result[3] = idiv(ia[3], ib[3], s[3]);
|
|
3605
3605
|
}
|
|
3606
3606
|
return vec4(result);
|
|
3607
|
-
`,`int32`);var n=new
|
|
3607
|
+
`,`int32`);var n=new ja(`
|
|
3608
3608
|
float s = sign(a) * sign(b);
|
|
3609
3609
|
int ia = round(a);
|
|
3610
3610
|
int ib = round(b);
|
|
@@ -3614,7 +3614,7 @@ return a / b;`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`float32`)},t.
|
|
|
3614
3614
|
} else {
|
|
3615
3615
|
return NAN;
|
|
3616
3616
|
}
|
|
3617
|
-
`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`int32`)},t.prototype.add=function(e,t){if(e.dtype===`complex64`&&t.dtype===`complex64`)return this.complexSeparableBinaryOp(e,t,
|
|
3617
|
+
`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`int32`)},t.prototype.add=function(e,t){if(e.dtype===`complex64`&&t.dtype===`complex64`)return this.complexSeparableBinaryOp(e,t,Da);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);var n=st(e.dtype,t.dtype);if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,Da,n);var r=new ja(Da,e.shape,t.shape);return this.compileAndRun(r,[e,t],n)},t.prototype.packedUnaryOp=function(e,t,n){var r=new Ws(e.shape,t);return this.compileAndRun(r,[e],n)},t.prototype.packedBinaryOp=function(e,t,n,r,i){i===void 0&&(i=!1);var a=new Na(n,e.shape,t.shape,i);return this.compileAndRun(a,[e,t],r)},t.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,i=this.texData.get(e.dataId),a=this.texData.get(t.dataId),o=[[i.complexTensors.real,a.complexTensors.real],[i.complexTensors.imag,a.complexTensors.imag]].map((function(i){var a=i[0],o=i[1],s=r.makeComplexComponentTensorInfo(e,a),c=r.makeComplexComponentTensorInfo(t,o),l=new ja(n,e.shape,t.shape);return r.compileAndRun(l,[s,c],st(a.dtype,o.dtype))})),s=o[0],c=o[1],l=this.complex(s,c);return s.dispose(),c.dispose(),l},t.prototype.makeComplexComponentTensorInfo=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},t.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>O().get(`WEBGL_MAX_TEXTURES_IN_SHADER`)){var t=Math.floor(e.length/2),n=this.addN(e.slice(0,t)),r=this.addN(e.slice(t));return this.addN([n,r])}var i=e.map((function(e){return e.dtype})).reduce((function(e,t){return st(e,t)})),a=e.map((function(e){return e.shape})),o=O().getBool(`WEBGL_PACK`)?new $i(e[0].shape,a):new Qi(e[0].shape,a);return this.compileAndRun(o,e,i)},t.prototype.subtract=function(e,t){if(e.dtype===`complex64`&&t.dtype===`complex64`)return this.complexSeparableBinaryOp(e,t,Oa);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);var n=st(e.dtype,t.dtype);if(O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`))return this.packedBinaryOp(e,t,Oa,e.dtype);var r=new ja(Oa,e.shape,t.shape);return this.compileAndRun(r,[e,t],n)},t.prototype.pow=function(e,t){var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3618
3618
|
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
|
|
3619
3619
|
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
|
|
3620
3620
|
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
|
|
@@ -3635,7 +3635,7 @@ return a / b;`,e.shape,t.shape);return this.compileAndRun(n,[e,t],`float32`)},t.
|
|
|
3635
3635
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
3636
3636
|
|
|
3637
3637
|
return result;
|
|
3638
|
-
`,e.shape,t.shape):new
|
|
3638
|
+
`,e.shape,t.shape):new ja(`
|
|
3639
3639
|
if(a < 0.0 && floor(b) < b){
|
|
3640
3640
|
return NAN;
|
|
3641
3641
|
}
|
|
@@ -3644,10 +3644,10 @@ if (b == 0.0) {
|
|
|
3644
3644
|
}
|
|
3645
3645
|
return (round(mod(b, 2.0)) != 1) ?
|
|
3646
3646
|
pow(abs(a), b) : sign(a) * pow(abs(a), b);
|
|
3647
|
-
`,e.shape,t.shape),r=
|
|
3647
|
+
`,e.shape,t.shape),r=st(e.dtype,t.dtype);return this.compileAndRun(n,[e,t],r)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,Ds,e.dtype);var t=new vs(e.shape,Ds);return this.compileAndRun(t,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,Os,e.dtype);var t=new vs(e.shape,Os);return this.compileAndRun(t,[e])},t.prototype.sign=function(e){var t=new vs(e.shape,`
|
|
3648
3648
|
if (isnan(x)) { return 0.0; }
|
|
3649
3649
|
return sign(x);
|
|
3650
|
-
`);return this.compileAndRun(t,[e])},t.prototype.isNaN=function(e){var t=new
|
|
3650
|
+
`);return this.compileAndRun(t,[e])},t.prototype.isNaN=function(e){var t=new vs(e.shape,`return float(isnan(x));`);return this.compileAndRun(t,[e],`bool`)},t.prototype.isInf=function(e){var t=new vs(e.shape,`return float(isinf(x));`);return this.compileAndRun(t,[e],`bool`)},t.prototype.isFinite=function(e){var t=new vs(e.shape,`return float(!isnan(x) && !isinf(x));`);return this.compileAndRun(t,[e],`bool`)},t.prototype.round=function(e){var t=new vs(e.shape,`
|
|
3651
3651
|
// OpenGL ES does not support round function.
|
|
3652
3652
|
// The algorithm is based on banker's rounding.
|
|
3653
3653
|
float base = floor(x);
|
|
@@ -3662,7 +3662,7 @@ return (round(mod(b, 2.0)) != 1) ?
|
|
|
3662
3662
|
return base + 1.0;
|
|
3663
3663
|
}
|
|
3664
3664
|
}
|
|
3665
|
-
`);return this.compileAndRun(t,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(
|
|
3665
|
+
`);return this.compileAndRun(t,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,ks,e.dtype);var t=new vs(e.shape,ks);return this.compileAndRun(t,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,As,e.dtype);var t=new vs(e.shape,As);return this.compileAndRun(t,[e])},t.prototype.softmax=function(e,t){var n=me([t],e.shape),r=this.max(e,n),i=An(r.shape,n),a=this.subtract(e,r.reshape(i)),o=this.exp(a),s=this.sum(o,n).reshape(i);return this.realDivide(o,s)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,`
|
|
3666
3666
|
vec4 result = log(x);
|
|
3667
3667
|
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
|
|
3668
3668
|
result.r = isNaN.r == 1.0 ? NAN : result.r;
|
|
@@ -3671,11 +3671,11 @@ return (round(mod(b, 2.0)) != 1) ?
|
|
|
3671
3671
|
result.a = isNaN.a == 1.0 ? NAN : result.a;
|
|
3672
3672
|
|
|
3673
3673
|
return result;
|
|
3674
|
-
`,e.dtype);var t=new
|
|
3675
|
-
return log(x);`);return this.compileAndRun(t,[e])},t.prototype.log1p=function(e){var t=new
|
|
3674
|
+
`,e.dtype);var t=new vs(e.shape,`if (x < 0.0) return NAN;
|
|
3675
|
+
return log(x);`);return this.compileAndRun(t,[e])},t.prototype.log1p=function(e){var t=new vs(e.shape,`return log(1.0 + x);`);return this.compileAndRun(t,[e])},t.prototype.sqrt=function(e){var t=new vs(e.shape,`return sqrt(x);`);return this.compileAndRun(t,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var t=new vs(e.shape,`return inversesqrt(x);`);return this.compileAndRun(t,[e])},t.prototype.reciprocal=function(e){var t=new vs(e.shape,`return 1.0 / x;`);return this.compileAndRun(t,[e])},t.prototype.relu=function(e){var t;return t=O().getBool(`WEBGL_PACK`)?new Ws(e.shape,Vs):new vs(e.shape,Ss),this.compileAndRun(t,[e])},t.prototype.relu6=function(e){var t;return t=O().getBool(`WEBGL_PACK`)?new Ws(e.shape,Hs):new vs(e.shape,Cs),this.compileAndRun(t,[e])},t.prototype.prelu=function(e,t){var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(Ma,e.shape,t.shape):new ja(Aa,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.elu=function(e){if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,Us,e.dtype);var t=new vs(e.shape,ws);return this.compileAndRun(t,[e])},t.prototype.eluDer=function(e,t){var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3676
3676
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
3677
3677
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
3678
|
-
`,e.shape,t.shape):new
|
|
3678
|
+
`,e.shape,t.shape):new ja(`return (b >= 1.0) ? a : a * (b + 1.0);`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.selu=function(e){var t=new vs(e.shape,Ts);return this.compileAndRun(t,[e])},t.prototype.int=function(e){var t=new vs(e.shape,`return float(int(x));`);return this.compileAndRun(t,[e],`int32`)},t.prototype.clip=function(e,t,n){var r,i=(r=O().getBool(`WEBGL_PACK_CLIP`)?new Fa(e.shape):new Pa(e.shape)).getCustomSetupFunc(t,n);return this.compileAndRun(r,[e],null,i)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(O().getBool(`WEBGL_PACK_UNARY_OPERATIONS`))return this.packedUnaryOp(e,xs,e.dtype);var t=new vs(e.shape,xs);return this.compileAndRun(t,[e])},t.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),n=new Ia(e.shape),r=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(e){var t=new vs(e.shape,`return 1.0 / (1.0 + exp(-1.0 * x));`);return this.compileAndRun(t,[e])},t.prototype.softplus=function(e){var t=new vs(e.shape,`
|
|
3679
3679
|
float epsilon = 1.1920928955078125e-7;
|
|
3680
3680
|
float threshold = log(epsilon) + 2.0;
|
|
3681
3681
|
|
|
@@ -3695,7 +3695,7 @@ return (round(mod(b, 2.0)) != 1) ?
|
|
|
3695
3695
|
result = log(exp_x + 1.0);
|
|
3696
3696
|
}
|
|
3697
3697
|
return result;
|
|
3698
|
-
`);return this.compileAndRun(t,[e])},t.prototype.sin=function(e){var t=new
|
|
3698
|
+
`);return this.compileAndRun(t,[e])},t.prototype.sin=function(e){var t=new vs(e.shape,js);return this.compileAndRun(t,[e])},t.prototype.cos=function(e){var t=new vs(e.shape,Ms);return this.compileAndRun(t,[e])},t.prototype.tan=function(e){var t=new vs(e.shape,`return tan(x);`);return this.compileAndRun(t,[e])},t.prototype.asin=function(e){var t=new vs(e.shape,Ns);return this.compileAndRun(t,[e])},t.prototype.acos=function(e){var t=new vs(e.shape,Ps);return this.compileAndRun(t,[e])},t.prototype.atan=function(e){var t=new vs(e.shape,Fs);return this.compileAndRun(t,[e])},t.prototype.atan2=function(e,t){var n=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`
|
|
3699
3699
|
vec4 result = atan(a, b);
|
|
3700
3700
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
3701
3701
|
|
|
@@ -3705,21 +3705,21 @@ return (round(mod(b, 2.0)) != 1) ?
|
|
|
3705
3705
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
3706
3706
|
|
|
3707
3707
|
return result;
|
|
3708
|
-
`,e.shape,t.shape):new
|
|
3708
|
+
`,e.shape,t.shape):new ja(`
|
|
3709
3709
|
if (isnan(a)) return a;
|
|
3710
3710
|
if (isnan(b)) return b;
|
|
3711
3711
|
|
|
3712
3712
|
return atan(a, b);
|
|
3713
|
-
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.sinh=function(e){var t=new
|
|
3713
|
+
`,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.sinh=function(e){var t=new vs(e.shape,`
|
|
3714
3714
|
float e2x = exp(x);
|
|
3715
3715
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
3716
|
-
`);return this.compileAndRun(t,[e])},t.prototype.cosh=function(e){var t=new
|
|
3716
|
+
`);return this.compileAndRun(t,[e])},t.prototype.cosh=function(e){var t=new vs(e.shape,`
|
|
3717
3717
|
float e2x = exp(-x);
|
|
3718
3718
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
3719
|
-
`);return this.compileAndRun(t,[e])},t.prototype.tanh=function(e){var t=new
|
|
3719
|
+
`);return this.compileAndRun(t,[e])},t.prototype.tanh=function(e){var t=new vs(e.shape,`
|
|
3720
3720
|
float e2x = exp(-2.0 * abs(x));
|
|
3721
3721
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
3722
|
-
`);return this.compileAndRun(t,[e])},t.prototype.asinh=function(e){var t=new
|
|
3722
|
+
`);return this.compileAndRun(t,[e])},t.prototype.asinh=function(e){var t=new vs(e.shape,Is);return this.compileAndRun(t,[e])},t.prototype.acosh=function(e){var t=new vs(e.shape,Ls);return this.compileAndRun(t,[e])},t.prototype.atanh=function(e){var t=new vs(e.shape,Rs);return this.compileAndRun(t,[e])},t.prototype.erf=function(e){var t=new vs(e.shape,`
|
|
3723
3723
|
// Error function is calculated approximately with elementary function.
|
|
3724
3724
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
3725
3725
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
@@ -3734,13 +3734,13 @@ return (round(mod(b, 2.0)) != 1) ?
|
|
|
3734
3734
|
x = abs(x);
|
|
3735
3735
|
float t = 1.0 / (1.0 + p * x);
|
|
3736
3736
|
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
|
|
3737
|
-
`);return this.compileAndRun(t,[e])},t.prototype.step=function(e,t){var n=new
|
|
3737
|
+
`);return this.compileAndRun(t,[e])},t.prototype.step=function(e,t){var n=new vs(e.shape,function(e){return e===void 0&&(e=0),ys+`
|
|
3738
3738
|
return x > 0.0 ? 1.0 : float(`+e+`);
|
|
3739
|
-
`}(t));return this.compileAndRun(n,[e])},t.prototype.conv2dByMatMul=function(e,t,n,r,i,a){var o=e.shape,s=this.texData.get(e.dataId),c=n.inChannels,l=o[0]*o[1]*o[2],u=n.outChannels,d=n.dataFormat===`channelsLast`,f=(l===1||u===1)&&c>1e3,p=o[2]%2!=0&&!!s.isPacked;if(f||!m().getBool(`WEBGL_LAZILY_UNPACK`)||!m().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)||!p){var h=d?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],g=this.reshape(e,[1,h,n.inChannels]),_=this.reshape(t,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:_,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),n.outShape)}var v=d?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),y={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},b=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,O(Xt(s.shape,y.shape),(function(){return`packed reshape `+s.shape+` to `+y.shape+` isn't free`}));var x=this.reshape(t,[1,n.inChannels,n.outChannels]),S=this.fusedBatchMatMul({a:y,b:x,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),C=this.texData.get(S.dataId);return O(C.isPacked,(function(){return`batchMatMul result is expected to be packed`})),s.shape=b,C.shape=n.outShape,z.makeTensorFromDataId(S.dataId,n.outShape,S.dtype)},t.prototype.conv2dWithIm2Row=function(e,t,n,r,i,a){var o=n.filterWidth,s=n.filterHeight,c=n.inChannels,l=n.outWidth,u=n.outHeight,d=n.dataFormat===`channelsLast`,f=o*s*c,p=u*l,m=[f,p],h=e.squeeze([0]),g=t.reshape([1,f,-1]),_=new xo(m,h.shape,n),v=this.compileAndRun(_,[h]).reshape([1,m[0],m[1]]),y=r!=null,b=a!=null,x=i?Ns(i,!0):null,S=new Do(v.shape,[1,p,n.outChannels],!0,!1,y,x,b),C=[v,g];r&&C.push(r),b&&C.push(a);var w=this.compileAndRun(S,C);return d?w.reshape([1,u,l,n.outChannels]):w.reshape([1,n.outChannels,u,l])},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights;if(r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type===`SAME`||r.padInfo.type===`VALID`))return this.conv2dByMatMul(t,n,r,i,a,o);if(m().getBool(`WEBGL_CONV_IM2COL`)&&t.shape[0]===1)return this.conv2dWithIm2Row(t,n,r,i,a,o);var s=i!=null,c=o!=null,l=new Na(r,s,a?Ns(a,!1):null,c),u=[t,n];return i&&u.push(i),o&&u.push(o),this.compileAndRun(l,u)},t.prototype.conv2d=function(e,t,n){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type===`SAME`||n.padInfo.type===`VALID`))return this.conv2dByMatMul(e,t,n);if(m().getBool(`WEBGL_CONV_IM2COL`)&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);var r=new Na(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerInput=function(e,t,n){var r=new Oa(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerFilter=function(e,t,n){var r=new Da(n);return this.compileAndRun(r,[e,t])},t.prototype.fusedDepthwiseConv2D=function(e){var t,n=e.input,r=e.filter,i=e.convInfo,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=m().getBool(`WEBGL_PACK_DEPTHWISECONV`)&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,l=o?Ns(o,c):null,u=[n,r],d=a!=null,f=s!=null;return d&&u.push(a),f&&u.push(s),c?(t=new Ia(i,d,l,f),this.compileAndRun(t,u)):(t=new Fa(i,d,l,f),this.compileAndRun(t,u))},t.prototype.depthwiseConv2D=function(e,t,n){var r;return m().getBool(`WEBGL_PACK_DEPTHWISECONV`)&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Ia(n),this.compileAndRun(r,[e,t])):(r=new Fa(n),this.compileAndRun(r,[e,t]))},t.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new Ma(n);return this.compileAndRun(r,[e,t])},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new ja(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3d=function(e,t,n){var r=new Pa(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerInput=function(e,t,n){var r=new Aa(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerFilter=function(e,t,n){var r=new ka(n);return this.compileAndRun(r,[e,t])},t.prototype.maxPool=function(e,t){var n=new No(t,`max`,!1);return this.compileAndRun(n,[e])},t.prototype.avgPool=function(e,t){var n=new No(t,`avg`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.maxPoolBackprop=function(e,t,n,r){var i=new No(r,`max`,!0),a=this.compileAndRun(i,[t]),o=new To(r),s=this.compileAndRun(o,[e,a],t.dtype);return a.dispose(),s},t.prototype.avgPoolBackprop=function(e,t,n){var r=new sa(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.cast=function(e,t){return bi(e,t,this)},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=Array(e.rank-1),i=0,a=0;a<e.rank;a++)a!==t&&(r[i++]=e.shape[a]);var o=Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=Array(n);for(a=0;a<c.length;a++)o[t]=a,c[a]=this.slice(e,o,s).reshape(r);return c},t.prototype.avgPool3d=function(e,t){var n=new Po(t,`avg`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.avgPool3dBackprop=function(e,t,n){var r=new ca(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.maxPool3d=function(e,t){var n=new Po(t,`max`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.maxPool3dBackprop=function(e,t,n,r){var i=new Po(r,`max`,!0),a=this.compileAndRun(i,[t]),o=new Eo(r),s=this.compileAndRun(o,[e,a],t.dtype);return a.dispose(),s},t.prototype.reshape=function(e,t){var n=this.texData.get(e.dataId);if(n.isPacked&&!Xt(e.shape,t)&&(n.texture===null||!Xt(n.shape,t))){var r=this.packedReshape(e,t);return z.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return xi(e,t)},t.prototype.resizeBilinear=function(e,t,n,r){var i=m().getBool(`WEBGL_PACK_IMAGE_OPERATIONS`)?new zo(e.shape,t,n,r):new Ro(e.shape,t,n,r);return this.compileAndRun(i,[e],`float32`)},t.prototype.resizeBilinearBackprop=function(e,t,n){var r=new Lo(e,t,n);return this.compileAndRun(r,[e])},t.prototype.resizeNearestNeighbor=function(e,t,n,r){var i=new Vo(e.shape,t,n,r);return this.compileAndRun(i,[e])},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new Bo(e,t,n);return this.compileAndRun(r,[e])},t.prototype.multinomial=function(e,t,n,r){var i=t?e:ni(e),a=i.shape[0],o=i.shape[1],s=new Oo(a,o,n),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],`int32`,c)},t.prototype.oneHot=function(e,t,n,r){var i=new ko(e.size,t,n,r);return this.compileAndRun(i,[e])},t.prototype.diag=function(e){var t=new Ua(e.size);return this.compileAndRun(t,[e])},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return dn(`tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead`),ki(e.dataSync(),t.dataSync(),n,r,i)},t.prototype.cropAndResize=function(e,t,n,r,i,a){var o=new La(e.shape,t.shape,r,i,a);return this.compileAndRun(o,[e,t,n],`float32`)},t.prototype.depthToSpace=function(e,t,n){O(t>1,(function(){return`blockSize should be > 1 for depthToSpace, but was: `+t}));var r=e.shape[0],i=n===`NHWC`?e.shape[1]:e.shape[2],a=n===`NHWC`?e.shape[2]:e.shape[3],o=n===`NHWC`?e.shape[3]:e.shape[1],s=i*t,c=a*t,l=o/(t*t),u=new Ha(n===`NHWC`?[r,s,c,l]:[r,l,s,c],t,n);return this.compileAndRun(u,[e])},t.prototype.split=function(e,t,n){return Fi(e,t,n)},t.prototype.scatterND=function(e,t,n){var r=Kr(0,e,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,c=r.outputSize,l=[c/o,o],u=e.reshape([a,i]),d=t.reshape([a,o]);if(c===0)return xi(On([]),n);var f=G(0),p=new Wo(a,i,u.rank,d.rank,s,l);return this.compileAndRun(p,[d,u,f]).reshape(n)},t.prototype.sparseToDense=function(e,t,n,r){var i=Kr(0,e,n),a=i.sliceRank,o=i.numUpdates,s=i.strides,c=i.outputSize,l=new Wo(o,a,e.rank,t.rank,s,[c,1],!1);return this.compileAndRun(l,[t,e,r]).reshape(n)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,t){var n=this.texData.get(e.dataId),r=new Xa(Ja,e.shape,t),i=new Xa(Ya,e.shape,t),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)],o=this.compileAndRun(r,a),s=this.compileAndRun(i,a),c=this.complex(o,s).as2D(e.shape[0],e.shape[1]);return o.dispose(),s.dispose(),c},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=Vr(e,t),a=i[0],o=i[1],s=i[2],c=i[3],l=t.reshape([o,r]),u=e.reshape([e.size/s,s]),d=new $a(r,c,[o,s]);return this.compileAndRun(d,[u,l]).reshape(a)},t.prototype.fill=function(e,t,n){if((n||=he(t))===`string`){var r=ae(n,M(e));return r.fill(t),z.makeTensor(r,e,n,this)}var i=new Za(e,t),a=i.getCustomSetupFunc(t);return this.compileAndRun(i,[],n,a)},t.prototype.onesLike=function(e){if(e.dtype===`string`)throw Error(`onesLike is not supported under string dtype`);return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype===`string`?``:0,e.dtype)},t.prototype.linspace=function(e,t,n){return Si(e,t,n)},t.prototype.makeTensorInfo=function(e,t){var n=this.write(null,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}},t.prototype.makeOutput=function(e,t){var n=this.makeTensorInfo(e,t).dataId;return z.makeTensorFromDataId(n,e,t,this)},t.prototype.unpackTensor=function(e){var t=new js(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},t.prototype.packTensor=function(e){var t=new Ao(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,t){var n=[Gt(e.shape)].concat(Kt(e.shape)),r={dtype:e.dtype,shape:n,dataId:e.dataId},i=new Io([Gt(t)].concat(Kt(t)),n),a=this.runWebGLProgram(i,[r],e.dtype,null,!0);return{dataId:a.dataId,shape:t,dtype:a.dtype}},t.prototype.decode=function(e){var t,n=this.texData.get(e),r=n.isPacked,i=n.shape,a=n.dtype,o=qt(i);return t=r?new Va(o):new Ba(o),{dtype:a,shape:i,dataId:this.runWebGLProgram(t,[{shape:o,dtype:a,dataId:e}],a,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,t,n,r,i){var a=this;i===void 0&&(i=!1);var o=this.makeTensorInfo(e.outputShape,n),s=this.texData.get(o.dataId);if(e.packedOutput&&(s.isPacked=!0),e.outPackingScheme===at.DENSE&&(s.texShape=pt(e.outputShape).map((function(e){return 2*e}))),e.outTexUsage!=null&&(s.usage=e.outTexUsage),M(o.shape)===0)return s.values=ie(o.dtype,0),o;var c=[],l=t.map((function(t){if(t.dtype===`complex64`)throw Error(`GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.`);var n=a.texData.get(t.dataId);if(n.texture==null){if(!e.packedInputs&&M(t.shape)<=m().getNumber(`WEBGL_SIZE_UPLOAD_UNIFORM`))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}else if(!!n.isPacked!=!!e.packedInputs)t=n.isPacked?a.unpackTensor(t):a.packTensor(t),c.push(t),n=a.texData.get(t.dataId);else if(n.isPacked&&!Xt(n.shape,t.shape)){var r=t,i=t.shape;t.shape=n.shape,t=a.packedReshape(t,i),c.push(t),n=a.texData.get(t.dataId),r.shape=i}return a.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);var u,d={shape:o.shape,texData:s,isUniform:!1},f=function(e,t,n){var r=``;t.concat(n).forEach((function(e){var t=e.texData!=null&&e.texData.slice!=null&&e.texData.slice.flatOffset>0,n=e.isUniform?`uniform`:e.texData.texShape;r+=e.shape+`_`+n+`_`+t}));var i=e.userCode,a=e.constructor.name;return a+=`_`+r+`_`+i}(e,l,d),p=this.getAndSaveBinary(f,(function(){return function(e,t,n,r){var i=t.userCode,a=n.map((function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return e.texData!=null&&e.texData.slice!=null&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),o=a.map((function(e){return e.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=Ji(a,s,i,t.packedInputs),l=e.createProgram(c),u=null,d=e.getUniformLocation(l,`NAN`,!1);m().getNumber(`WEBGL_VERSION`)===1&&(u=e.getUniformLocation(l,`INFINITY`,!1));for(var f={},p=0;p<t.variableNames.length;p++){var h=t.variableNames[p];f[h]=e.getUniformLocation(l,h,!1),f[`offset`+h]=e.getUniformLocation(l,`offset`+h,!1)}return{program:t,source:c,webGLProgram:l,uniformLocations:f,inShapeInfos:o,outShapeInfo:s,infLoc:u,nanLoc:d}}(a.gpgpu,e,l,d)})),h=this.activeTimers!=null;if(h&&(u=this.startTimer()),function(e,t,n,r,i){bo(t.inShapeInfos,n),bo([t.outShapeInfo],[r]);var a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),m().getNumber(`WEBGL_VERSION`)===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((function(n,r){var i=t.program.variableNames[r],a=t.uniformLocations[i],o=t.uniformLocations[`offset`+i];if(a!=null)if(n.isUniform)if(M(n.shape)<2)e.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),e.gl.uniform1fv(a,s)}else n.texData.slice!=null&&o!=null&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture,a,r)})),i?.(e,t.webGLProgram),e.executeProgram()}(this.gpgpu,p,l,d,r),c.forEach((function(e){return a.disposeData(e.dataId)})),h&&(u=this.endTimer(u),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(u)})),!m().getBool(`WEBGL_LAZILY_UNPACK`)&&s.isPacked&&!1===i){var g=this.unpackTensor(o);return this.disposeData(o.dataId),g}return o},t.prototype.compileAndRun=function(e,t,n,r,i){i===void 0&&(i=!1),n||=t[0].dtype;var a=this.runWebGLProgram(e,t,n,r,i);return z.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},t.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;this.disposed||=(m().getBool(`IS_TEST`)||Object.keys(this.binaryCache).forEach((function(t){e.gpgpu.deleteProgram(e.binaryCache[t].webGLProgram),delete e.binaryCache[t]})),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<`u`&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),!0)},t.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue??=H((function(){if(!m().get(`WEBGL_RENDER_FLOAT32_ENABLED`)){var t=m().getBool(`DEBUG`);m().set(`DEBUG`,!1);var n=e.abs(G(1e-8)).dataSync()[0];if(m().set(`DEBUG`,t),n>0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,a=n.values,o=n.texture,s=n.usage,c=n.isPacked;if(o==null){var l,u=this.activeTimers!=null;u&&(l=Ce());var d=n.texShape;if(d??(d=Jt(r,c),n.texShape=d),a!=null){var f=qt(r),p=void 0,m=d[1],h=d[0],g=a instanceof Uint8Array;c?(m=(t=mt(d[0],d[1]))[0],h=t[1],p=new qa(f,[h,m],g)):p=new Ka(f,[h,m],g);var _=this.makeTensorInfo([h,m],i);this.texData.get(_.dataId).usage=g?ot.PIXELS:ot.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(_.dataId),m,h,a);var v=this.runWebGLProgram(p,[_],i,null,!0),y=this.texData.get(v.dataId);n.texture=y.texture,n.texShape=y.texShape,n.isPacked=y.isPacked,n.usage=y.usage,this.disposeData(_.dataId),this.texData.delete(v.dataId),n.values=null,u&&(this.uploadWaitMs+=Ce()-l)}else n.texture=this.acquireTexture(d,s,i,c)}},t.prototype.convertAndCacheOnCPU=function(e,t){var n=this.texData.get(e),r=n.dtype;return this.releaseGPUData(e),t!=null&&(n.values=function(e,t){if(t===`float32`||t===`complex64`)return e;if(t===`int32`||t===`bool`){for(var n=t===`int32`?new Int32Array(e.length):new Uint8Array(e.length),r=0;r<n.length;++r)n[r]=Math.round(e[r]);return n}throw Error(`Unknown dtype `+t)}(t,r)),n.values},t.prototype.acquireTexture=function(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: `+i+` MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)},t.prototype.computeBytes=function(e,t){return e[0]*e[1]*ue(t)},t}(ai);rt()&&z.registerBackend(`webgl`,(function(){return new Fs}),2);var Is=W({square_:function(e){var t=U(e,`x`,`square`),n=[t];return z.runKernelFunc((function(e,n){return n([t]),e.square(t)}),{x:t},null,`Square`,{},n,[])}}),Ls=`SquaredDifference`,Rs=W({squaredDifference_:function(e,t){var n,r=U(e,`a`,`squaredDifference`),i=U(t,`b`,`squaredDifference`);n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape);var a={a:r,b:i},o=[r,i];return z.runKernelFunc((function(e,t){var n=e.squaredDifference(r,i);return t([r,i]),n}),a,(function(e,t){var n=t[0],r=t[1],i=G(2);return{a:function(){return e.mul(n.sub(r).mul(i))},b:function(){return e.mul(r.sub(n).mul(i))}}}),Ls,{},o,[])}}),zs=W({abs_:function(e){var t=U(e,`x`,`abs`);return t.dtype===`complex64`?z.runKernelFunc((function(e){return e.complexAbs(t)}),{$x:t}):z.runKernelFunc((function(e,n){var r=e.abs(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().step(-1))}}}),`Abs`)}}),Bs=W({acos_:function(e){var t=U(e,`x`,`acos`);return z.runKernelFunc((function(e,n){var r=e.acos(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(G(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Vs=W({acosh_:function(e){var t=U(e,`x`,`acosh`);return z.runKernelFunc((function(e,n){var r=e.acosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(n.toFloat().square().sub(1).sqrt())}}}))}}),Hs=W({asin_:function(e){var t=U(e,`x`,`asin`);return z.runKernelFunc((function(e,n){var r=e.asin(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(G(1).sub(n.toFloat().square()).sqrt())}}}))}}),Us=W({asinh_:function(e){var t=U(e,`x`,`asinh`);return z.runKernelFunc((function(e,n){var r=e.asinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(G(1).add(n.toFloat().square()).sqrt())}}}))}}),Ws=W({atan_:function(e){var t=U(e,`x`,`atan`);return z.runKernelFunc((function(e,n){var r=e.atan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().square().add(1))}}}))}}),Gs=W({atanh_:function(e){var t=U(e,`x`,`atanh`);return z.runKernelFunc((function(e,n){var r=e.atanh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(G(1).sub(n.toFloat().square()))}}}))}}),Ks=W({ceil_:function(e){var t=U(e,`x`,`ceil`);return z.runKernelFunc((function(e){return e.ceil(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),qs=W({clipByValue_:function(e,t,n){var r=U(e,`x`,`clipByValue`);O(t<=n,(function(){return`Error in clip: min (`+t+`) must be less than or equal to max (`+n+`).`}));var i=[r],a={min:t,max:n};return z.runKernelFunc((function(e,i){var a=e.clip(r,t,n);return i([r]),a}),{x:r},(function(e,r){var i=r[0];return{x:function(){return e.where(i.greaterEqual(t).logicalAnd(i.lessEqual(n)),Un(e))}}}),`ClipByValue`,a,i)}}),Js=W({cos_:function(e){var t=U(e,`x`,`cos`),n=[t];return z.runKernelFunc((function(e,n){var r=e.cos(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().sin().neg().mul(e)}}}),`Cos`,{},n)}}),Ys=W({cosh_:function(e){var t=U(e,`x`,`cosh`);return z.runKernelFunc((function(e,n){var r=e.cosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().sinh().mulStrict(e)}}}))}}),Xs=W({erf_:function(e){var t=U(e,`x`,`erf`);return O(t.dtype===`int32`||t.dtype===`float32`,(function(){return"Input dtype must be `int32` or `float32`."})),t.dtype===`int32`&&(t=t.toFloat()),z.runKernelFunc((function(e,n){var r=e.erf(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),Zs=W({exp_:function(e){var t=U(e,`x`,`exp`);return z.runKernelFunc((function(e,n){var r=e.exp(t);return n([r]),r}),{x:t},(function(e,t){return{x:function(){return e.mulStrict(t[0])}}}),`Exp`,{},[],[!0])}}),Qs=W({expm1_:function(e){var t=U(e,`x`,`expm1`);return z.runKernelFunc((function(e,n){var r=e.expm1(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.exp())}}}))}}),$s=W({floor_:function(e){var t=U(e,`x`,`floor`);return z.runKernelFunc((function(e){return e.floor(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),ec=W({log_:function(e){var t=U(e,`x`,`log`),n=[t];return z.runKernelFunc((function(e,n){var r=e.log(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.toFloat())}}}),`Log`,{},n)}}),tc=W({log1p_:function(e){var t=U(e,`x`,`log1p`);return z.runKernelFunc((function(e,n){var r=e.log1p(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.add(1))}}}))}}),nc=W({logSigmoid_:function(e){var t=U(e,`x`,`logSigmoid`);return z.runKernelFunc((function(e,n){var r=e.softplus(t.neg()).neg();return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.neg().sigmoid())}}}))}}),rc=W({neg_:function(e){var t=U(e,`x`,`neg`),n=[t];return z.runKernelFunc((function(e){return e.neg(t)}),{x:t},(function(e){return{x:function(){return e.neg()}}}),`Neg`,{},n)}}),ic=W({reciprocal_:function(e){var t=U(e,`x`,`reciprocal`);return z.runKernelFunc((function(e,n){var r=e.reciprocal(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.square().neg())}}}))}}),ac=W({round_:function(e){var t=U(e,`x`,`round`);return z.runKernelFunc((function(e){return e.round(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),oc=W({rsqrt_:function(e){var t=U(e,`x`,`rsqrt`),n=[t];return z.runKernelFunc((function(e,n){var r=e.rsqrt(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.pow(1.5).mul(2)).neg()}}}),`Rsqrt`,{},n)}}),sc=W({sigmoid_:function(e){var t=U(e,`x`,`sigmoid`);return z.runKernelFunc((function(e,n){var r=e.sigmoid(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.mul(G(1).sub(n)))}}}),`Sigmoid`)}}),cc=W({sign_:function(e){var t=U(e,`x`,`sign`);return z.runKernelFunc((function(e){return e.sign(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),lc=W({isNaN_:function(e){var t=U(e,`x`,`isNaN`);return z.runKernelFunc((function(e){return e.isNaN(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),uc=W({isInf_:function(e){var t=U(e,`x`,`isInf`);return z.runKernelFunc((function(e){return e.isInf(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),dc=W({isFinite_:function(e){var t=U(e,`x`,`isFinite`);return z.runKernelFunc((function(e){return e.isFinite(t)}),{$x:t},(function(e){return{$x:function(){return Un(e)}}}))}}),fc=W({sin_:function(e){var t=U(e,`x`,`sin`),n=[t];return z.runKernelFunc((function(e,n){var r=e.sin(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().cos().mul(e)}}}),`Sin`,{},n)}}),pc=W({sinh_:function(e){var t=U(e,`x`,`sinh`);return z.runKernelFunc((function(e,n){var r=e.sinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().cosh().mulStrict(e)}}}))}}),mc=W({softplus_:function(e){var t=U(e,`x`,`softplus`);return z.runKernelFunc((function(e,n){var r=e.softplus(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.sigmoid())}}}))}}),hc=W({sqrt_:function(e){var t=U(e,`x`,`sqrt`);return z.runKernelFunc((function(e,n){var r=e.sqrt(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().sqrt().mul(2))}}}))}}),gc=W({step_:function(e,t){t===void 0&&(t=0);var n=U(e,`x`,`step`);return z.runKernelFunc((function(e){return e.step(n,t)}),{$x:n},(function(e){return{$x:function(){return Un(e)}}}))}}),_c=W({tan_:function(e){var t=U(e,`x`,`tan`);return z.runKernelFunc((function(e,n){var r=e.tan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.cos().square())}}}))}}),vc=W({tanh_:function(e){var t=U(e,`x`,`tanh`);return z.runKernelFunc((function(e,n){var r=e.tanh(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return G(1).sub(n.square()).mulStrict(e)}}}),`Tanh`,{},null,[!0])}});function yc(e,t,n,r,i,a){var o,s,c=U(e,`x`,`batchNorm`),l=U(t,`mean`,`batchNorm`),u=U(n,`variance`,`batchNorm`);return i!=null&&(o=U(i,`scale`,`batchNorm`)),r!=null&&(s=U(r,`offset`,`batchNorm`)),O(c.rank===2,(function(){return`Error in batchNorm3D: x must be rank 3 but got rank `+c.rank+`.`})),O(l.rank===2||l.rank===1,(function(){return`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank `+l.rank+`.`})),O(u.rank===2||u.rank===1,(function(){return`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank `+u.rank+`.`})),o!=null&&O(o.rank===2||o.rank===1,(function(){return`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank `+o.rank+`.`})),s!=null&&O(s.rank===2||s.rank===1,(function(){return`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank `+s.rank+`.`})),Sc(c,l,u,s,o,a)}function bc(e,t,n,r,i,a){var o,s,c=U(e,`x`,`batchNorm`),l=U(t,`mean`,`batchNorm`),u=U(n,`variance`,`batchNorm`);return i!=null&&(o=U(i,`scale`,`batchNorm`)),r!=null&&(s=U(r,`offset`,`batchNorm`)),O(c.rank===3,(function(){return`Error in batchNorm3D: x must be rank 3 but got rank `+c.rank+`.`})),O(l.rank===3||l.rank===1,(function(){return`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank `+l.rank+`.`})),O(u.rank===3||u.rank===1,(function(){return`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank `+u.rank+`.`})),o!=null&&O(o.rank===3||o.rank===1,(function(){return`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank `+o.rank+`.`})),s!=null&&O(s.rank===3||s.rank===1,(function(){return`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank `+s.rank+`.`})),Sc(c,l,u,s,o,a)}function xc(e,t,n,r,i,a){var o,s,c=U(e,`x`,`batchNorm`),l=U(t,`mean`,`batchNorm`),u=U(n,`variance`,`batchNorm`);return i!=null&&(o=U(i,`scale`,`batchNorm`)),r!=null&&(s=U(r,`offset`,`batchNorm`)),O(c.rank===4,(function(){return`Error in batchNorm4D: x must be rank 4 but got rank `+c.rank+`.`})),O(l.rank===4||l.rank===1,(function(){return`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank `+l.rank+`.`})),O(u.rank===4||u.rank===1,(function(){return`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank `+u.rank+`.`})),o!=null&&O(o.rank===4||o.rank===1,(function(){return`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank `+o.rank+`.`})),s!=null&&O(s.rank===4||s.rank===1,(function(){return`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank `+s.rank+`.`})),Sc(c,l,u,s,o,a)}function Sc(e,t,n,r,i,a){a??=.001;var o,s,c,l=U(e,`x`,`batchNorm`),u=U(t,`mean`,`batchNorm`),d=U(n,`variance`,`batchNorm`);i!=null&&(o=U(i,`scale`,`batchNorm`)),r!=null&&(s=U(r,`offset`,`batchNorm`)),O(u.rank===d.rank,(function(){return`Batch normalization gradient requires mean and variance to have equal ranks.`})),O(s==null||u.rank===s.rank,(function(){return`Batch normalization gradient requires mean and offset to have equal ranks.`})),O(o==null||u.rank===o.rank,(function(){return`Batch normalization gradient requires mean and scale to have equal ranks.`})),c=l.rank===0||l.rank===1?l.as4D(1,1,1,l.size):l.rank===2?l.as4D(1,1,l.shape[0],l.shape[1]):l.rank===3?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;var f=[l,u,d,o];return z.runKernelFunc((function(e,t){var n=e.batchNormalization(c,Cc(u),Cc(d),a,Cc(o),Cc(s));return t([l,u,d,o]),n}),{x:l,mean:u,variance:d,scale:o,offset:s},(function(e,t){var n=t,r=n[0],i=n[1],o=n[2],s=n[3]??G(1),l=si(i.shape,c.shape),u=[];if(i.rank===1){for(var d=0;d<c.shape.length-1;++d)u.push(c.shape[d]);u.push(1)}var f=r.sub(i),p=e.mul(s),m=oc(o.add(G(a))),h=m.mul(m).mul(m).mul(G(-.5));return{x:function(){return i.rank===1?e.mul(Mr(m.as4D(1,1,1,i.shape[0]),u)).mul(s).reshape(r.shape):e.mul(m).mul(s).reshape(r.shape)},mean:function(){var e=m.mul(G(-1)).mul(p);return i.rank===1&&(e=e.sum(l)),e.reshape(i.shape)},variance:function(){var e=h.mul(f).mul(p);return i.rank===1&&(e=e.sum(l)),e.reshape(i.shape)},scale:function(){var t=f.mul(m),n=e.mul(t);return i.rank===1&&(n=n.sum(l)),n.reshape(i.shape)},offset:function(){var t=e;return i.rank===1&&(t=t.sum(l)),t.reshape(i.shape)}}}),`BatchNormalization`,{varianceEpsilon:a},f).reshape(l.shape)}function Cc(e){return e==null?null:e.rank===0?e.as1D():e.rank===1?e:e.rank===2?e.as4D(1,1,e.shape[0],e.shape[1]):e.rank===3?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}function wc(){cn(`tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon`)}var Tc=W({batchNormalization2d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),wc(),yc(e,t,n,a,i,r)}}),Ec=W({batchNormalization3d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),wc(),bc(e,t,n,a,i,r)}}),Dc=W({batchNormalization4d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),wc(),xc(e,t,n,a,i,r)}}),Oc=W({batchNormalization_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),wc(),Sc(e,t,n,a,i,r)}}),kc=W({batchNorm_:Sc}),Ac=W({batchNorm2d_:yc}),jc=W({batchNorm3d_:bc}),Mc=W({batchNorm4d_:xc}),Nc=W({logicalAnd_:function(e,t){var n=U(e,`a`,`logicalAnd`,`bool`),r=U(t,`b`,`logicalAnd`,`bool`);return J(n.shape,r.shape),z.runKernelFunc((function(e){return e.logicalAnd(n,r)}),{a:n,b:r},null,`LogicalAnd`)}}),Pc=W({logicalNot_:function(e){var t=U(e,`x`,`logicalNot`,`bool`);return z.runKernelFunc((function(e){return e.logicalNot(t)}),{$x:t})}}),Fc=W({logicalOr_:function(e,t){var n=U(e,`a`,`logicalOr`,`bool`),r=U(t,`b`,`logicalOr`,`bool`);return J(n.shape,r.shape),z.runKernelFunc((function(e){return e.logicalOr(n,r)}),{$a:n,$b:r})}}),Ic=W({logicalXor_:function(e,t){var n=U(e,`a`,`logicalXor`,`bool`),r=U(t,`b`,`logicalXor`,`bool`);return J(n.shape,r.shape),Fc(e,t).logicalAnd(Nc(e,t).logicalNot())}}),Lc=W({where_:function(e,t,n){var r=U(t,`a`,`where`),i=U(n,`b`,`where`),a=U(e,`condition`,`where`,`bool`);return k(r.shape,i.shape,`Error in where: `),a.rank===1?O(a.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):k(a.shape,i.shape,`Error in where: `),z.runKernelFunc((function(e,t){var n=e.select(a,r,i);return t([a]),n}),{$condition:a,$a:r,$b:i},(function(e,t){var n=t[0];return{$condition:function(){return Un(n).toFloat()},$a:function(){return e.mul(n.cast(e.dtype))},$b:function(){return e.mul(n.logicalNot().cast(e.dtype))}}}))}}),Rc=function(e){return u(this,void 0,void 0,(function(){var t,n,r;return d(this,(function(i){switch(i.label){case 0:return[4,(t=U(e,`condition`,`whereAsync`,`bool`)).data()];case 1:return n=i.sent(),r=Ri(t.shape,n),e!==t&&t.dispose(),[2,r]}}))}))},zc=W({add_:function(e,t){var n,r=U(e,`a`,`add`),i=U(t,`b`,`add`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e){return e.add(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=si(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=si(i.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(i.shape)}}}),`Add`)}}),Bc=W({addN_:function(e){O(Array.isArray(e),(function(){return`The argument passed to tf.addN() must be a list of tensors`})),O(e.length>=1,(function(){return`Must pass at least one tensor to tf.addN(), but got `+e.length}));var t=e.map((function(e,t){return U(e,`tensors`+t,`addN`)})),n=t[0];t.forEach((function(e){if(e.dtype!==n.dtype)throw Error(`All tensors passed to tf.addN() must have the same dtype`)})),t.forEach((function(e){if(!N(e.shape,n.shape))throw Error(`All tensors passed to tf.addN() must have the same shape`)}));var r=t;return z.runKernelFunc((function(e){return e.addN(t)}),r,(function(e){var n={};return t.forEach((function(t,r){n[r]=function(){return e.clone()}})),n}),`AddN`)}}),Vc=W({addStrict_:function(e,t){var n=U(e,`a`,`addStrict`),r=U(t,`b`,`addStrict`);return k(n.shape,r.shape,`Error in addStrict: `),n.add(r)}}),Hc=W({atan2_:function(e,t){var n,r=U(e,`a`,`atan2`),i=U(t,`b`,`atan2`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e,t){var n=e.atan2(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=zc(n.square(),r.square()),i=e.mul(r.div(t)),o=si(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=zc(n.square(),r.square()),i=rc(e.mul(n.div(t))),o=si(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}}))}}),Uc=W({div_:function(e,t){var n,r=U(e,`a`,`div`),i=U(t,`b`,`div`);if(n=Ze(r,i),r=n[0],i=n[1],r.dtype===`int32`&&i.dtype===`int32`)return Kc(r,i);var a=J(r.shape,i.shape);return z.runKernelFunc((function(e,t){var n=e.realDivide(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=si(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=si(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}}),`Div`)}}),Wc=W({divNoNan_:function(e,t){var n,r=U(e,`a`,`div`),i=U(t,`b`,`div`);r=(n=Ze(r,i))[0],i=n[1];var a=Uc(r,i),o=Un(a);return Lc(i.equal(o),o,a)}}),Gc=W({divStrict_:function(e,t){var n=U(e,`a`,`div`),r=U(t,`b`,`div`);return k(n.shape,r.shape,`Error in divideStrict: `),n.div(r)}}),Kc=W({floorDiv_:function(e,t){var n,r=U(e,`a`,`floorDiv`),i=U(t,`b`,`floorDiv`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e,t){var n=e.floorDiv(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=si(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=si(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}}),`FloorDiv`)}}),qc=W({maximum_:function(e,t){var n,r=U(e,`a`,`maximum`),i=U(t,`b`,`maximum`);return n=Ze(r,i),r=n[0],i=n[1],r.dtype===`bool`&&(r=r.toInt(),i=i.toInt()),J(r.shape,i.shape),z.runKernelFunc((function(e,t){var n=e.maximum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.greaterEqual(r).toFloat())},b:function(){return e.mul(n.less(r).toFloat())}}}),`Maximum`)}}),Jc=W({maximumStrict_:function(e,t){var n=U(e,`a`,`maximumStrict`),r=U(t,`b`,`maximumStrict`);return k(n.shape,r.shape,`Error in maximumStrict: `),n.maximum(r)}}),Yc=W({minimum_:function(e,t){var n,r=U(e,`a`,`minimum`),i=U(t,`b`,`minimum`);return n=Ze(r,i),r=n[0],i=n[1],r.dtype===`bool`&&(r=r.toInt(),i=i.toInt()),J(r.shape,i.shape),z.runKernelFunc((function(e,t){var n=e.minimum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.lessEqual(r).toFloat())},b:function(){return e.mul(n.greater(r).toFloat())}}}),`Minimum`)}}),Xc=W({minimumStrict_:function(e,t){var n=U(e,`a`,`minimumStrict`),r=U(t,`b`,`minimumStrict`);return k(n.shape,r.shape,`Error in minimumStrict: `),n.minimum(r)}}),Zc=W({mod_:function(e,t){var n,r=U(e,`a`,`mod`),i=U(t,`b`,`mod`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e,t){var n=e.mod(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=si(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=si(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}}))}}),Qc=W({modStrict_:function(e,t){var n=U(e,`a`,`modStrict`),r=U(t,`b`,`modStrict`);return k(n.shape,r.shape,`Error in modStrict: `),n.mod(r)}}),$c=W({mul_:function(e,t){var n,r=U(e,`a`,`mul`),i=U(t,`b`,`mul`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e,t){var n=e.multiply(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.mul(r.toFloat()),i=si(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=si(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}}),`Mul`)}}),el=W({mulStrict_:function(e,t){var n=U(e,`a`,`mul`),r=U(t,`b`,`mul`);return k(n.shape,r.shape,`Error in multiplyStrict: `),n.mul(r)}}),tl=W({pow_:function(e,t){var n,r=U(e,`base`,`pow`),i=U(t,`exp`,`pow`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape),o=[r,i];return z.runKernelFunc((function(e,t){var n=e.pow(r,i);return t([r,i,n]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1],i=t[2];return{a:function(){var t=r.toFloat(),i=e.mul(t.mul(n.pow(t.sub(G(1))))),o=si(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},b:function(){var t=n.greater(0),o=n.log().where(t,Un(n)),s=e.mul(i.mul(o)),c=si(r.shape,a);return c.length>0&&(s=s.sum(c)),s.reshape(r.shape)}}}),`Pow`,{},o,[!0])}}),nl=W({powStrict_:function(e,t){return k(e.shape,t.shape,`Error in powStrict: `),e.pow(t)}}),rl=W({squaredDifferenceStrict_:function(e,t){var n=U(e,`a`,`squaredDifferenceStrict`),r=U(t,`b`,`squaredDifferenceStrict`);return k(n.shape,r.shape,`Error in squaredDifferenceStrict: `),n.squaredDifference(r)}}),il=W({sub_:function(e,t){var n,r=U(e,`a`,`sub`),i=U(t,`b`,`sub`);n=Ze(r,i),r=n[0],i=n[1];var a=J(r.shape,i.shape);return z.runKernelFunc((function(e){return e.subtract(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=si(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=si(i.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(i.shape)}}}),`Sub`)}}),al=W({subStrict_:function(e,t){var n=U(e,`a`,`subStrict`),r=U(t,`b`,`subStrict`);return k(n.shape,r.shape,`Error in subStrict: `),n.sub(r)}}),ol=W({equal_:function(e,t){var n,r=U(e,`a`,`equal`),i=U(t,`b`,`equal`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e){return e.equal(r,i)}),{$a:r,$b:i})}}),sl=W({equalStrict_:function(e,t){var n=U(e,`a`,`equalStrict`),r=U(t,`b`,`equalStrict`);return k(n.shape,r.shape,`Error in equalStrict: `),n.equal(r)}}),cl=W({greater_:function(e,t){var n,r=U(e,`a`,`greater`),i=U(t,`b`,`greater`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e){return e.greater(r,i)}),{a:r,b:i},null,`Greater`)}}),ll=W({greaterEqual_:function(e,t){var n,r=U(e,`a`,`greaterEqual`),i=U(t,`b`,`greaterEqual`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e,t){var n=e.greaterEqual(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return Un(n)},b:function(){return Un(r)}}}),`GreaterEqual`)}}),ul=W({greaterEqualStrict_:function(e,t){var n=U(e,`a`,`greaterEqualStrict`),r=U(t,`b`,`greaterEqualStrict`);return k(n.shape,r.shape,`Error in greaterEqualStrict: `),n.greaterEqual(r)}}),dl=W({greaterStrict_:function(e,t){var n=U(e,`a`,`greaterStrict`),r=U(t,`b`,`greaterStrict`);return k(n.shape,r.shape,`Error in greaterStrict: `),n.greater(r)}}),fl=W({less_:function(e,t){var n,r=U(e,`a`,`less`),i=U(t,`b`,`less`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e){return e.less(r,i)}),{a:r,b:i},null,`Less`)}}),pl=W({lessEqual_:function(e,t){var n,r=U(e,`a`,`lessEqual`),i=U(t,`b`,`lessEqual`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e,t){var n=e.lessEqual(r,i);return t([r,i]),n}),{a:r,b:i},null,`LessEqual`)}}),ml=W({lessEqualStrict_:function(e,t){var n=U(e,`a`,`lessEqualStrict`),r=U(t,`b`,`lessEqualStrict`);return k(n.shape,r.shape,`Error in lessEqualStrict: `),n.lessEqual(r)}}),hl=W({lessStrict_:function(e,t){var n=U(e,`a`,`lessStrict`),r=U(t,`b`,`lessStrict`);return k(n.shape,r.shape,`Error in lessStrict: `),n.less(r)}}),gl=W({notEqual_:function(e,t){var n,r=U(e,`a`,`notEqual`),i=U(t,`b`,`notEqual`);return n=Ze(r,i),r=n[0],i=n[1],J(r.shape,i.shape),z.runKernelFunc((function(e){return e.notEqual(r,i)}),{a:r,b:i},null,`NotEqual`)}}),_l=W({notEqualStrict_:function(e,t){var n=U(e,`a`,`notEqualStrict`),r=U(t,`b`,`notEqualStrict`);return k(n.shape,r.shape,`Error in notEqualStrict: `),n.notEqual(r)}});function vl(e,t){for(var n=[],r=e;r<t;++r)n.push(r);return n}function yl(e){for(var t=[],n=0;n<e.length;++n)for(var r=0;r<e[n].length;++r)t.push(e[n][r]);return t}var bl=W({gather_:function(e,t,n){n===void 0&&(n=0);var r=U(e,`x`,`gather`),i=U(t,`indices`,`gather`,`int32`);n=L(n,r.shape)[0];var a=function(e,t,n){for(var r=e.shape[n],i=[],a=1,o=1,s=0;s<n;s++)i.push(e.shape[s]),a*=e.shape[s];for(s=0;s<t.rank;s++)i.push(t.shape[s]);for(s=n+1;s<e.rank;s++)i.push(e.shape[s]),o*=e.shape[s];return{batchSize:a,sliceSize:o,dimSize:r,outputShape:i}}(r,i,n);return z.runKernelFunc((function(e,t){var a=e.gather(r,i.flatten(),n);return t([i]),a}),{x:r,indices:i},(function(e,t){var i=t[0];return{x:function(){var t=r.shape,a=i.size,o=t.slice(0,n),s=o.length,c=t.slice(n,t.length).slice(1),l=c.length,u=vl(0,s),d=vl(s+1,s+1+l),f=yl([o,[a],c]),p=e.reshape(f),m=i.reshape([a]),h=yl([[s],u,d]),g=xl(p.transpose(h),m,r.shape[n]),_=xn(h);return g=g.transpose(_)},indices:function(){return i}}}),`Gather`,{axis:n}).reshape(a.outputShape)}}),xl=W({unsortedSegmentSum_:function(e,t,n){var r=U(e,`x`,`unsortedSegmentSum`),i=U(t,`segmentIds`,`unsortedSegmentSum`,`int32`);return O(P(n),(function(){return`numSegments must be of dtype int`})),z.runKernelFunc((function(e,t){var a=e.unsortedSegmentSum(r,i,n);return t([i]),a}),{$x:r},(function(e,t){var n=t[0];return{$x:function(){return function(e,t){for(var n=bl(e,qc(t,Un(t))),r=ll(t,G(0,`int32`)),i=n.rank-r.rank,a=0;a<i;++a)r=hr(r,a+1);r=Nc(r,Ln(n.shape,`bool`));var o=Un(n);return Lc(r,n,o)}(e,n)}}}))}}),Sl=function(e,t,n){return u(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,f,p,m,h,g;return d(this,(function(d){switch(d.label){case 0:for(r=U(e,`tensor`,`boolMask`),i=U(t,`mask`,`boolMask`,`bool`),a=n??0,o=i.rank,s=r.shape,O(o>0,(function(){return`mask cannot be scalar`})),k(s.slice(a,a+o),i.shape,`mask's shape must match the first K dimensions of tensor's shape,`),c=1,l=a;l<a+o;l++)c*=s[l];return u=s.slice(0,a).concat([c],s.slice(a+o)),f=r.reshape(u),p=i.reshape([-1]),[4,Rc(p)];case 1:return m=d.sent(),h=m.squeeze([1]),g=bl(f,h,a),e!==r&&r.dispose(),t!==i&&i.dispose(),h.dispose(),f.dispose(),p.dispose(),m.dispose(),[2,g]}}))}))};function Cl(e,t,n,r,i,a,o){a===void 0&&(a=`NHWC`),O(e.length===t.rank,(function(){return`Length of inShape (`+e.length+`) and rank of dy (`+t.rank+`) must match`}));var s=e,c=t,l=!1;t.rank===3&&(l=!0,c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),s=[1,e[0],e[1],e[2]]),O(s.length===4,(function(){return`Error in conv2dDerInput: inShape must be length 4, but got length `+s.length+`.`})),O(c.rank===4,(function(){return`Error in conv2dDerInput: dy must be rank 4, but got rank `+c.rank})),O(n.rank===4,(function(){return`Error in conv2dDerInput: filter must be rank 4, but got rank `+n.rank}));var u=a===`NHWC`?s[3]:s[1],d=a===`NHWC`?c.shape[3]:c.shape[1];O(u===n.shape[2],(function(){return`Error in conv2dDerInput: depth of input (`+u+`) must match input depth for filter `+n.shape[2]+`.`})),O(d===n.shape[3],(function(){return`Error in conv2dDerInput: depth of output (`+d+`) must match output depth for filter `+n.shape[3]+`.`})),o!=null&&O(P(i),(function(){return`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+i+`.`}));var f=yi(a),p=ui(s,n.shape,r,1,i,o,!1,f),m=z.runKernelFunc((function(e,t){var r=e.conv2dDerInput(c,n,p);return t([n,c]),r}),{dy4D:c,filter:n},(function(e,t){var n=t[0],s=t[1];return{dy4D:function(){return Dl(e,n,r,i,a,1,o)},filter:function(){return kl(e,s,n.shape,r,i,a,o)}}}));return l?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}function wl(e){var t=function(e){return typeof e==`number`?[e,e,e]:e.length===2?[e[0],e[1],1]:e}(e),n=t[0],r=t[1],i=t[2];return n===1&&r===1&&i===1}function Tl(e,t,n,r,i){O(e.length===t.rank,(function(){return`Length of inShape (`+e.length+`) and rank of dy (`+t.rank+`) must match`}));var a=e,o=t,s=!1;t.rank===4&&(s=!0,o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),a=[1,e[0],e[1],e[2],e[3]]);var c=a[4],l=o.shape[4];O(a.length===5,(function(){return`Error in conv3dDerInput: inShape must be length 5, but got length `+a.length+`.`})),O(o.rank===5,(function(){return`Error in conv3dDerInput: dy must be rank 5, but got rank `+o.rank})),O(n.rank===5,(function(){return`Error in conv3dDerInput: filter must be rank 5, but got rank `+n.rank})),O(c===n.shape[3],(function(){return`Error in conv3dDerInput: depth of input (`+c+`) must match input depth for filter `+n.shape[3]+`.`})),O(l===n.shape[4],(function(){return`Error in conv3dDerInput: depth of output (`+l+`) must match output depth for filter `+n.shape[4]+`.`}));var u=di(a,n.shape,r,1,i),d=z.runKernelFunc((function(e){return e.conv3dDerInput(o,n,u)}),{dy5D:o});return s?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}var El=W({conv1d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NWC`),a===void 0&&(a=1);var s=U(e,`x`,`conv1d`),c=U(t,`filter`,`conv1d`),l=s,u=!1;s.rank===2&&(u=!0,l=s.as3D(1,s.shape[0],s.shape[1])),O(l.rank===3,(function(){return`Error in conv1d: input must be rank 3, but got rank `+l.rank+`.`})),O(c.rank===3,(function(){return`Error in conv1d: filter must be rank 3, but got rank `+c.rank+`.`})),o!=null&&O(P(r),(function(){return`Error in conv1d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`})),O(l.shape[2]===c.shape[1],(function(){return`Error in conv1d: depth of input (`+l.shape[2]+`) must match input depth for filter `+c.shape[1]+`.`})),O(vi(n,a),(function(){return`Error in conv1D: Either stride or dilation must be 1. Got stride `+n+` and dilation '`+a+`'`})),O(i===`NWC`,(function(){return`Error in conv1d: got dataFormat of `+i+` but only NWC is currently supported.`}));var d=c.as4D(1,c.shape[0],c.shape[1],c.shape[2]),f=Dl(l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),d,[1,n],r,`NHWC`,[1,a],o);return u?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),Dl=W({conv2d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NHWC`),a===void 0&&(a=[1,1]);var s=U(e,`x`,`conv2d`),c=U(t,`filter`,`conv2d`),l=s,u=!1;s.rank===3&&(u=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),O(l.rank===4,(function(){return`Error in conv2d: input must be rank 4, but got rank `+l.rank+`.`})),O(c.rank===4,(function(){return`Error in conv2d: filter must be rank 4, but got rank `+c.rank+`.`})),o!=null&&O(P(r),(function(){return`Error in conv2d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`}));var d=i===`NHWC`?l.shape[3]:l.shape[1];O(d===c.shape[2],(function(){return`Error in conv2d: depth of input (`+d+`) must match input depth for filter `+c.shape[2]+`.`})),O(vi(n,a),(function(){return`Error in conv2D: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`}));var f=yi(i),p=ui(l.shape,c.shape,n,a,r,o,!1,f),m=[c,l],h=z.runKernelFunc((function(e,t){var n=e.conv2d(l,c,p);return t([c,l]),n}),{x:l,filter:c},(function(e,t){var o=t,s=o[0],c=o[1];return O(_i(a),(function(){return`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+a+`'`})),{x:function(){return Al(c.shape,e,s,n,r,i)},filter:function(){return kl(c,e,s.shape,n,r,i)}}}),`Conv2D`,p,m);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),Ol=W({conv3d_:function(e,t,n,r,i,a){i===void 0&&(i=`NDHWC`),a===void 0&&(a=[1,1,1]);var o=U(e,`x`,`conv3d`),s=U(t,`filter`,`conv3d`),c=o,l=!1;o.rank===4&&(l=!0,c=o.as5D(1,o.shape[0],o.shape[1],o.shape[2],o.shape[3])),O(c.rank===5,(function(){return`Error in conv3d: input must be rank 5, but got rank `+c.rank+`.`})),O(s.rank===5,(function(){return`Error in conv3d: filter must be rank 5, but got rank `+s.rank+`.`})),O(c.shape[4]===s.shape[3],(function(){return`Error in conv3d: depth of input (`+c.shape[4]+`) must match input depth for filter `+s.shape[3]+`.`})),O(function(e,t){return wl(e)||wl(t)}(n,a),(function(){return`Error in conv3D: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`})),O(i===`NDHWC`,(function(){return`Error in conv3d: got dataFormat of `+i+` but only NDHWC is currently supported.`}));var u=di(c.shape,s.shape,n,a,r),d=z.runKernelFunc((function(e,t){var n=e.conv3d(c,s,u);return t([c,s]),n}),{x:c,$filter:s},(function(e,t){O(wl(a),(function(){return`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+a+`'`}));var i=t[0],o=t[1];return{x:function(){return Tl(i.shape,e,o,n,r)},$filter:function(){return function(e,t,n,r,i){var a=e;e.rank===4&&(a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));var o=t;o.rank===4&&(o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3])),O(a.rank===5,(function(){return`Error in conv3dDerFilter: input must be rank 5, but got shape `+a.shape+`.`})),O(o.rank===5,(function(){return`Error in conv3dDerFilter: dy must be rank 5, but got shape `+o.shape+`.`})),O(n.length===5,(function(){return`Error in conv3dDerFilter: filterShape must be length 5, but got `+n+`.`})),O(a.shape[4]===n[3],(function(){return`Error in conv3dDerFilter: depth of input `+a.shape[4]+`) must match input depth in filter (`+n[3]+`.`})),O(o.shape[4]===n[4],(function(){return`Error in conv3dDerFilter: depth of dy (`+o.shape[4]+`) must match output depth for filter (`+n[4]+`).`}));var s=di(a.shape,n,r,1,i);return z.runKernelFunc((function(e){return e.conv3dDerFilter(a,o,s)}),{x5D:a,dy5D:o})}(i,e,o.shape,n,r)}}}));return l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),kl=W({conv2dDerFilter_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NHWC`);var s=e;e.rank===3&&(s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t;c.rank===3&&(c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),O(s.rank===4,(function(){return`Error in conv2dDerFilter: input must be rank 4, but got shape `+s.shape+`.`})),O(c.rank===4,(function(){return`Error in conv2dDerFilter: dy must be rank 4, but got shape `+c.shape+`.`})),O(n.length===4,(function(){return`Error in conv2dDerFilter: filterShape must be length 4, but got `+n+`.`}));var l=a===`NHWC`?s.shape[3]:s.shape[1],u=a===`NHWC`?c.shape[3]:c.shape[1];O(l===n[2],(function(){return`Error in conv2dDerFilter: depth of input `+l+`) must match input depth in filter (`+n[2]+`.`})),O(u===n[3],(function(){return`Error in conv2dDerFilter: depth of dy (`+u+`) must match output depth for filter (`+n[3]+`).`})),o!=null&&O(P(i),(function(){return`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+i+`.`}));var d=yi(a),f=ui(s.shape,n,r,1,i,o,!1,d);return z.runKernelFunc((function(e){return e.conv2dDerFilter(s,c,f)}),{x4D:s,dy4D:c})}}),Al=W({conv2dDerInput_:Cl}),jl=W({depthwiseConv2d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NHWC`),a===void 0&&(a=[1,1]);var s=U(e,`x`,`depthwiseConv2d`),c=U(t,`filter`,`depthwiseConv2d`),l=s,u=!1;s.rank===3&&(u=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),O(l.rank===4,(function(){return`Error in depthwiseConv2d: input must be rank 4, but got rank `+l.rank+`.`})),O(c.rank===4,(function(){return`Error in depthwiseConv2d: filter must be rank 4, but got rank `+c.rank+`.`})),O(l.shape[3]===c.shape[2],(function(){return`Error in depthwiseConv2d: number of input channels (`+l.shape[3]+`) must match the inChannels dimension in filter `+c.shape[2]+`.`})),a??=[1,1],O(vi(n,a),(function(){return`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`})),o!=null&&O(P(r),(function(){return`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`}));var d=ui(l.shape,c.shape,n,a,r,o,!0),f=[l,c],p=z.runKernelFunc((function(e,t){var n=e.depthwiseConv2D(l,c,d);return t([l,c]),n}),{x:l,filter:c},(function(e,t){O(_i(a),(function(){return`Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '`+a+`'`}));var n=t[0],r=t[1];return{x:function(){return Ml(n.shape,e,r,d)},filter:function(){return Nl(n,e,r.shape,d)}}}),`DepthwiseConv2dNative`,d,f);return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),Ml=W({depthwiseConv2dDerInput_:function(e,t,n,r){var i=t,a=!1;t.rank===3&&(a=!0,i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=z.runKernelFunc((function(e){return e.depthwiseConv2DDerInput(i,n,r)}),{dy4D:i});return a?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}}),Nl=W({depthwiseConv2dDerFilter_:function(e,t,n,r){var i=e;e.rank===3&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var a=t;return a.rank===3&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),z.runKernelFunc((function(e){return e.depthwiseConv2DDerFilter(i,a,r)}),{x4D:i,dy4D:a})}}),Pl=W({separableConv2d_:function(e,t,n,r,i,a,o){a===void 0&&(a=[1,1]),o===void 0&&(o=`NHWC`);var s=U(e,`x`,`separableConv2d`),c=U(t,`depthwiseFilter`,`separableConv2d`),l=U(n,`pointwiseFilter`,`separableConv2d`),u=s,d=!1;if(s.rank===3&&(d=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),o===`NCHW`)throw Error(`separableConv2d currently does not support dataFormat NCHW; only NHWC is supported`);O(u.rank===4,(function(){return`Error in separableConv2d: input must be rank 4, but got rank `+u.rank+`.`})),O(c.rank===4,(function(){return`Error in separableConv2d: depthwise filter must be rank 4, but got rank `+c.rank+`.`})),O(l.rank===4,(function(){return`Error in separableConv2d: pointwise filter must be rank 4, but got rank `+c.rank+`.`})),O(l.shape[0]===1,(function(){return`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got `+l.shape[0]+`.`})),O(l.shape[1]===1,(function(){return`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got `+l.shape[1]+`.`}));var f=c.shape[2],p=c.shape[3];O(l.shape[2]===f*p,(function(){return`Error in separableConv2d: the third dimension of pointwise filter must be `+f*p+`, but got `+l.shape[2]+`.`}));var m=Dl(jl(u,c,r,i,o,a),l,1,`valid`,o);return d?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Fl=W({conv2dTranspose_:function(e,t,n,r,i,a){return Cl(n,U(e,`x`,`conv2dTranspose`),U(t,`filter`,`conv2dTranspose`),r,i,`NHWC`,a)}}),Il=W({conv3dTranspose_:function(e,t,n,r,i){return Tl(n,U(e,`x`,`conv3dTranspose`),U(t,`filter`,`conv3dTranspose`),r,i)}}),Ll=W({matMul_:function(e,t,n,r){var i;n===void 0&&(n=!1),r===void 0&&(r=!1);var a=U(e,`a`,`matMul`),o=U(t,`b`,`matMul`);i=Ze(a,o),a=i[0],o=i[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],c=r?o.shape[o.rank-1]:o.shape[o.rank-2],l=n?a.shape[a.rank-1]:a.shape[a.rank-2],u=r?o.shape[o.rank-2]:o.shape[o.rank-1],d=a.shape.slice(0,-2),f=o.shape.slice(0,-2),p=M(d),m=M(f);O(a.rank>=2&&o.rank>=2&&a.rank===o.rank,(function(){return`Error in matMul: inputs must have the same rank of at least 2, got ranks `+a.rank+` and `+o.rank+`.`})),O(N(d,f),(function(){return`Error in matMul: outer dimensions (`+d+`) and (`+f+`) of Tensors with shapes `+a.shape+` and `+o.shape+` must match.`})),O(s===c,(function(){return`Error in matMul: inner shapes (`+s+`) and (`+c+`) of Tensors with shapes `+a.shape+` and `+o.shape+` and transposeA=`+n+` and transposeB=`+r+` must match.`}));var h=a.shape.slice(0,-2).concat([l,u]),g=n?a.as3D(p,s,l):a.as3D(p,l,s),_=r?o.as3D(m,u,c):o.as3D(m,c,u),v={transposeA:n,transposeB:r};return z.runKernelFunc((function(e,t){var i=e.batchMatMul(g,_,n,r);return t([g,_]),i}),{a:g,b:_},(function(e,t){var i=t,a=i[0],o=i[1];return n||r?!n&&r?{a:function(){return e.matMul(o,!1,!1)},b:function(){return e.matMul(a,!0,!1)}}:n&&!r?{a:function(){return o.matMul(e,!1,!0)},b:function(){return a.matMul(e,!1,!1)}}:{a:function(){return o.matMul(e,!0,!0)},b:function(){return e.matMul(a,!0,!0)}}:{a:function(){return e.matMul(o,!1,!0)},b:function(){return a.matMul(e,!0,!1)}}}),`BatchMatMul`,v).reshape(h)}}),Rl=W({dot_:function(e,t){var n=U(e,`t1`,`dot`),r=U(t,`t2`,`dot`);O(!(n.rank!==1&&n.rank!==2||r.rank!==1&&r.rank!==2),(function(){return`Error in dot: inputs must all be rank 1 or 2, but got ranks `+n.rank+` and `+r.rank+`.`}));var i=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];return O(i===a,(function(){return`Error in dot: inner dimensions of inputs must match, but got `+i+` and `+a+`.`})),n.rank===1&&r.rank===1?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():n.rank===1&&r.rank===2?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():n.rank===2&&r.rank===1?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),zl=W({outerProduct_:function(e,t){var n=U(e,`v1`,`outerProduct`),r=U(t,`v2`,`outerProduct`);return O(n.rank===1&&r.rank===1,(function(){return`Error in outerProduct: inputs must be rank 1, but got ranks `+n.rank+` and `+r.rank+`.`})),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Bl=W({reverse_:function(e,t){var n=U(e,`x`,`reverse`);if(n.rank===0)return n.clone();var r=L(t,n.shape);return z.runKernelFunc((function(e){return e.reverse(n,r)}),{$x:n},(function(e){return{$x:function(){return e.reverse(r)}}})).reshapeAs(n)}}),Vl=W({reverse1d_:function(e){var t=U(e,`x`,`reverse`);return O(t.rank===1,(function(){return`Error in reverse1D: x must be rank 1 but got rank `+t.rank+`.`})),Bl(t,0)}}),Hl=W({reverse2d_:function(e,t){var n=U(e,`x`,`reverse`);return O(n.rank===2,(function(){return`Error in reverse2D: x must be rank 2 but got rank `+n.rank+`.`})),Bl(n,t)}}),Ul=W({reverse3d_:function(e,t){var n=U(e,`x`,`reverse`);return O(n.rank===3,(function(){return`Error in reverse3D: x must be rank 3 but got rank `+n.rank+`.`})),Bl(n,t)}}),Wl=W({reverse4d_:function(e,t){var n=U(e,`x`,`reverse`);return O(n.rank===4,(function(){return`Error in reverse4D: x must be rank 4 but got rank `+n.rank+`.`})),Bl(n,t)}});function Gl(e,t,n,r,i,a){var o=U(e,`x`,`maxPool`),s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),r??=[1,1],O(s.rank===4,(function(){return`Error in maxPool: input must be rank 4 but got rank `+s.rank+`.`})),O(vi(n,r),(function(){return`Error in maxPool: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+r+`'`})),a!=null&&O(P(i),(function(){return`Error in maxPool: pad must be an integer when using, dimRoundingMode `+a+` but got pad `+i+`.`}));var l=ci(s.shape,t,n,r,i,a);if(l.filterWidth===1&&l.filterHeight===1&&N(l.inShape,l.outShape))return o.clone();var u=[s],d=z.runKernelFunc((function(e,t){var n=e.maxPool(s,l);return t([s,n]),n}),{x:s},(function(e,a){var o=a[0],s=a[1];return{x:function(){return function(e,t,n,r,i,a,o,s){var c=U(e,`dy`,`maxPoolBackprop`),l=U(t,`input`,`maxPoolBackprop`),u=U(n,`output`,`maxPoolBackprop`);O(l.rank===c.rank,(function(){return`Rank of input (`+l.rank+`) does not match rank of dy (`+c.rank+`)`})),a??=[1,1],O(vi(i,a),(function(){return`Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides `+i+` and dilations '`+a+`'`})),O(c.rank===4,(function(){return`Error in maxPoolBackprop: dy must be rank 4 but got rank `+c.rank+`.`})),O(l.rank===4,(function(){return`Error in maxPoolBackprop: input must be rank 4 but got rank `+l.rank+`.`})),s!=null&&O(P(o),(function(){return`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode `+s+` but got pad `+o+`.`}));var d=ci(l.shape,r,i,a,o,s);return z.runKernelFunc((function(e){return e.maxPoolBackprop(c,l,u,d)}),{$dy:c,$input:l})}(e,o,s,t,n,r,i)}}}),`MaxPool`,l,u);return c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function Kl(e,t,n,r,i,a){var o=U(e,`x`,`avgPool`,`float32`);r??=[1,1],O(vi(n,r),(function(){return`Error in avgPool: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+r+`'`}));var s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),O(s.rank===4,(function(){return`Error in avgPool: x must be rank 4 but got rank `+s.rank+`.`})),a!=null&&O(P(i),(function(){return`Error in avgPool: pad must be an integer when using, dimRoundingMode `+a+` but got pad `+i+`.`}));var l=ci(s.shape,t,n,r,i,a);if(l.filterWidth===1&&l.filterHeight===1&&N(l.inShape,l.outShape))return o.clone();var u=z.runKernelFunc((function(e){return e.avgPool(s,l)}),{x:s},(function(e){return{x:function(){return function(e,t,n,r,i,a){var o=U(e,`dy`,`avgPoolBackprop`),s=U(t,`input`,`avgPoolBackprop`);O(s.rank===o.rank,(function(){return`Rank of input (`+s.rank+`) does not match rank of dy (`+o.rank+`)`})),i??=[1,1],O(vi(r,i),(function(){return`Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+i+`'`}));var c=s,l=o,u=!1;s.rank===3&&(u=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),O(l.rank===4,(function(){return`Error in avgPoolBackprop: dy must be rank 4 but got rank `+l.rank+`.`})),O(c.rank===4,(function(){return`Error in avgPoolBackprop: input must be rank 4 but got rank `+c.rank+`.`}));var d=ci(c.shape,n,r,i,a),f=z.runKernelFunc((function(e){return e.avgPoolBackprop(l,c,d)}),{dy4D:l,input4D:c});return u?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(e,s,t,n,r,i)}}}),`AvgPool`,l);return u=u.cast(o.dtype),c?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}var ql=W({maxPool_:function(e,t,n,r,i){return Gl(e,t,n,1,r,i)}}),Jl=W({avgPool_:function(e,t,n,r,i){return Kl(e,t,n,1,r,i)}}),Yl=W({pool_:function(e,t,n,r,i,a){i??=[1,1],a??=1,r===0&&(r=`valid`);var o=U(e,`x`,`maxPool`),s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),O(vi(a,i),(function(){return`Error in pool: Either strides or dilations must be 1. Got strides `+a+` and dilations '`+i+`'`}));var l,u=ci(s.shape,t,a,i,r),d=[u.dilationHeight,u.dilationWidth];l=r===`same`?function(e,t){var n=e.map((function(e,n){return e+(e-1)*(t[n]-1)})).map((function(e){return e-1})),r=n.map((function(e){return Math.floor(e/2)})),i=n.map((function(e,t){return e-r[t]}));return n.map((function(e,t){return[r[t],i[t]]}))}([u.filterHeight,u.filterWidth],d):[[0,0],[0,0]];var f=d[0]===1&&d[1]===1,p=function(e,t,n){var r=n.map((function(e){return e[0]})),i=n.map((function(e){return e[1]})),a=e.concat(r,i),o=t.map((function(e,t){return(e-a[t]%e)%e})),s=i.map((function(e,t){return e+o[t]}));return[t.map((function(e,t){return[r[t],s[t]]})),t.map((function(e,t){return[0,o[t]]}))]}([u.inHeight,u.inWidth],d,l),m=p[0],h=p[1],g=f?r:`valid`,_=f?s:kr(s,d,m),v=(n===`avg`?function(){return Kl(_,t,a,1,g)}:function(){return Gl(_,t,a,1,g)})(),y=f?v:lr(v,d,h);return c?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}}),Xl=W({maxPool3d_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NDHWC`);var s=U(e,`x`,`maxPool3d`),c=s,l=!1;s.rank===4&&(l=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),o??=[1,1,1],O(c.rank===5,(function(){return`Error in maxPool3d: x must be rank 5 but got rank `+c.rank+`.`})),O(a===`NDHWC`,(function(){return`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of `+a})),O(vi(n,o),(function(){return`Error in maxPool3d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+o+`'`})),i!=null&&O(P(r),(function(){return`Error in maxPool3d: pad must be an integer when using, dimRoundingMode `+i+` but got pad `+r+`.`}));var u=li(c.shape,t,n,o,r,i,a),d=z.runKernelFunc((function(e,t){var n=e.maxPool3d(c,u);return t([c,n]),n}),{x:c},(function(e,a){var s=a[0],c=a[1];return{x:function(){return function(e,t,n,r,i,a,o,s){var c=U(e,`dy`,`maxPool3dBackprop`),l=U(t,`input`,`maxPool3dBackprop`),u=U(n,`output`,`maxPool3dBackprop`),d=c,f=l,p=u,m=!1;l.rank===4&&(m=!0,d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),f=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),O(d.rank===5,(function(){return`Error in maxPool3dBackprop: dy must be rank 5 but got rank `+d.rank+`.`})),O(f.rank===5,(function(){return`Error in maxPool3dBackprop: input must be rank 5 but got rank `+f.rank+`.`})),O(p.rank===5,(function(){return`Error in maxPool3dBackprop: output must be rank 5 but got rank `+p.rank+`.`})),a??=[1,1,1],O(vi(i,a),(function(){return`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides `+i+` and dilations '`+a+`'`})),s!=null&&O(P(o),(function(){return`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode `+s+` but got pad `+o+`.`}));var h=li(f.shape,r,i,a,o,s),g=z.runKernelFunc((function(e){return e.maxPool3dBackprop(d,f,p,h)}),{dy5D:d,input5D:f});return m?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(e,s,c,t,n,o,r,i)}}}));return l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),Zl=W({avgPool3d_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NDHWC`);var s=U(e,`x`,`avgPool3d`,`float32`),c=s,l=!1;s.rank===4&&(l=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),o??=[1,1,1],O(c.rank===5,(function(){return`Error in avgPool3d: x must be rank 5 but got rank `+c.rank+`.`})),O(a===`NDHWC`,(function(){return`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of `+a})),O(vi(n,o),(function(){return`Error in avgPool3d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+o+`'`})),i!=null&&O(P(r),(function(){return`Error in avgPool3d: pad must be an integer when using, dimRoundingMode `+i+` but got pad `+r+`.`}));var u=li(c.shape,t,n,o,r,i,a),d=z.runKernelFunc((function(e){return e.avgPool3d(c,u)}),{x:c},(function(e){return{x:function(){return function(e,t,n,r,i,a,o){var s=U(e,`dy`,`avgPool3dBackprop`),c=U(t,`input`,`avgPool3dBackprop`),l=s,u=c,d=!1;c.rank===4&&(d=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),u=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),O(l.rank===5,(function(){return`Error in avgPool3dBackprop: dy must be rank 5 but got rank `+l.rank+`.`})),O(u.rank===5,(function(){return`Error in avgPool3dBackprop: input must be rank 5 but got rank `+u.rank+`.`})),i??=[1,1,1],O(vi(r,i),(function(){return`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+i+`'`})),o!=null&&O(P(a),(function(){return`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+a+`.`}));var f=li(u.shape,n,r,i,a,o),p=z.runKernelFunc((function(e){return e.avgPool3dBackprop(l,u,f)}),{dy5D:l,input5D:u});return d?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}(e,c,t,n,o,r,i)}}}));return d=d.cast(c.dtype),l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),Ql=W({slice_:function(e,t,n){var r,i,a=U(e,`x`,`slice`);if(a.rank===0)throw Error(`Slicing scalar is not possible`);(r=typeof t==`number`?[t].concat(Array(a.rank-1).fill(0)):t.length<a.rank?t.concat(Array(a.rank-t.length).fill(0)):t.slice()).forEach((function(e){O(e!==-1,(function(){return`slice() does not support negative begin indexing.`}))})),i=(i=n==null?Array(a.rank).fill(-1):typeof n==`number`?[n].concat(Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(Array(a.rank-n.length).fill(-1)):n).map((function(e,t){return e>=0?e:(O(e===-1,(function(){return`Negative size values should be exactly -1 but got `+e+` for the slice() size at index `+t+`.`})),a.shape[t]-r[t])})),qr(a,r,i);var o=a.shape,s={begin:r,size:i};return z.runKernelFunc((function(e){return e.slice(a,r,i)}),{x:a},(function(e){for(var t=[],n=0;n<e.rank;n++)t.push([r[n],o[n]-r[n]-i[n]]);return{x:function(){return e.pad(t)}}}),`Slice`,s)}}),$l=W({slice1d_:function(e,t,n){var r=U(e,`x`,`slice1d`);return O(r.rank===1,(function(){return`slice1d expects a rank-1 tensor, but got a rank-`+r.rank+` tensor`})),Ql(r,[t],[n])}}),eu=W({slice2d_:function(e,t,n){var r=U(e,`x`,`slice2d`);return O(r.rank===2,(function(){return`slice2d expects a rank-2 tensor, but got a rank-`+r.rank+` tensor`})),Ql(r,t,n)}}),tu=W({slice3d_:function(e,t,n){var r=U(e,`x`,`slice3d`);return O(r.rank===3,(function(){return`slice3d expects a rank-3 tensor, but got a rank-`+r.rank+` tensor`})),Ql(r,t,n)}}),nu=W({slice4d_:function(e,t,n){var r=U(e,`x`,`slice4d`);return O(r.rank===4,(function(){return`slice4d expects a rank-4 tensor, but got a rank-`+r.rank+` tensor`})),Ql(r,t,n)}});function ru(e,t,n,r,i){return t.rank<n.rank&&(t=t.reshape(vn(t.shape,r))),e.rank<n.rank&&(e=e.reshape(vn(e.shape,r))),{x:function(){var r=e.mul(n.equal(t).cast(e.dtype));return i==null?r:r.transpose(i)}}}var iu=W({all_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`all`,`bool`),i=L(t,r.shape),a=i,o=bn(a,r.rank);o!=null&&(r=r.transpose(o),a=Sn(a.length,r.rank));var s=z.runKernelFunc((function(e){return e.all(r,a)}),{$x:r});if(n){var c=vn(s.shape,i);return s.reshape(c)}return s}}),au=W({any_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`any`,`bool`),i=L(t,r.shape),a=i,o=bn(a,r.rank);o!=null&&(r=r.transpose(o),a=Sn(a.length,r.rank));var s=z.runKernelFunc((function(e){return e.any(r,a)}),{$x:r});if(n){var c=vn(s.shape,i);return s.reshape(c)}return s}}),ou=W({argMax_:function(e,t){t===void 0&&(t=0);var n=U(e,`x`,`argMax`);t??=0;var r=L(t,n.shape),i=bn(r,n.rank);i!=null&&(n=n.transpose(i),r=Sn(r.length,n.rank));var a={axis:r[0]},o=[n];return z.runKernelFunc((function(e,t){var i=e.argMax(n,r[0]);return t([n]),i}),{x:n},(function(e,t){var n=t[0];return{x:function(){return Un(n)}}}),`ArgMax`,a,o)}}),su=W({argMin_:function(e,t){t===void 0&&(t=0);var n=U(e,`x`,`argMin`);t??=0;var r=L(t,n.shape),i=bn(r,n.rank);return i!=null&&(n=n.transpose(i),r=Sn(r.length,n.rank)),z.runKernelFunc((function(e,t){var i=e.argMin(n,r[0]);return t([n]),i}),{$x:n},(function(e,t){var n=t[0];return{$x:function(){return Un(n)}}}))}}),cu=W({logSumExp_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`logSumExp`),i=L(t,r.shape),a=r.max(i,!0),o=r.sub(a).exp().sum(i).log(),s=a.reshape(o.shape).add(o);if(n){var c=vn(s.shape,i);return s.reshape(c)}return s}}),lu=W({max_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`max`),i=r,a=L(t,r.shape),o=a,s=bn(o,r.rank);s!=null&&(r=r.transpose(s),o=Sn(o.length,r.rank));var c=[r],l=z.runKernelFunc((function(e,t){var n=e.max(r,o);return t([i,n]),n}),{x:r},(function(e,t){return ru(e,t[1],t[0],a,s)}),`Max`,{axes:o},c,[!0]);if(n){var u=vn(l.shape,a);l=l.reshape(u)}return l}}),uu=W({mean_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`mean`),i=L(t,r.shape),a=M(_n(r.shape,i)[1]);return ti((function(e){var r=G(a);return{value:(r.dtype===e.dtype?e:e.cast(r.dtype)).div(r).sum(t,n),gradFunc:function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(Ln(e.shape,`float32`)).div(a)}}}))(r)}}),du=W({min_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`min`),i=r,a=L(t,r.shape),o=a,s=bn(o,r.rank);s!=null&&(r=r.transpose(s),o=Sn(o.length,r.rank));var c=[r],l=z.runKernelFunc((function(e,t){var n=e.min(r,o);return t([i,n]),n}),{x:r},(function(e,t){return ru(e,t[1],t[0],a,s)}),`Min`,{axes:o},c,[!0]);if(n){var u=vn(l.shape,a);l=l.reshape(u)}return l}}),fu=W({moments_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=L(t,(e=U(e,`x`,`moments`)).shape),i=e.mean(r,n),a=i.shape;return n||(a=vn(i.shape,r)),{mean:i,variance:e.toFloat().sub(i.reshape(a)).square().mean(r,n)}}}),pu=W({sum_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`sum`);r.dtype===`bool`&&(r=r.toInt());var i=L(t,r.shape);return ti((function(e){var t=bn(i,e.rank),r=i,a=e;t!=null&&(a=e.transpose(t),r=Sn(r.length,e.rank));var o=function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(Ln(e.shape,`float32`))},s={axes:r},c=z.runKernelFunc((function(e){return e.sum(a,r)}),{x:a},(function(e){return{x:function(){return o(e)}}}),`Sum`,s);if(n){var l=vn(c.shape,i);c=c.reshape(l)}return{value:c,gradFunc:o}}))(r)}}),mu=W({prod_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=U(e,`x`,`prod`);r.dtype===`bool`&&(r=r.toInt());var i=L(t,r.shape),a=bn(i,r.rank),o=i,s=r;a!=null&&(s=r.transpose(a),o=Sn(o.length,r.rank));var c=z.runKernelFunc((function(e){return e.prod(s,o)}),{permutedX:s});if(n){var l=vn(c.shape,i);c=c.reshape(l)}return c}}),hu=W({elu_:function(e){var t=U(e,`x`,`elu`);return z.runKernelFunc((function(e,n){var r=e.elu(t);return n([r]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return z.runKernelFunc((function(t){return t.eluDer(e,n)}),{dy:e,y:n})}}}))}}),gu=W({leakyRelu_:function(e,t){t===void 0&&(t=.2);var n=U(e,`x`,`leakyRelu`);return qc(G(t).mul(n),n)}}),_u=W({prelu_:function(e,t){var n=U(e,`x`,`prelu`),r=U(t,`alpha`,`prelu`);return z.runKernelFunc((function(e,t){var i=e.prelu(n,r);return t([n,r]),i}),{x:n,alpha:r},(function(e,t){var n=t[0],r=t[1],i=n.greater(0);return{x:function(){return Lc(i,e,e.mul(r))},alpha:function(){var t=Lc(i,Un(e),e.mul(n)),a=si(r.shape,e.shape);return a.length>0&&(t=t.sum(a)),t.reshape(r.shape)}}}),`Prelu`)}}),vu=W({relu_:function(e){var t=U(e,`x`,`relu`);return t.dtype===`bool`?t.toInt():z.runKernelFunc((function(e,n){var r=e.relu(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mulStrict(n.step().toFloat())}}}),`Relu`)}}),yu=W({relu6_:function(e){var t=U(e,`x`,`relu6`);return t.dtype===`bool`?t.toInt():z.runKernelFunc((function(e,n){var r=e.relu6(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return e.mulStrict(r.toFloat())}}}),`Relu6`)}}),bu=W({selu_:function(e){var t=U(e,`x`,`selu`);return z.runKernelFunc((function(e,n){var r=e.selu(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){var t=n.greater(G(0)),r=G(rs),i=G(is);return Lc(t,e.mul(i),e.mul(r).mul(n.toFloat().exp()))}}}))}}),xu=W({transpose_:function(e,t){var n=U(e,`x`,`transpose`);if(t??=n.shape.map((function(e,t){return t})).reverse(),O(n.rank===t.length,(function(){return`Error in transpose: rank of input `+n.rank+` must match length of perm `+t+`.`})),t.forEach((function(e){O(e>=0&&e<n.rank,(function(){return`All entries in 'perm' must be between 0 and `+(n.rank-1)+` but got `+t}))})),n.rank<=1)return n.clone();var r={perm:t};return z.runKernelFunc((function(e){return e.transpose(n,t)}),{x:n},(function(e){var n=xn(t);return{x:function(){return e.transpose(n)}}}),`Transpose`,r)}}),Su=W({localResponseNormalization_:function(e,t,n,r,i){t===void 0&&(t=5),n===void 0&&(n=1),r===void 0&&(r=1),i===void 0&&(i=.5);var a=U(e,`x`,`localResponseNormalization`);O(a.rank===4||a.rank===3,(function(){return`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
3740
|
-
rank `+a.rank+`.`})),O(P(t),(function(){return`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius `+t+`.`}));var o=a,s=!1;a.rank===3&&(s=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var c=z.runKernelFunc((function(e,a){var s=e.localResponseNormalization4D(o,t,n,r,i);return a([o,s]),s}),{x4D:o},(function(e,a){var o=a[0],s=a[1];return{x4D:function(){return z.runKernelFunc((function(a){return a.LRNGrad(e,o,s,t,n,r,i)}),{})}}}));return s?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),Cu=W({norm_:function(e,t,n,r){t===void 0&&(t=`euclidean`),n===void 0&&(n=null),r===void 0&&(r=!1);var i=function e(t,n,r){if(r===void 0&&(r=null),t.rank===0)return t.abs();if(t.rank!==1&&r===null)return e(t.reshape([-1]),n,r);if(t.rank===1||typeof r==`number`||Array.isArray(r)&&r.length===1){if(n===1)return t.abs().sum(r);if(n===1/0)return t.abs().max(r);if(n===-1/0)return t.abs().min(r);if(n===`euclidean`||n===2)return t.abs().pow(G(2,`int32`)).sum(r).sqrt();throw Error(`Error in norm: invalid ord value: `+n)}if(Array.isArray(r)&&r.length===2){if(n===1)return t.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return t.abs().sum(r[1]).max(r[0]);if(n===-1/0)return t.abs().sum(r[1]).min(r[0]);if(n===`fro`||n===`euclidean`)return t.square().sum(r).sqrt();throw Error(`Error in norm: invalid ord value: `+n)}throw Error(`Error in norm: invalid axis: `+r)}(e=U(e,`x`,`norm`),t,n),a=i.shape;if(r){var o=L(n,e.shape);a=vn(i.shape,o)}return i.reshape(a)}}),wu=W({basicLSTMCell_:function(e,t,n,r,i,a){var o=U(e,`forgetBias`,`basicLSTMCell`),s=U(t,`lstmKernel`,`basicLSTMCell`),c=U(n,`lstmBias`,`basicLSTMCell`),l=U(r,`data`,`basicLSTMCell`),u=U(i,`c`,`basicLSTMCell`),d=U(a,`h`,`basicLSTMCell`),f=l.concat(d,1).matMul(s).add(c),p=f.shape[0],m=f.shape[1]/4,h=[p,m],g=f.slice([0,0],h),_=f.slice([0,m],h),v=f.slice([0,2*m],h),y=f.slice([0,3*m],h),b=g.sigmoid().mulStrict(_.tanh()).addStrict(u.mulStrict(o.add(v).sigmoid()));return[b,b.tanh().mulStrict(y.sigmoid())]}}),Tu=W({multiRNNCell_:function(e,t,n,r){for(var i=U(t,`data`,`multiRNNCell`),a=mn(n,`c`,`multiRNNCell`),o=mn(r,`h`,`multiRNNCell`),s=i,c=[],l=0;l<e.length;l++){var u=e[l](s,a[l],o[l]);c.push(u[0]),c.push(u[1]),s=u[1]}var d=[],f=[];for(l=0;l<c.length;l+=2)d.push(c[l]),f.push(c[l+1]);return[d,f]}}),Eu=W({movingAverage_:function(e,t,n,r,i){i===void 0&&(i=!0);var a=U(e,`v`,`movingAverage`),o=U(t,`x`,`movingAverage`),s=U(n,`decay`,`movingAverage`);Qe(a,o),O(N(a.shape,o.shape),(function(){return`Shape mismatch in v and x`}));var c=G(1),l=c.sub(s),u=o.sub(a).mul(l);if(i){O(r!=null,(function(){return`When using zeroDebias: true, step is required.`}));var d=U(r,`step`,`movingAverage`);u=u.div(c.sub(tl(s,d)))}return a.add(u)}}),Du=W({stridedSlice_:function(e,t,n,r,i,a,o,s,c){if(i===void 0&&(i=0),a===void 0&&(a=0),o===void 0&&(o=0),s===void 0&&(s=0),c===void 0&&(c=0),r??=Array(t.length),o!==0)throw Error(`ellipsis mask is not yet supported`);var l=U(e,`x`,`stridedSlice`),u=Jr(s),d=l.shape.slice();u.forEach((function(e){t[e]=0,n[e]=1,d.splice(e,0,1)})),l=l.reshape(d);for(var f=0;f<l.rank;f++)t[f]=Xr(i,t,r,l.shape,f),n[f]=Zr(a,n,r,l.shape,f),r[f]=r[f]||1;var p=Jr(c);p.forEach((function(e){n[e]=t[e]+1,r[e]=1}));var m=Yr(t,n,r),h=m.filter((function(e,t){return p.indexOf(t)===-1}));return r.every((function(e){return e===1}))?Ql(l,t,m).reshape(h):z.runKernelFunc((function(e){return e.stridedSlice(l,t,n,r)}),{$x:l}).reshape(h)}}),Ou=W({topk_:function(e,t,n){t===void 0&&(t=1),n===void 0&&(n=!0);var r=U(e,`x`,`topk`);if(r.rank===0)throw Error(`topk() expects the input to be of rank 1 or higher`);var i=r.shape[r.shape.length-1];if(t>i)throw Error(`'k' passed to topk() must be <= the last dimension (`+i+`) but got `+t);var a=z.runKernelFunc((function(e){return e.topk(r,t,n)}),{$x:r});return{values:a[0],indices:a[1]}}}),ku=W({scatterND_:function(e,t,n){var r=U(e,`indices`,`scatterND`,`int32`),i=U(t,`updates`,`scatterND`);return Gr(i,r,n),z.runKernelFunc((function(e){return e.scatterND(r,i,n)}),{indices:r,updates:i},null,`ScatterNd`,{shape:n})}}),Au=W({fft_:function(e){O(e.dtype===`complex64`,(function(){return`The dtype for tf.spectral.fft() must be complex64 but got `+e.dtype+`.`}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return z.runKernelFunc((function(e){return e.fft(r)}),{input:e}).reshape(e.shape)}}),ju=W({ifft_:function(e){O(e.dtype===`complex64`,(function(){return`The dtype for tf.spectral.ifft() must be complex64 but got `+e.dtype+`.`}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return z.runKernelFunc((function(e){return e.ifft(r)}),{input:e}).reshape(e.shape)}}),Mu=W({rfft_:function(e,t){O(e.dtype===`float32`,(function(){return`The dtype for rfft() must be real value but got `+e.dtype}));var n,r=e.shape[e.shape.length-1],i=e.size/r;if(t!=null&&t<r){var a=e.shape.map((function(e){return 0})),o=e.shape.map((function(e){return e}));o[e.shape.length-1]=t,n=e.slice(a,o),r=t}else if(t!=null&&t>r){var s=e.shape.map((function(e){return e}));s[e.shape.length-1]=t-r,n=e.concat(Rn(s),e.shape.length-1),r=t}else n=e;var c=n.zerosLike(),l=Au(Tn(n,c).as2D(i,r)),u=Math.floor(r/2)+1,d=En(l),f=Dn(l),p=d.split([u,r-u],d.shape.length-1),m=f.split([u,r-u],f.shape.length-1),h=n.shape.slice();return h[n.shape.length-1]=u,Tn(p[0],m[0]).reshape(h)}}),Nu=W({irfft_:function(e){var t=e.shape[e.shape.length-1],n=e.size/t;if(t<=2){var r=e.as2D(n,t),i=ju(r);return En(i)}var a=[n,2*(t-1)],o=En(e).as2D(n,t),s=Dn(e).as2D(n,t),c=o.slice([0,1],[n,t-2]).reverse(1),l=s.slice([0,1],[n,t-2]).reverse(1).mul(G(-1));return r=Tn(o.concat(c,1),s.concat(l,1)).as2D(a[0],a[1]),i=ju(r),En(i)}}),Pu=Object.freeze({fft:Au,ifft:ju,rfft:Mu,irfft:Nu}),Fu=W({sparseToDense_:function(e,t,n,r){r===void 0&&(r=0);var i=U(e,`sparseIndices`,`sparseToDense`,`int32`),a=U(t,`sparseValues`,`sparseToDense`),o=U(r,`defaultValue`,`sparseToDense`,a.dtype);return function(e,t,n,r){if(e.dtype!==`int32`)throw Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was `+e.dtype+`.`);if(e.rank>2)throw Error(`sparseIndices should be a scalar, vector, or matrix, but got shape `+e.shape+`.`);var i=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw Error(`outputShape has incorrect number of elements:, `+n.length+`, should be: `+a+`.`);var o=t.size;if(t.rank!==0&&(t.rank!==1||o!==i))throw Error(`sparseValues has incorrect shape `+t.shape+`, should be [] or [`+i+`]`);if(t.dtype!==r.dtype)throw Error(`sparseValues.dtype must match defaultValues.dtype`)}(i,a,n,o),z.runKernelFunc((function(e){return e.sparseToDense(i,a,n,o)}),{$sparseIndices:i,$sparseValues:a,$defaultValue:o})}}),Iu=W({gatherND_:function(e,t){var n=U(t,`indices`,`gatherND`,`int32`),r=U(e,`x`,`gatherND`);return z.runKernelFunc((function(e){return e.gatherND(r,n)}),{x:r,indices:n},null,`GatherNd`)}}),Lu=W({diag_:function(e){var t=U(e,`x`,`diag`).flatten(),n=e.shape.concat(e.shape);return z.runKernelFunc((function(e){return e.diag(t)}),{$x:t}).reshape(n)}}),Ru=W({dropout_:function(e,t,n,r){var i=U(e,`x`,`dropout`);if(O(i.dtype===`float32`,(function(){return`x has to be a floating point tensor since it's going to be scaled, but got a `+i.dtype+` tensor instead.`})),O(t>=0&&t<1,(function(){return`rate must be a float in the range [0, 1), but got `+t+`.`})),t===0)return e instanceof Ve?i.clone():i;var a=function(e,t){if(t==null)return e.shape.slice();if(N(e.shape,t))return t;if(e.shape.length===t.length){for(var n=[],r=0;r<e.shape.length;r++)t[r]==null&&e.shape[r]!=null?n.push(e.shape[r]):n.push(t[r]);return n}return t}(i,n),o=1-t,s=Dr(a,0,1,`float32`,r).add(o).floor().div(o);return i.mul(s)}});function zu(e,t,n){for(var r=1-e%2,i=new Float32Array(e),a=0;a<e;++a){var o=2*Math.PI*a/(e+r-1);i[a]=t-n*Math.cos(o)}return An(i,`float32`)}var Bu=W({hannWindow_:function(e){return zu(e,.5,.5)}}),Vu=W({hammingWindow_:function(e){return zu(e,.54,.46)}}),Hu=W({frame_:function(e,t,n,r,i){r===void 0&&(r=!1),i===void 0&&(i=0);for(var a=0,o=[];a+t<=e.size;)o.push(Ql(e,a,t)),a+=n;if(r)for(;a<e.size;){var s=a+t-e.size,c=Wn([Ql(e,a,t-s),zn([s],i)]);o.push(c),a+=n}return o.length===0?jn([],[0,t]):Wn(o).as2D(o.length,t)}}),Uu=W({stft_:function(e,t,n,r,i){var a;i===void 0&&(i=Bu),r??=(a=t,Math.floor(2**Math.ceil(Math.log(a)/Math.log(2))));for(var o=Hu(e,t,n),s=$c(o,i(t)),c=[],l=0;l<o.shape[0];l++)c.push(Mu(s.slice([l,0],[1,t]),r));return Wn(c)}}),Wu=Object.freeze({hannWindow:Bu,hammingWindow:Vu,frame:Hu,stft:Uu}),Gu,Ku=function(e,t,n){return n===void 0&&(n=1),u(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,f,p,m,h,g,_;return d(this,(function(d){switch(d.label){case 0:return r=U(e,`predictions`,`inTopK`),i=U(t,`targets`,`inTopK`),O(r.rank>1,(function(){return`inTopK() expects the predictions to be of rank 2 or higher, but got `+r.rank})),O(r.rank-1===i.rank,(function(){return`predictions rank should be 1 larger than targets rank, but got predictions rank `+r.rank+` and targets rank `+i.rank})),k(r.shape.slice(0,r.shape.length-1),i.shape,`predictions's shape should be align with the targets' shape, except the last dimension.`),a=r.shape[r.shape.length-1],O(n>0&&n<=a,(function(){return`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (`+a+`), but got `+n})),[4,r.data()];case 1:return o=d.sent(),[4,i.data()];case 2:for(s=d.sent(),c=[o.length/a,a],u=c[1],f=ie(`bool`,l=c[0]),p=0;p<l;p++){for(m=p*u,h=o.subarray(m,m+u),g=[],_=0;_<h.length;_++)g.push({value:h[_],index:_});for(g.sort((function(e,t){return t.value-e.value})),f[p]=0,_=0;_<n;_++)if(g[_].index===s[p]){f[p]=1;break}}return e!==r&&r.dispose(),t!==i&&i.dispose(),[2,On(f,i.shape,`bool`)]}}))}))};(function(e){e[e.NONE=0]=`NONE`,e[e.MEAN=1]=`MEAN`,e[e.SUM=2]=`SUM`,e[e.SUM_BY_NONZERO_WEIGHTS=3]=`SUM_BY_NONZERO_WEIGHTS`})(Gu||={});var qu=W({absoluteDifference_:function(e,t,n,r){r===void 0&&(r=Gu.SUM_BY_NONZERO_WEIGHTS);var i=U(e,`labels`,`absoluteDifference`),a=U(t,`predictions`,`absoluteDifference`),o=null;return n!=null&&(o=U(n,`weights`,`absoluteDifference`)),k(i.shape,a.shape,`Error in absoluteDifference: `),Ju(i.sub(a).abs(),o,r)}}),Ju=W({computeWeightedLoss_:function(e,t,n){n===void 0&&(n=Gu.SUM_BY_NONZERO_WEIGHTS);var r=U(e,`losses`,`computeWeightedLoss`),i=null;t!=null&&(i=U(t,`weights`,`computeWeightedLoss`));var a=i==null?r:r.mul(i);if(n===Gu.NONE)return a;if(n===Gu.SUM)return a.sum();if(n===Gu.MEAN){if(i==null)return a.mean();var o=r.size/i.size,s=a.sum().div(i.sum());return o>1?s.div(G(o)):s}if(n===Gu.SUM_BY_NONZERO_WEIGHTS){if(i==null)return a.sum().div(G(r.size));var c=i.mul(Ln(r.shape)).notEqual(G(0)).sum().toFloat();return a.sum().div(c)}throw Error(`Unknown reduction: `+n)}}),Yu=W({cosineDistance_:function(e,t,n,r,i){i===void 0&&(i=Gu.SUM_BY_NONZERO_WEIGHTS);var a=U(e,`labels`,`cosineDistance`),o=U(t,`predictions`,`cosineDistance`),s=null;return r!=null&&(s=U(r,`weights`,`cosineDistance`)),k(a.shape,o.shape,`Error in cosineDistance: `),Ju(G(1).sub(a.mul(o).sum(n,!0)),s,i)}}),Xu=W({hingeLoss_:function(e,t,n,r){r===void 0&&(r=Gu.SUM_BY_NONZERO_WEIGHTS);var i=U(e,`labels`,`hingeLoss`),a=U(t,`predictions`,`hingeLoss`),o=null;n!=null&&(o=U(n,`weights`,`hingeLoss`)),k(i.shape,a.shape,`Error in hingeLoss: `);var s=G(1);return i=G(2).mul(i).sub(s),Ju(s.sub(i.mul(a)).relu(),o,r)}}),Zu=W({huberLoss_:function(e,t,n,r,i){r===void 0&&(r=1),i===void 0&&(i=Gu.SUM_BY_NONZERO_WEIGHTS);var a=U(e,`labels`,`huberLoss`),o=U(t,`predictions`,`huberLoss`),s=null;n!=null&&(s=U(n,`weights`,`huberLoss`)),k(a.shape,o.shape,`Error in huberLoss: `);var c=G(r),l=o.sub(a).abs(),u=Yc(l,c),d=l.sub(u);return Ju(G(.5).mul(u.square()).add(c.mul(d)),s,i)}}),Qu=W({logLoss_:function(e,t,n,r,i){r===void 0&&(r=1e-7),i===void 0&&(i=Gu.SUM_BY_NONZERO_WEIGHTS);var a=U(e,`labels`,`logLoss`),o=U(t,`predictions`,`logLoss`),s=null;n!=null&&(s=U(n,`weights`,`logLoss`)),k(a.shape,o.shape,`Error in logLoss: `);var c=G(1),l=G(r);return Ju(a.mul(o.add(l).log()).neg().sub(c.sub(a).mul(c.sub(o).add(l).log())),s,i)}}),$u=W({meanSquaredError_:function(e,t,n,r){r===void 0&&(r=Gu.SUM_BY_NONZERO_WEIGHTS);var i=U(e,`labels`,`meanSquaredError`),a=U(t,`predictions`,`meanSquaredError`),o=null;return n!=null&&(o=U(n,`weights`,`meanSquaredError`)),k(i.shape,a.shape,`Error in meanSquaredError: `),Ju(i.squaredDifference(a),o,r)}}),ed=W({sigmoidCrossEntropy_:function(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=Gu.SUM_BY_NONZERO_WEIGHTS);var a=U(e,`multiClassLabels`,`sigmoidCrossEntropy`),o=U(t,`logits`,`sigmoidCrossEntropy`),s=null;if(n!=null&&(s=U(n,`weights`,`sigmoidCrossEntropy`)),k(a.shape,o.shape,`Error in sigmoidCrossEntropy: `),r>0){var c=G(r),l=G(1),u=G(.5);a=a.mul(l.sub(c)).add(u.mul(c))}return Ju(function(e,t){var n=U(e,`labels`,`sigmoidCrossEntropyWithLogits`),r=U(t,`logits`,`sigmoidCrossEntropyWithLogits`);k(n.shape,r.shape,`Error in sigmoidCrossEntropyWithLogits: `);var i=r.relu(),a=r.mul(n),o=r.abs().neg().exp().log1p();return i.sub(a).add(o)}(a,o),s,i)}}),td=W({softmaxCrossEntropy_:function(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=Gu.SUM_BY_NONZERO_WEIGHTS);var a=U(e,`onehotLabels`,`softmaxCrossEntropy`),o=U(t,`logits`,`softmaxCrossEntropy`),s=null;if(n!=null&&(s=U(n,`weights`,`softmaxCrossEntropy`)),k(a.shape,o.shape,`Error in softmaxCrossEntropy: `),r>0){var c=G(r),l=G(1),u=G(a.shape[1]);a=a.mul(l.sub(c)).add(c.div(u))}return Ju(function(e,t,n){if(n===void 0&&(n=-1),n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank `+t.rank+` and dim was `+n);return ti((function(e,t,r){var i=t.logSumExp([n],!0),a=t.toFloat().sub(i);return r([e,a]),{value:a.mul(e).neg().sum([n]),gradFunc:function(e,t){var r=t[0],i=t[1],a=vn(e.shape,[n]);return[e.reshape(a).mul(r.toFloat().sub(i.exp())),e.reshape(a).mul(i.exp().sub(r.toFloat()))]}}}))(e,t)}(a,o),s,i)}}),nd=Object.freeze({get Reduction(){return Gu},absoluteDifference:qu,computeWeightedLoss:Ju,cosineDistance:Yu,hingeLoss:Xu,huberLoss:Zu,logLoss:Qu,meanSquaredError:$u,sigmoidCrossEntropy:ed,softmaxCrossEntropy:td});function rd(e,t){return t===void 0&&(t=!1),z.tidy((function(){if(e.shape.length!==2)throw Error(`qr2d() requires a 2D Tensor, but got a `+e.shape.length+`D Tensor.`);for(var n=e.shape[0],r=e.shape[1],i=gr(n),a=e.clone(),o=jn([[1]],[1,1]),s=o.clone(),c=n>=r?r:n,l=function(e){var t,c=a,l=s,u=i;t=z.tidy((function(){var t=a.slice([e,e],[n-e,1]),c=t.norm(),l=a.slice([e,e],[1,1]),u=jn([[-1]]).where(l.greater(0),jn([[1]])),d=l.sub(u.mul(c)),f=t.div(d);s=f.shape[0]===1?o.clone():o.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var p=u.matMul(d).div(c).neg(),m=a.slice([e,0],[n-e,r]),h=p.mul(s);if(e===0)a=m.sub(h.matMul(s.transpose().matMul(m)));else{var g=m.sub(h.matMul(s.transpose().matMul(m)));a=a.slice([0,0],[e,r]).concat(g,0)}var _=i.slice([0,e],[n,i.shape[1]-e]);if(e===0)i=_.sub(_.matMul(s).matMul(h.transpose()));else{var v=_.sub(_.matMul(s).matMul(h.transpose()));i=i.slice([0,0],[n,e]).concat(v,1)}return[s,a,i]})),s=t[0],a=t[1],i=t[2],ln([c,l,u])},u=0;u<c;++u)l(u);return!t&&n>r&&(i=i.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[i,a]}))}var id=W({bandPart_:function(e,t,n){if(t%1!=0)throw Error(`bandPart(): numLower must be an integer, got `+t+`.`);if(n%1!=0)throw Error(`bandPart(): numUpper must be an integer, got `+n+`.`);var r=U(e,`a`,`bandPart`);if(r.rank<2)throw Error(`bandPart(): Rank must be at least 2, got `+r.rank+`.`);var i=r.shape,a=r.shape.slice(-2),o=a[0],s=a[1];if(!(t<=o))throw Error(`bandPart(): numLower (`+t+`) must not be greater than the number of rows (`+o+`).`);if(!(n<=s))throw Error(`bandPart(): numUpper (`+n+`) must not be greater than the number of columns (`+s+`).`);t<0&&(t=o),n<0&&(n=s);var c=il(Vn(0,o,1,`int32`).reshape([-1,1]),Vn(0,s,1,`int32`)),l=Nc(c.lessEqual(G(+t,`int32`)),c.greaterEqual(G(-n,`int32`))),u=Rn([o,s],r.dtype);return jr(Pr(r.reshape([-1,o,s])).map((function(e){return Lc(l,e,u)}))).reshape(i)}}),ad=W({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,O(e!=null&&e.length>0,(function(){return`Gram-Schmidt process: input must not be null, undefined, or empty`}));for(var n=e[0].shape[0],r=function(t){O(e[t].shape[0]===n,(function(){return`Gram-Schmidt: Non-unique lengths found in the input vectors: (`+e[t].shape[0]+` vs. `+n+`)`}))},i=1;i<e.length;++i)r(i)}else t=!0,e=Yn(e,e.shape[0],0).map((function(e){return Ar(e,[0])}));O(e.length<=e[0].shape[0],(function(){return`Gram-Schmidt: Number of vectors (`+e.length+`) exceeds number of dimensions (`+e[0].shape[0]+`).`}));var a=[],o=e,s=function(e){a.push(z.tidy((function(){var t=o[e];if(e>0)for(var n=0;n<e;++n){var r=pu(a[n].mulStrict(t)).mul(a[n]);t=t.sub(r)}return t.div(Cu(t,`euclidean`))})))};for(i=0;i<e.length;++i)s(i);return t?jr(a,0):a}}),od=W({qr_:function(e,t){if(t===void 0&&(t=!1),e.rank<2)throw Error(`qr() requires input tensor to have a rank >= 2, but got rank `+e.rank);if(e.rank===2)return rd(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce((function(e,t){return e*t})),r=Pr(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],a=[];return r.forEach((function(e){var n=rd(e,t),r=n[0],o=n[1];i.push(r),a.push(o)})),[jr(i,0).reshape(e.shape),jr(a,0).reshape(e.shape)]}}),sd=Object.freeze({bandPart:id,gramSchmidt:ad,qr:od});function cd(e,t,n,r,i,a){r??=.5,i??=-1/0,a??=0;var o=e.shape[0];return n=Math.min(n,o),O(0<=r&&r<=1,(function(){return`iouThreshold must be in [0, 1], but was '`+r+`'`})),O(e.rank===2,(function(){return`boxes must be a 2D tensor, but was of rank '`+e.rank+`'`})),O(e.shape[1]===4,(function(){return`boxes must have 4 columns, but 2nd dimension was `+e.shape[1]})),O(t.rank===1,(function(){return`scores must be a 1D tensor`})),O(t.shape[0]===o,(function(){return`scores has incompatible shape with boxes. Expected `+o+`, but was `+t.shape[0]})),O(0<=a&&a<=1,(function(){return`softNmsSigma must be in [0, 1], but was '`+a+`'`})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i,softNmsSigma:a}}var ld=W({resizeBilinear_:function(e,t,n){n===void 0&&(n=!1);var r=U(e,`images`,`resizeBilinear`);O(r.rank===3||r.rank===4,(function(){return`Error in resizeBilinear: x must be rank 3 or 4, but got rank `+r.rank+`.`})),O(t.length===2,(function(){return`Error in resizeBilinear: new shape must 2D, but got shape `+t+`.`}));var i=r,a=!1;r.rank===3&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],c=z.runKernelFunc((function(e,t){return t([i]),e.resizeBilinear(i,o,s,n)}),{x:i},(function(e,t){return{x:function(){return z.runKernelFunc((function(r){return r.resizeBilinearBackprop(e,t[0],n)}),{})}}}),`ResizeBilinear`,{alignCorners:n,newHeight:o,newWidth:s});return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),ud=W({resizeNearestNeighbor_:function(e,t,n){n===void 0&&(n=!1);var r=U(e,`images`,`resizeNearestNeighbor`);O(r.rank===3||r.rank===4,(function(){return`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank `+r.rank+`.`})),O(t.length===2,(function(){return`Error in resizeNearestNeighbor: new shape must 2D, but got shape `+t+`.`})),O(r.dtype===`float32`||r.dtype===`int32`,(function(){return"`images` must have `int32` or `float32` as dtype"}));var i=r,a=!1;r.rank===3&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],c=z.runKernelFunc((function(e,t){return t([i]),e.resizeNearestNeighbor(i,o,s,n)}),{batchImages:i},(function(e,t){return{batchImages:function(){return z.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(e,t[0],n)}),{})}}}));return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),dd=W({nonMaxSuppression_:function(e,t,n,r,i){r===void 0&&(r=.5),i===void 0&&(i=-1/0);var a=U(e,`boxes`,`nonMaxSuppression`),o=U(t,`scores`,`nonMaxSuppression`),s=cd(a,o,n,r,i);n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold;var c={maxOutputSize:n,iouThreshold:r,scoreThreshold:i};return z.runKernelFunc((function(e){return e.nonMaxSuppression(a,o,n,r,i)}),{boxes:a,scores:o},null,`NonMaxSuppressionV3`,c)}}),fd=function(e,t,n,r,i){return r===void 0&&(r=.5),i===void 0&&(i=-1/0),u(this,void 0,void 0,(function(){var a,o,s,c,l,u,f;return d(this,(function(d){switch(d.label){case 0:return a=U(e,`boxes`,`nonMaxSuppressionAsync`),o=U(t,`scores`,`nonMaxSuppressionAsync`),s=cd(a,o,n,r,i),n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,[4,Promise.all([a.data(),o.data()])];case 1:return c=d.sent(),l=c[0],u=c[1],f=ki(l,u,n,r,i),a!==e&&a.dispose(),o!==t&&o.dispose(),[2,f]}}))}))},pd=W({nonMaxSuppressionWithScore_:function(e,t,n,r,i,a){r===void 0&&(r=.5),i===void 0&&(i=-1/0),a===void 0&&(a=0);var o=U(e,`boxes`,`nonMaxSuppression`),s=U(t,`scores`,`nonMaxSuppression`),c=cd(o,s,n,r,i,a),l={maxOutputSize:n=c.maxOutputSize,iouThreshold:r=c.iouThreshold,scoreThreshold:i=c.scoreThreshold,softNmsSigma:a=c.softNmsSigma},u=z.runKernel(`NonMaxSuppressionV5`,{boxes:o,scores:s},l);return{selectedIndices:u[0],selectedScores:u[1]}}}),md=function(e,t,n,r,i,a){return r===void 0&&(r=.5),i===void 0&&(i=-1/0),a===void 0&&(a=0),u(this,void 0,void 0,(function(){var o,s,c,l,u,f,p;return d(this,(function(d){switch(d.label){case 0:return o=U(e,`boxes`,`nonMaxSuppressionAsync`),s=U(t,`scores`,`nonMaxSuppressionAsync`),c=cd(o,s,n,r,i,a),n=c.maxOutputSize,r=c.iouThreshold,i=c.scoreThreshold,a=c.softNmsSigma,[4,Promise.all([o.data(),s.data()])];case 1:return l=d.sent(),u=l[0],f=l[1],p=Ai(u,f,n,r,i,a),o!==e&&o.dispose(),s!==t&&s.dispose(),[2,p]}}))}))},hd=W({cropAndResize_:function(e,t,n,r,i,a){var o=U(e,`image`,`cropAndResize`),s=U(t,`boxes`,`cropAndResize`,`float32`),c=U(n,`boxInd`,`cropAndResize`,`int32`);i||=`bilinear`,a||=0;var l=s.shape[0];return O(o.rank===4,(function(){return`Error in cropAndResize: image must be rank 4,but got rank `+o.rank+`.`})),O(s.rank===2&&s.shape[1]===4,(function(){return`Error in cropAndResize: boxes must be have size [`+l+`,4] but had shape `+s.shape+`.`})),O(c.rank===1&&c.shape[0]===l,(function(){return`Error in cropAndResize: boxInd must be have size [`+l+`] but had shape `+s.shape+`.`})),O(r.length===2,(function(){return`Error in cropAndResize: cropSize must be of length 2, but got length `+r.length+`.`})),O(r[0]>=1&&r[1]>=1,(function(){return`cropSize must be atleast [1,1], but was `+r})),O(i===`bilinear`||i===`nearest`,(function(){return`method must be bilinear or nearest, but was `+i})),z.runKernelFunc((function(e,t){return e.cropAndResize(o,s,c,r,i,a)}),{images:o,boxes:s,boxInd:c},null,`CropAndResize`,{method:i,extrapolationValue:a,cropSize:r})}}),gd=Object.freeze({resizeBilinear:ld,resizeNearestNeighbor:ud,nonMaxSuppression:dd,nonMaxSuppressionAsync:fd,nonMaxSuppressionWithScore:pd,nonMaxSuppressionWithScoreAsync:md,cropAndResize:hd}),_d=function(e,t){return!(e>0)||t===`linear`},vd=function(e,t,n){if(n==null||n===`linear`)return e;if(n===`relu`)return e.mul(t.step());throw Error(`Gradient for activation `+n+` has not been implemented yet.`)},yd=function(e,t){var n=t,r=si(e.shape,t.shape);return r.length>0&&(n=n.sum(r)),n.reshape(e.shape)},bd=function(e,t,n){if(t===`linear`)return e;if(t===`relu`)return vu(e);if(t===`elu`)return hu(e);if(t===`relu6`)return yu(e);if(t===`prelu`)return _u(e,n);throw Error(`Unknown fused activation `+t+`.`)},xd=W({fusedMatMul_:function(e){var t,n=e.a,r=e.b,i=e.transposeA,a=i!==void 0&&i,o=e.transposeB,s=o!==void 0&&o,c=e.bias,l=e.activation,u=l===void 0?`linear`:l,d=e.preluActivationWeights;if(!1===_d(z.state.gradientDepth,u)){var f=Ll(n,r,a,s);return c!=null&&(f=zc(f,c)),bd(f,u,d)}var p=U(n,`a`,`fused matMul`),m=U(r,`b`,`fused matMul`);t=Ze(p,m),p=t[0],m=t[1];var h=a?p.shape[p.rank-2]:p.shape[p.rank-1],g=s?m.shape[m.rank-1]:m.shape[m.rank-2],_=a?p.shape[p.rank-1]:p.shape[p.rank-2],v=s?m.shape[m.rank-2]:m.shape[m.rank-1],y=p.shape.slice(0,-2),b=m.shape.slice(0,-2),x=M(y),S=M(b);O(p.rank>=2&&m.rank>=2&&p.rank===m.rank,(function(){return`Error in fused matMul: inputs must have the same rank of at least 2, got ranks `+p.rank+` and `+m.rank+`.`})),O(N(y,b),(function(){return`Error in fused matMul: outer dimensions (`+y+`) and (`+b+`) of Tensors with shapes `+p.shape+` and `+m.shape+` must match.`})),O(h===g,(function(){return`Error in fused matMul: inner shapes (`+h+`) and (`+g+`) of Tensors with shapes `+p.shape+` and `+m.shape+` and transposeA=`+a+` and transposeB=`+s+` must match.`}));var C,w,T=p.shape.slice(0,-2).concat([_,v]),E=a?p.as3D(x,h,_):p.as3D(x,_,h),D=s?m.as3D(S,v,g):m.as3D(S,g,v);c!=null&&J(T,(C=Ze(C=U(c,`bias`,`fused matMul`),p)[0]).shape),d!=null&&(w=U(d,`prelu weights`,`fused matMul`));var k={a:E,b:D};c!=null&&(k.bias=C),d!=null&&(k.preluActivationWeights=w);var A=[E,D];return z.runKernelFunc((function(e,t){var n=e.fusedBatchMatMul({a:E,b:D,transposeA:a,transposeB:s,bias:C,activation:u,preluActivationWeights:w});return t([E,D,n]),n}),k,(function(e,t){var n=t[0],r=t[1],i=t[2],o=vd(e,i,u),l={};return c!=null&&(l={bias:function(){return yd(C,o)}}),Object.assign(a||s?!a&&s?{a:function(){return o.matMul(r,!1,!1)},b:function(){return o.matMul(n,!0,!1)}}:a&&!s?{a:function(){return r.matMul(o,!1,!0)},b:function(){return n.matMul(o,!1,!1)}}:{a:function(){return r.matMul(o,!0,!0)},b:function(){return o.matMul(n,!0,!0)}}:{a:function(){return o.matMul(r,!1,!0)},b:function(){return n.matMul(o,!0,!1)}},l)}),`_FusedMatMul`,{transposeA:a,transposeB:s,activation:u},A,[!0]).reshape(T)}}),Sd=W({fusedConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,a=e.dataFormat,o=a===void 0?`NHWC`:a,s=e.dilations,c=s===void 0?[1,1]:s,l=e.dimRoundingMode,u=e.bias,d=e.activation,f=d===void 0?`linear`:d,p=e.preluActivationWeights;if(f||=`linear`,!1===_d(z.state.gradientDepth,f)){var m=Dl(t,n,r,i,o,c,l);return u!=null&&(m=zc(m,u)),bd(m,f,p)}var h=U(t,`x`,`conv2d`),g=U(n,`filter`,`conv2d`),_=h,v=!1;h.rank===3&&(v=!0,_=h.as4D(1,h.shape[0],h.shape[1],h.shape[2])),O(_.rank===4,(function(){return`Error in fused conv2d: input must be rank 4, but got rank `+_.rank+`.`})),O(g.rank===4,(function(){return`Error in fused conv2d: filter must be rank 4, but got rank `+g.rank+`.`})),l!=null&&O(P(i),(function(){return`Error in fused conv2d: pad must be an integer when using, dimRoundingMode `+l+` but got pad `+i+`.`})),O(_.shape[3]===g.shape[2],(function(){return`Error in conv2d: depth of input (`+_.shape[3]+`) must match input depth for filter `+g.shape[2]+`.`})),O(vi(r,c),(function(){return`Error in conv2D: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+c+`'`})),O(o===`NHWC`,(function(){return`Error in conv2d: got dataFormat of `+o+` but only NHWC is currently supported.`}));var y,b,x=ui(_.shape,g.shape,r,c,i,l);u!=null&&(y=Ze(y=U(u,`bias`,`fused conv2d`),h)[0],J(x.outShape,y.shape)),p!=null&&(b=U(p,`prelu weights`,`fused conv2d`));var S={x:_,filter:g};u!=null&&(S.bias=y),p!=null&&(S.preluActivationWeights=b);var C=[g,_],w=z.runKernelFunc((function(e,t){var n=e.fusedConv2d({input:_,filter:g,convInfo:x,bias:y,activation:f,preluActivationWeights:b});return t([g,_,n]),n}),S,(function(e,t){var n=t,a=n[0],o=n[1],s=n[2],l=vd(e,s,f);O(_i(c),(function(){return`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+c+`'`}));var d={};return u!=null&&(d={bias:function(){return yd(y,l)}}),Object.assign({x:function(){return Al(o.shape,l,a,r,i)},filter:function(){return kl(o,l,a.shape,r,i)}},d)}),`FusedConv2D`,{convInfo:x,activation:f},C,[!0]);return v?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),Cd=W({fusedDepthwiseConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,a=e.dataFormat,o=a===void 0?`NHWC`:a,s=e.dilations,c=s===void 0?[1,1]:s,l=e.dimRoundingMode,u=e.bias,d=e.activation,f=d===void 0?`linear`:d,p=e.preluActivationWeights;if(!1===_d(z.state.gradientDepth,f)){var m=jl(t,n,r,i,o,c,l);return u!=null&&(m=zc(m,u)),bd(m,f,p)}var h=U(t,`x`,`depthwiseConv2d`),g=U(n,`filter`,`depthwiseConv2d`),_=h,v=!1;h.rank===3&&(v=!0,_=h.as4D(1,h.shape[0],h.shape[1],h.shape[2])),O(_.rank===4,(function(){return`Error in fused depthwiseConv2d: input must be rank 4, but got rank `+_.rank+`.`})),O(g.rank===4,(function(){return`Error in fused depthwiseConv2d: filter must be rank 4, but got rank `+g.rank+`.`})),O(_.shape[3]===g.shape[2],(function(){return`Error in fused depthwiseConv2d: number of input channels (`+_.shape[3]+`) must match the inChannels dimension in filter `+g.shape[2]+`.`})),c??=[1,1],O(vi(r,c),(function(){return`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+c+`'`})),l!=null&&O(P(i),(function(){return`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode `+l+` but got pad `+i+`.`}));var y,b,x=ui(_.shape,g.shape,r,c,i,l,!0);u!=null&&(y=Ze(y=U(u,`bias`,`fused conv2d`),h)[0],J(x.outShape,y.shape)),p!=null&&(b=U(p,`prelu weights`,`fused depthwiseConv2d`));var S={x:_,filter:g};u!=null&&(S.bias=y),p!=null&&(S.preluActivationWeights=b);var C=[g,_],w=z.runKernelFunc((function(e,t){var n=e.fusedDepthwiseConv2D({input:_,filter:g,convInfo:x,bias:y,activation:f,preluActivationWeights:b});return t([g,_,n]),n}),S,(function(e,t){O(_i(c),(function(){return`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '`+c+`'`}));var n=t[0],r=t[1],i=t[2],a=vd(e,i,f),o={};return u!=null&&(o={bias:function(){return yd(y,a)}}),Object.assign({x:function(){return Ml(r.shape,a,n,x)},filter:function(){return Nl(r,a,n.shape,x)}},o)}),`FusedDepthwiseConv2D`,{convInfo:x,activation:f},C,[!0]);return v?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),wd=Object.freeze({matMul:xd,conv2d:Sd,depthwiseConv2d:Cd}),Td=Object.freeze({image:gd,linalg:sd,losses:nd,spectral:Pu,fused:wd,signal:Wu,square:Is,squaredDifference:Rs,conv1d:El,conv2d:Dl,conv3d:Ol,depthwiseConv2d:jl,separableConv2d:Pl,conv2dTranspose:Fl,conv3dTranspose:Il,op:W,batchNormalization2d:Tc,batchNormalization3d:Ec,batchNormalization4d:Dc,batchNormalization:Oc,batchNorm:kc,batchNorm2d:Ac,batchNorm3d:jc,batchNorm4d:Mc,booleanMaskAsync:Sl,complex:Tn,real:En,imag:Dn,concat:Wn,concat1d:Gn,concat2d:Kn,concat3d:qn,concat4d:Jn,split:Yn,matMul:Ll,dot:Rl,outerProduct:zl,reverse:Bl,reverse1d:Vl,reverse2d:Hl,reverse3d:Ul,reverse4d:Wl,maxPool:ql,avgPool:Jl,pool:Yl,maxPool3d:Xl,avgPool3d:Zl,slice:Ql,slice1d:$l,slice2d:eu,slice3d:tu,slice4d:nu,abs:zs,acos:Bs,acosh:Vs,asin:Hs,asinh:Us,atan:Ws,atanh:Gs,ceil:Ks,clipByValue:qs,cos:Js,cosh:Ys,erf:Xs,exp:Zs,expm1:Qs,floor:$s,log:ec,log1p:tc,logSigmoid:nc,neg:rc,reciprocal:ic,round:ac,rsqrt:oc,sigmoid:sc,sign:cc,isNaN:lc,isInf:uc,isFinite:dc,sin:fc,sinh:pc,softplus:mc,sqrt:hc,step:gc,tan:_c,tanh:vc,all:iu,any:au,argMax:ou,argMin:su,logSumExp:cu,max:lu,mean:uu,min:du,moments:fu,sum:pu,prod:mu,equal:ol,equalStrict:sl,greater:cl,greaterEqual:ll,greaterEqualStrict:ul,greaterStrict:dl,less:fl,lessEqual:pl,lessEqualStrict:ml,lessStrict:hl,notEqual:gl,notEqualStrict:_l,add:zc,addN:Bc,addStrict:Vc,atan2:Hc,div:Uc,divNoNan:Wc,divStrict:Gc,floorDiv:Kc,maximum:qc,maximumStrict:Jc,minimum:Yc,minimumStrict:Xc,mod:Zc,modStrict:Qc,mul:$c,mulStrict:el,pow:tl,powStrict:nl,squaredDifferenceStrict:rl,sub:il,subStrict:al,elu:hu,leakyRelu:gu,prelu:_u,relu:vu,relu6:yu,selu:bu,logicalAnd:Nc,logicalNot:Pc,logicalOr:Fc,logicalXor:Ic,where:Lc,whereAsync:Rc,buffer:K,print:cr,batchToSpaceND:lr,broadcastTo:ur,cast:dr,clone:fr,cumsum:pr,depthToSpace:mr,expandDims:hr,eye:gr,multinomial:_r,oneHot:vr,pad:yr,pad1d:br,pad2d:xr,pad3d:Sr,pad4d:Cr,rand:wr,randomNormal:Tr,randomGamma:Er,randomUniform:Dr,reshape:Or,spaceToBatchND:kr,squeeze:Ar,stack:jr,tile:Mr,truncatedNormal:Nr,unstack:Pr,setdiff1dAsync:Fr,fill:zn,linspace:Bn,ones:Ln,range:Vn,scalar:G,tensor:On,tensor1d:An,tensor2d:jn,tensor3d:Mn,tensor4d:Nn,tensor5d:Pn,tensor6d:Fn,variable:In,zeros:Rn,onesLike:Hn,zerosLike:Un,transpose:xu,softmax:ni,logSoftmax:ri,localResponseNormalization:Su,norm:Cu,gather:bl,unsortedSegmentSum:xl,basicLSTMCell:wu,multiRNNCell:Tu,movingAverage:Eu,stridedSlice:Du,topk:Ou,scatterND:ku,fft:Au,ifft:ju,rfft:Mu,irfft:Nu,sparseToDense:Fu,gatherND:Iu,diag:Lu,dropout:Ru,hannWindow:Bu,hammingWindow:Vu,frame:Hu,stft:Uu,inTopKAsync:Ku});function X(e,t){Array.isArray(e)||(e=[e]),e.forEach((function(e){e!=null&&O(e.dtype!==`complex64`,(function(){return t+` does not support complex64 tensors.`}))}))}function Ed(e,t,n,r){if(n===`linear`)return e.linear(t);if(n===`relu`)return e.relu(t);if(n===`elu`)return e.elu(t);if(n===`relu6`)return e.relu6(t);if(n===`prelu`)return e.prelu(t,r);throw Error(`Activation `+n+` has not been implemented for the CPU backend.`)}var Dd=function(e){function t(){var t=e.call(this)||this;return t.blockSize=48,t.firstUse=!0,t.data=new ii(t,z),t}return l(t,e),t.prototype.write=function(e,t,n){this.firstUse&&(this.firstUse=!1,m().get(`IS_NODE`)&&dn(`
|
|
3739
|
+
`}(t));return this.compileAndRun(n,[e])},t.prototype.conv2dByMatMul=function(e,t,n,r,i,a){var o=e.shape,s=this.texData.get(e.dataId),c=n.inChannels,l=o[0]*o[1]*o[2],u=n.outChannels,d=n.dataFormat===`channelsLast`,f=(l===1||u===1)&&c>1e3,p=o[2]%2!=0&&!!s.isPacked;if(f||!O().getBool(`WEBGL_LAZILY_UNPACK`)||!O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)||!p){var m=d?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],h=this.reshape(e,[1,m,n.inChannels]),g=this.reshape(t,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:h,b:g,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),n.outShape)}var _=d?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),v={dataId:e.dataId,shape:[1,_,n.inChannels],dtype:e.dtype},y=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,I(ln(s.shape,v.shape),(function(){return`packed reshape `+s.shape+` to `+v.shape+` isn't free`}));var b=this.reshape(t,[1,n.inChannels,n.outChannels]),x=this.fusedBatchMatMul({a:v,b,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),S=this.texData.get(x.dataId);return I(S.isPacked,(function(){return`batchMatMul result is expected to be packed`})),s.shape=y,S.shape=n.outShape,V.makeTensorFromDataId(x.dataId,n.outShape,x.dtype)},t.prototype.conv2dWithIm2Row=function(e,t,n,r,i,a){var o=n.filterWidth,s=n.filterHeight,c=n.inChannels,l=n.outWidth,u=n.outHeight,d=n.dataFormat===`channelsLast`,f=o*s*c,p=u*l,m=[f,p],h=e.squeeze([0]),g=t.reshape([1,f,-1]),_=new Po(m,h.shape,n),v=this.compileAndRun(_,[h]).reshape([1,m[0],m[1]]),y=r!=null,b=a!=null,x=i?qs(i,!0):null,S=new Bo(v.shape,[1,p,n.outChannels],!0,!1,y,x,b),C=[v,g];r&&C.push(r),b&&C.push(a);var w=this.compileAndRun(S,C);return d?w.reshape([1,u,l,n.outChannels]):w.reshape([1,n.outChannels,u,l])},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights;if(r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type===`SAME`||r.padInfo.type===`VALID`))return this.conv2dByMatMul(t,n,r,i,a,o);if(O().getBool(`WEBGL_CONV_IM2COL`)&&t.shape[0]===1)return this.conv2dWithIm2Row(t,n,r,i,a,o);var s=i!=null,c=o!=null,l=new Ka(r,s,a?qs(a,!1):null,c),u=[t,n];return i&&u.push(i),o&&u.push(o),this.compileAndRun(l,u)},t.prototype.conv2d=function(e,t,n){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type===`SAME`||n.padInfo.type===`VALID`))return this.conv2dByMatMul(e,t,n);if(O().getBool(`WEBGL_CONV_IM2COL`)&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);var r=new Ka(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerInput=function(e,t,n){var r=new Va(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerFilter=function(e,t,n){var r=new Ba(n);return this.compileAndRun(r,[e,t])},t.prototype.fusedDepthwiseConv2D=function(e){var t,n=e.input,r=e.filter,i=e.convInfo,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=O().getBool(`WEBGL_PACK_DEPTHWISECONV`)&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,l=o?qs(o,c):null,u=[n,r],d=a!=null,f=s!=null;return d&&u.push(a),f&&u.push(s),c?(t=new Ya(i,d,l,f),this.compileAndRun(t,u)):(t=new Ja(i,d,l,f),this.compileAndRun(t,u))},t.prototype.depthwiseConv2D=function(e,t,n){var r;return O().getBool(`WEBGL_PACK_DEPTHWISECONV`)&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Ya(n),this.compileAndRun(r,[e,t])):(r=new Ja(n),this.compileAndRun(r,[e,t]))},t.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new Ga(n);return this.compileAndRun(r,[e,t])},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new Wa(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3d=function(e,t,n){var r=new qa(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerInput=function(e,t,n){var r=new Ua(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerFilter=function(e,t,n){var r=new Ha(n);return this.compileAndRun(r,[e,t])},t.prototype.maxPool=function(e,t){var n=new Ko(t,`max`,!1);return this.compileAndRun(n,[e])},t.prototype.avgPool=function(e,t){var n=new Ko(t,`avg`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.maxPoolBackprop=function(e,t,n,r){var i=new Ko(r,`max`,!0),a=this.compileAndRun(i,[t]),o=new Ro(r),s=this.compileAndRun(o,[e,a],t.dtype);return a.dispose(),s},t.prototype.avgPoolBackprop=function(e,t,n){var r=new ba(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.cast=function(e,t){return Ni(e,t,this)},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=Array(e.rank-1),i=0,a=0;a<e.rank;a++)a!==t&&(r[i++]=e.shape[a]);var o=Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=Array(n);for(a=0;a<c.length;a++)o[t]=a,c[a]=this.slice(e,o,s).reshape(r);return c},t.prototype.avgPool3d=function(e,t){var n=new qo(t,`avg`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.avgPool3dBackprop=function(e,t,n){var r=new xa(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.maxPool3d=function(e,t){var n=new qo(t,`max`,!1);return this.compileAndRun(n,[e],`float32`)},t.prototype.maxPool3dBackprop=function(e,t,n,r){var i=new qo(r,`max`,!0),a=this.compileAndRun(i,[t]),o=new zo(r),s=this.compileAndRun(o,[e,a],t.dtype);return a.dispose(),s},t.prototype.reshape=function(e,t){var n=this.texData.get(e.dataId);if(n.isPacked&&!ln(e.shape,t)&&(n.texture===null||!ln(n.shape,t))){var r=this.packedReshape(e,t);return V.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Pi(e,t)},t.prototype.resizeBilinear=function(e,t,n,r){var i=O().getBool(`WEBGL_PACK_IMAGE_OPERATIONS`)?new Qo(e.shape,t,n,r):new Zo(e.shape,t,n,r);return this.compileAndRun(i,[e],`float32`)},t.prototype.resizeBilinearBackprop=function(e,t,n){var r=new Xo(e,t,n);return this.compileAndRun(r,[e])},t.prototype.resizeNearestNeighbor=function(e,t,n,r){var i=new es(e.shape,t,n,r);return this.compileAndRun(i,[e])},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new $o(e,t,n);return this.compileAndRun(r,[e])},t.prototype.multinomial=function(e,t,n,r){var i=t?e:mi(e),a=i.shape[0],o=i.shape[1],s=new Vo(a,o,n),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],`int32`,c)},t.prototype.oneHot=function(e,t,n,r){var i=new Ho(e.size,t,n,r);return this.compileAndRun(i,[e])},t.prototype.diag=function(e){var t=new no(e.size);return this.compileAndRun(t,[e])},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return Cn(`tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead`),Hi(e.dataSync(),t.dataSync(),n,r,i)},t.prototype.cropAndResize=function(e,t,n,r,i,a){var o=new Xa(e.shape,t.shape,r,i,a);return this.compileAndRun(o,[e,t,n],`float32`)},t.prototype.depthToSpace=function(e,t,n){I(t>1,(function(){return`blockSize should be > 1 for depthToSpace, but was: `+t}));var r=e.shape[0],i=n===`NHWC`?e.shape[1]:e.shape[2],a=n===`NHWC`?e.shape[2]:e.shape[3],o=n===`NHWC`?e.shape[3]:e.shape[1],s=i*t,c=a*t,l=o/(t*t),u=new to(n===`NHWC`?[r,s,c,l]:[r,l,s,c],t,n);return this.compileAndRun(u,[e])},t.prototype.split=function(e,t,n){return Ji(e,t,n)},t.prototype.scatterND=function(e,t,n){var r=ii(0,e,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,c=r.outputSize,l=[c/o,o],u=e.reshape([a,i]),d=t.reshape([a,o]);if(c===0)return Pi(Bn([]),n);var f=q(0),p=new rs(a,i,u.rank,d.rank,s,l);return this.compileAndRun(p,[d,u,f]).reshape(n)},t.prototype.sparseToDense=function(e,t,n,r){var i=ii(0,e,n),a=i.sliceRank,o=i.numUpdates,s=i.strides,c=i.outputSize,l=new rs(o,a,e.rank,t.rank,s,[c,1],!1);return this.compileAndRun(l,[t,e,r]).reshape(n)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,t){var n=this.texData.get(e.dataId),r=new lo(so,e.shape,t),i=new lo(co,e.shape,t),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)],o=this.compileAndRun(r,a),s=this.compileAndRun(i,a),c=this.complex(o,s).as2D(e.shape[0],e.shape[1]);return o.dispose(),s.dispose(),c},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=$r(e,t),a=i[0],o=i[1],s=i[2],c=i[3],l=t.reshape([o,r]),u=e.reshape([e.size/s,s]),d=new po(r,c,[o,s]);return this.compileAndRun(d,[u,l]).reshape(a)},t.prototype.fill=function(e,t,n){if((n||=De(t))===`string`){var r=_e(n,R(e));return r.fill(t),V.makeTensor(r,e,n,this)}var i=new uo(e,t),a=i.getCustomSetupFunc(t);return this.compileAndRun(i,[],n,a)},t.prototype.onesLike=function(e){if(e.dtype===`string`)throw Error(`onesLike is not supported under string dtype`);return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype===`string`?``:0,e.dtype)},t.prototype.linspace=function(e,t,n){return Fi(e,t,n)},t.prototype.makeTensorInfo=function(e,t){var n=this.write(null,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}},t.prototype.makeOutput=function(e,t){var n=this.makeTensorInfo(e,t).dataId;return V.makeTensorFromDataId(n,e,t,this)},t.prototype.unpackTensor=function(e){var t=new Gs(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},t.prototype.packTensor=function(e){var t=new Uo(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,t){var n=[rn(e.shape)].concat(an(e.shape)),r={dtype:e.dtype,shape:n,dataId:e.dataId},i=new Yo([rn(t)].concat(an(t)),n),a=this.runWebGLProgram(i,[r],e.dtype,null,!0);return{dataId:a.dataId,shape:t,dtype:a.dtype}},t.prototype.decode=function(e){var t,n=this.texData.get(e),r=n.isPacked,i=n.shape,a=n.dtype,o=on(i);return t=r?new eo(o):new $a(o),{dtype:a,shape:i,dataId:this.runWebGLProgram(t,[{shape:o,dtype:a,dataId:e}],a,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,t,n,r,i){var a=this;i===void 0&&(i=!1);var o=this.makeTensorInfo(e.outputShape,n),s=this.texData.get(o.dataId);if(e.packedOutput&&(s.isPacked=!0),e.outPackingScheme===_t.DENSE&&(s.texShape=Tt(e.outputShape).map((function(e){return 2*e}))),e.outTexUsage!=null&&(s.usage=e.outTexUsage),R(o.shape)===0)return s.values=ge(o.dtype,0),o;var c=[],l=t.map((function(t){if(t.dtype===`complex64`)throw Error(`GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.`);var n=a.texData.get(t.dataId);if(n.texture==null){if(!e.packedInputs&&R(t.shape)<=O().getNumber(`WEBGL_SIZE_UPLOAD_UNIFORM`))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}else if(!!n.isPacked!=!!e.packedInputs)t=n.isPacked?a.unpackTensor(t):a.packTensor(t),c.push(t),n=a.texData.get(t.dataId);else if(n.isPacked&&!ln(n.shape,t.shape)){var r=t,i=t.shape;t.shape=n.shape,t=a.packedReshape(t,i),c.push(t),n=a.texData.get(t.dataId),r.shape=i}return a.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);var u,d={shape:o.shape,texData:s,isUniform:!1},f=function(e,t,n){var r=``;t.concat(n).forEach((function(e){var t=e.texData!=null&&e.texData.slice!=null&&e.texData.slice.flatOffset>0,n=e.isUniform?`uniform`:e.texData.texShape;r+=e.shape+`_`+n+`_`+t}));var i=e.userCode,a=e.constructor.name;return a+=`_`+r+`_`+i}(e,l,d),p=this.getAndSaveBinary(f,(function(){return function(e,t,n,r){var i=t.userCode,a=n.map((function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return e.texData!=null&&e.texData.slice!=null&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),o=a.map((function(e){return e.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=sa(a,s,i,t.packedInputs),l=e.createProgram(c),u=null,d=e.getUniformLocation(l,`NAN`,!1);O().getNumber(`WEBGL_VERSION`)===1&&(u=e.getUniformLocation(l,`INFINITY`,!1));for(var f={},p=0;p<t.variableNames.length;p++){var m=t.variableNames[p];f[m]=e.getUniformLocation(l,m,!1),f[`offset`+m]=e.getUniformLocation(l,`offset`+m,!1)}return{program:t,source:c,webGLProgram:l,uniformLocations:f,inShapeInfos:o,outShapeInfo:s,infLoc:u,nanLoc:d}}(a.gpgpu,e,l,d)})),m=this.activeTimers!=null;if(m&&(u=this.startTimer()),function(e,t,n,r,i){No(t.inShapeInfos,n),No([t.outShapeInfo],[r]);var a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),O().getNumber(`WEBGL_VERSION`)===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((function(n,r){var i=t.program.variableNames[r],a=t.uniformLocations[i],o=t.uniformLocations[`offset`+i];if(a!=null)if(n.isUniform)if(R(n.shape)<2)e.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),e.gl.uniform1fv(a,s)}else n.texData.slice!=null&&o!=null&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture,a,r)})),i?.(e,t.webGLProgram),e.executeProgram()}(this.gpgpu,p,l,d,r),c.forEach((function(e){return a.disposeData(e.dataId)})),m&&(u=this.endTimer(u),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(u)})),!O().getBool(`WEBGL_LAZILY_UNPACK`)&&s.isPacked&&!1===i){var h=this.unpackTensor(o);return this.disposeData(o.dataId),h}return o},t.prototype.compileAndRun=function(e,t,n,r,i){i===void 0&&(i=!1),n||=t[0].dtype;var a=this.runWebGLProgram(e,t,n,r,i);return V.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},t.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;this.disposed||=(O().getBool(`IS_TEST`)||Object.keys(this.binaryCache).forEach((function(t){e.gpgpu.deleteProgram(e.binaryCache[t].webGLProgram),delete e.binaryCache[t]})),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<`u`&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),!0)},t.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue??=W((function(){if(!O().get(`WEBGL_RENDER_FLOAT32_ENABLED`)){var t=O().getBool(`DEBUG`);O().set(`DEBUG`,!1);var n=e.abs(q(1e-8)).dataSync()[0];if(O().set(`DEBUG`,t),n>0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,a=n.values,o=n.texture,s=n.usage,c=n.isPacked;if(o==null){var l,u=this.activeTimers!=null;u&&(l=Fe());var d=n.texShape;if(d??(d=sn(r,c),n.texShape=d),a!=null){var f=on(r),p=void 0,m=d[1],h=d[0],g=a instanceof Uint8Array;c?(m=(t=Et(d[0],d[1]))[0],h=t[1],p=new oo(f,[h,m],g)):p=new ao(f,[h,m],g);var _=this.makeTensorInfo([h,m],i);this.texData.get(_.dataId).usage=g?vt.PIXELS:vt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(_.dataId),m,h,a);var v=this.runWebGLProgram(p,[_],i,null,!0),y=this.texData.get(v.dataId);n.texture=y.texture,n.texShape=y.texShape,n.isPacked=y.isPacked,n.usage=y.usage,this.disposeData(_.dataId),this.texData.delete(v.dataId),n.values=null,u&&(this.uploadWaitMs+=Fe()-l)}else n.texture=this.acquireTexture(d,s,i,c)}},t.prototype.convertAndCacheOnCPU=function(e,t){var n=this.texData.get(e),r=n.dtype;return this.releaseGPUData(e),t!=null&&(n.values=function(e,t){if(t===`float32`||t===`complex64`)return e;if(t===`int32`||t===`bool`){for(var n=t===`int32`?new Int32Array(e.length):new Uint8Array(e.length),r=0;r<n.length;++r)n[r]=Math.round(e[r]);return n}throw Error(`Unknown dtype `+t)}(t,r)),n.values},t.prototype.acquireTexture=function(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: `+i+` MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)},t.prototype.computeBytes=function(e,t){return e[0]*e[1]*Se(t)},t}(_i);ht()&&V.registerBackend(`webgl`,(function(){return new Ys}),2);var Xs=K({square_:function(e){var t=G(e,`x`,`square`),n=[t];return V.runKernelFunc((function(e,n){return n([t]),e.square(t)}),{x:t},null,`Square`,{},n,[])}}),Zs=`SquaredDifference`,Qs=K({squaredDifference_:function(e,t){var n,r=G(e,`a`,`squaredDifference`),i=G(t,`b`,`squaredDifference`);n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape);var a={a:r,b:i},o=[r,i];return V.runKernelFunc((function(e,t){var n=e.squaredDifference(r,i);return t([r,i]),n}),a,(function(e,t){var n=t[0],r=t[1],i=q(2);return{a:function(){return e.mul(n.sub(r).mul(i))},b:function(){return e.mul(r.sub(n).mul(i))}}}),Zs,{},o,[])}}),$s=K({abs_:function(e){var t=G(e,`x`,`abs`);return t.dtype===`complex64`?V.runKernelFunc((function(e){return e.complexAbs(t)}),{$x:t}):V.runKernelFunc((function(e,n){var r=e.abs(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().step(-1))}}}),`Abs`)}}),ec=K({acos_:function(e){var t=G(e,`x`,`acos`);return V.runKernelFunc((function(e,n){var r=e.acos(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(q(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),tc=K({acosh_:function(e){var t=G(e,`x`,`acosh`);return V.runKernelFunc((function(e,n){var r=e.acosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(n.toFloat().square().sub(1).sqrt())}}}))}}),nc=K({asin_:function(e){var t=G(e,`x`,`asin`);return V.runKernelFunc((function(e,n){var r=e.asin(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(q(1).sub(n.toFloat().square()).sqrt())}}}))}}),rc=K({asinh_:function(e){var t=G(e,`x`,`asinh`);return V.runKernelFunc((function(e,n){var r=e.asinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(q(1).add(n.toFloat().square()).sqrt())}}}))}}),ic=K({atan_:function(e){var t=G(e,`x`,`atan`);return V.runKernelFunc((function(e,n){var r=e.atan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().square().add(1))}}}))}}),ac=K({atanh_:function(e){var t=G(e,`x`,`atanh`);return V.runKernelFunc((function(e,n){var r=e.atanh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(q(1).sub(n.toFloat().square()))}}}))}}),oc=K({ceil_:function(e){var t=G(e,`x`,`ceil`);return V.runKernelFunc((function(e){return e.ceil(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),sc=K({clipByValue_:function(e,t,n){var r=G(e,`x`,`clipByValue`);I(t<=n,(function(){return`Error in clip: min (`+t+`) must be less than or equal to max (`+n+`).`}));var i=[r],a={min:t,max:n};return V.runKernelFunc((function(e,i){var a=e.clip(r,t,n);return i([r]),a}),{x:r},(function(e,r){var i=r[0];return{x:function(){return e.where(i.greaterEqual(t).logicalAnd(i.lessEqual(n)),tr(e))}}}),`ClipByValue`,a,i)}}),cc=K({cos_:function(e){var t=G(e,`x`,`cos`),n=[t];return V.runKernelFunc((function(e,n){var r=e.cos(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().sin().neg().mul(e)}}}),`Cos`,{},n)}}),lc=K({cosh_:function(e){var t=G(e,`x`,`cosh`);return V.runKernelFunc((function(e,n){var r=e.cosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().sinh().mulStrict(e)}}}))}}),uc=K({erf_:function(e){var t=G(e,`x`,`erf`);return I(t.dtype===`int32`||t.dtype===`float32`,(function(){return"Input dtype must be `int32` or `float32`."})),t.dtype===`int32`&&(t=t.toFloat()),V.runKernelFunc((function(e,n){var r=e.erf(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),dc=K({exp_:function(e){var t=G(e,`x`,`exp`);return V.runKernelFunc((function(e,n){var r=e.exp(t);return n([r]),r}),{x:t},(function(e,t){return{x:function(){return e.mulStrict(t[0])}}}),`Exp`,{},[],[!0])}}),fc=K({expm1_:function(e){var t=G(e,`x`,`expm1`);return V.runKernelFunc((function(e,n){var r=e.expm1(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.exp())}}}))}}),pc=K({floor_:function(e){var t=G(e,`x`,`floor`);return V.runKernelFunc((function(e){return e.floor(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),mc=K({log_:function(e){var t=G(e,`x`,`log`),n=[t];return V.runKernelFunc((function(e,n){var r=e.log(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.toFloat())}}}),`Log`,{},n)}}),hc=K({log1p_:function(e){var t=G(e,`x`,`log1p`);return V.runKernelFunc((function(e,n){var r=e.log1p(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.add(1))}}}))}}),gc=K({logSigmoid_:function(e){var t=G(e,`x`,`logSigmoid`);return V.runKernelFunc((function(e,n){var r=e.softplus(t.neg()).neg();return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.neg().sigmoid())}}}))}}),_c=K({neg_:function(e){var t=G(e,`x`,`neg`),n=[t];return V.runKernelFunc((function(e){return e.neg(t)}),{x:t},(function(e){return{x:function(){return e.neg()}}}),`Neg`,{},n)}}),vc=K({reciprocal_:function(e){var t=G(e,`x`,`reciprocal`);return V.runKernelFunc((function(e,n){var r=e.reciprocal(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.square().neg())}}}))}}),yc=K({round_:function(e){var t=G(e,`x`,`round`);return V.runKernelFunc((function(e){return e.round(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),bc=K({rsqrt_:function(e){var t=G(e,`x`,`rsqrt`),n=[t];return V.runKernelFunc((function(e,n){var r=e.rsqrt(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.pow(1.5).mul(2)).neg()}}}),`Rsqrt`,{},n)}}),xc=K({sigmoid_:function(e){var t=G(e,`x`,`sigmoid`);return V.runKernelFunc((function(e,n){var r=e.sigmoid(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.mul(q(1).sub(n)))}}}),`Sigmoid`)}}),Sc=K({sign_:function(e){var t=G(e,`x`,`sign`);return V.runKernelFunc((function(e){return e.sign(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),Cc=K({isNaN_:function(e){var t=G(e,`x`,`isNaN`);return V.runKernelFunc((function(e){return e.isNaN(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),wc=K({isInf_:function(e){var t=G(e,`x`,`isInf`);return V.runKernelFunc((function(e){return e.isInf(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),Tc=K({isFinite_:function(e){var t=G(e,`x`,`isFinite`);return V.runKernelFunc((function(e){return e.isFinite(t)}),{$x:t},(function(e){return{$x:function(){return tr(e)}}}))}}),Ec=K({sin_:function(e){var t=G(e,`x`,`sin`),n=[t];return V.runKernelFunc((function(e,n){var r=e.sin(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().cos().mul(e)}}}),`Sin`,{},n)}}),Dc=K({sinh_:function(e){var t=G(e,`x`,`sinh`);return V.runKernelFunc((function(e,n){var r=e.sinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().cosh().mulStrict(e)}}}))}}),Oc=K({softplus_:function(e){var t=G(e,`x`,`softplus`);return V.runKernelFunc((function(e,n){var r=e.softplus(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.sigmoid())}}}))}}),kc=K({sqrt_:function(e){var t=G(e,`x`,`sqrt`);return V.runKernelFunc((function(e,n){var r=e.sqrt(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().sqrt().mul(2))}}}))}}),Ac=K({step_:function(e,t){t===void 0&&(t=0);var n=G(e,`x`,`step`);return V.runKernelFunc((function(e){return e.step(n,t)}),{$x:n},(function(e){return{$x:function(){return tr(e)}}}))}}),jc=K({tan_:function(e){var t=G(e,`x`,`tan`);return V.runKernelFunc((function(e,n){var r=e.tan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.cos().square())}}}))}}),Mc=K({tanh_:function(e){var t=G(e,`x`,`tanh`);return V.runKernelFunc((function(e,n){var r=e.tanh(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return q(1).sub(n.square()).mulStrict(e)}}}),`Tanh`,{},null,[!0])}});function Nc(e,t,n,r,i,a){var o,s,c=G(e,`x`,`batchNorm`),l=G(t,`mean`,`batchNorm`),u=G(n,`variance`,`batchNorm`);return i!=null&&(o=G(i,`scale`,`batchNorm`)),r!=null&&(s=G(r,`offset`,`batchNorm`)),I(c.rank===2,(function(){return`Error in batchNorm3D: x must be rank 3 but got rank `+c.rank+`.`})),I(l.rank===2||l.rank===1,(function(){return`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank `+l.rank+`.`})),I(u.rank===2||u.rank===1,(function(){return`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank `+u.rank+`.`})),o!=null&&I(o.rank===2||o.rank===1,(function(){return`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank `+o.rank+`.`})),s!=null&&I(s.rank===2||s.rank===1,(function(){return`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank `+s.rank+`.`})),Ic(c,l,u,s,o,a)}function Pc(e,t,n,r,i,a){var o,s,c=G(e,`x`,`batchNorm`),l=G(t,`mean`,`batchNorm`),u=G(n,`variance`,`batchNorm`);return i!=null&&(o=G(i,`scale`,`batchNorm`)),r!=null&&(s=G(r,`offset`,`batchNorm`)),I(c.rank===3,(function(){return`Error in batchNorm3D: x must be rank 3 but got rank `+c.rank+`.`})),I(l.rank===3||l.rank===1,(function(){return`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank `+l.rank+`.`})),I(u.rank===3||u.rank===1,(function(){return`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank `+u.rank+`.`})),o!=null&&I(o.rank===3||o.rank===1,(function(){return`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank `+o.rank+`.`})),s!=null&&I(s.rank===3||s.rank===1,(function(){return`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank `+s.rank+`.`})),Ic(c,l,u,s,o,a)}function Fc(e,t,n,r,i,a){var o,s,c=G(e,`x`,`batchNorm`),l=G(t,`mean`,`batchNorm`),u=G(n,`variance`,`batchNorm`);return i!=null&&(o=G(i,`scale`,`batchNorm`)),r!=null&&(s=G(r,`offset`,`batchNorm`)),I(c.rank===4,(function(){return`Error in batchNorm4D: x must be rank 4 but got rank `+c.rank+`.`})),I(l.rank===4||l.rank===1,(function(){return`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank `+l.rank+`.`})),I(u.rank===4||u.rank===1,(function(){return`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank `+u.rank+`.`})),o!=null&&I(o.rank===4||o.rank===1,(function(){return`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank `+o.rank+`.`})),s!=null&&I(s.rank===4||s.rank===1,(function(){return`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank `+s.rank+`.`})),Ic(c,l,u,s,o,a)}function Ic(e,t,n,r,i,a){a??=.001;var o,s,c,l=G(e,`x`,`batchNorm`),u=G(t,`mean`,`batchNorm`),d=G(n,`variance`,`batchNorm`);i!=null&&(o=G(i,`scale`,`batchNorm`)),r!=null&&(s=G(r,`offset`,`batchNorm`)),I(u.rank===d.rank,(function(){return`Batch normalization gradient requires mean and variance to have equal ranks.`})),I(s==null||u.rank===s.rank,(function(){return`Batch normalization gradient requires mean and offset to have equal ranks.`})),I(o==null||u.rank===o.rank,(function(){return`Batch normalization gradient requires mean and scale to have equal ranks.`})),c=l.rank===0||l.rank===1?l.as4D(1,1,1,l.size):l.rank===2?l.as4D(1,1,l.shape[0],l.shape[1]):l.rank===3?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;var f=[l,u,d,o];return V.runKernelFunc((function(e,t){var n=e.batchNormalization(c,Lc(u),Lc(d),a,Lc(o),Lc(s));return t([l,u,d,o]),n}),{x:l,mean:u,variance:d,scale:o,offset:s},(function(e,t){var n=t,r=n[0],i=n[1],o=n[2],s=n[3]??q(1),l=yi(i.shape,c.shape),u=[];if(i.rank===1){for(var d=0;d<c.shape.length-1;++d)u.push(c.shape[d]);u.push(1)}var f=r.sub(i),p=e.mul(s),m=bc(o.add(q(a))),h=m.mul(m).mul(m).mul(q(-.5));return{x:function(){return i.rank===1?e.mul(Wr(m.as4D(1,1,1,i.shape[0]),u)).mul(s).reshape(r.shape):e.mul(m).mul(s).reshape(r.shape)},mean:function(){var e=m.mul(q(-1)).mul(p);return i.rank===1&&(e=e.sum(l)),e.reshape(i.shape)},variance:function(){var e=h.mul(f).mul(p);return i.rank===1&&(e=e.sum(l)),e.reshape(i.shape)},scale:function(){var t=f.mul(m),n=e.mul(t);return i.rank===1&&(n=n.sum(l)),n.reshape(i.shape)},offset:function(){var t=e;return i.rank===1&&(t=t.sum(l)),t.reshape(i.shape)}}}),`BatchNormalization`,{varianceEpsilon:a},f).reshape(l.shape)}function Lc(e){return e==null?null:e.rank===0?e.as1D():e.rank===1?e:e.rank===2?e.as4D(1,1,e.shape[0],e.shape[1]):e.rank===3?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}function Rc(){bn(`tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon`)}var zc=K({batchNormalization2d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),Rc(),Nc(e,t,n,a,i,r)}}),Bc=K({batchNormalization3d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),Rc(),Pc(e,t,n,a,i,r)}}),Vc=K({batchNormalization4d_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),Rc(),Fc(e,t,n,a,i,r)}}),Hc=K({batchNormalization_:function(e,t,n,r,i,a){return r===void 0&&(r=.001),Rc(),Ic(e,t,n,a,i,r)}}),Uc=K({batchNorm_:Ic}),Wc=K({batchNorm2d_:Nc}),Gc=K({batchNorm3d_:Pc}),Kc=K({batchNorm4d_:Fc}),qc=K({logicalAnd_:function(e,t){var n=G(e,`a`,`logicalAnd`,`bool`),r=G(t,`b`,`logicalAnd`,`bool`);return bi(n.shape,r.shape),V.runKernelFunc((function(e){return e.logicalAnd(n,r)}),{a:n,b:r},null,`LogicalAnd`)}}),Jc=K({logicalNot_:function(e){var t=G(e,`x`,`logicalNot`,`bool`);return V.runKernelFunc((function(e){return e.logicalNot(t)}),{$x:t})}}),Yc=K({logicalOr_:function(e,t){var n=G(e,`a`,`logicalOr`,`bool`),r=G(t,`b`,`logicalOr`,`bool`);return bi(n.shape,r.shape),V.runKernelFunc((function(e){return e.logicalOr(n,r)}),{$a:n,$b:r})}}),Xc=K({logicalXor_:function(e,t){var n=G(e,`a`,`logicalXor`,`bool`),r=G(t,`b`,`logicalXor`,`bool`);return bi(n.shape,r.shape),Yc(e,t).logicalAnd(qc(e,t).logicalNot())}}),Zc=K({where_:function(e,t,n){var r=G(t,`a`,`where`),i=G(n,`b`,`where`),a=G(e,`condition`,`where`,`bool`);return L(r.shape,i.shape,`Error in where: `),a.rank===1?I(a.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):L(a.shape,i.shape,`Error in where: `),V.runKernelFunc((function(e,t){var n=e.select(a,r,i);return t([a]),n}),{$condition:a,$a:r,$b:i},(function(e,t){var n=t[0];return{$condition:function(){return tr(n).toFloat()},$a:function(){return e.mul(n.cast(e.dtype))},$b:function(){return e.mul(n.logicalNot().cast(e.dtype))}}}))}}),Qc=function(e){return w(this,void 0,void 0,(function(){var t,n,r;return T(this,(function(i){switch(i.label){case 0:return[4,(t=G(e,`condition`,`whereAsync`,`bool`)).data()];case 1:return n=i.sent(),r=Zi(t.shape,n),e!==t&&t.dispose(),[2,r]}}))}))},$c=K({add_:function(e,t){var n,r=G(e,`a`,`add`),i=G(t,`b`,`add`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e){return e.add(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=yi(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=yi(i.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(i.shape)}}}),`Add`)}}),el=K({addN_:function(e){I(Array.isArray(e),(function(){return`The argument passed to tf.addN() must be a list of tensors`})),I(e.length>=1,(function(){return`Must pass at least one tensor to tf.addN(), but got `+e.length}));var t=e.map((function(e,t){return G(e,`tensors`+t,`addN`)})),n=t[0];t.forEach((function(e){if(e.dtype!==n.dtype)throw Error(`All tensors passed to tf.addN() must have the same dtype`)})),t.forEach((function(e){if(!z(e.shape,n.shape))throw Error(`All tensors passed to tf.addN() must have the same shape`)}));var r=t;return V.runKernelFunc((function(e){return e.addN(t)}),r,(function(e){var n={};return t.forEach((function(t,r){n[r]=function(){return e.clone()}})),n}),`AddN`)}}),tl=K({addStrict_:function(e,t){var n=G(e,`a`,`addStrict`),r=G(t,`b`,`addStrict`);return L(n.shape,r.shape,`Error in addStrict: `),n.add(r)}}),nl=K({atan2_:function(e,t){var n,r=G(e,`a`,`atan2`),i=G(t,`b`,`atan2`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e,t){var n=e.atan2(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=$c(n.square(),r.square()),i=e.mul(r.div(t)),o=yi(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=$c(n.square(),r.square()),i=_c(e.mul(n.div(t))),o=yi(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}}))}}),rl=K({div_:function(e,t){var n,r=G(e,`a`,`div`),i=G(t,`b`,`div`);if(n=lt(r,i),r=n[0],i=n[1],r.dtype===`int32`&&i.dtype===`int32`)return ol(r,i);var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e,t){var n=e.realDivide(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=yi(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=yi(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}}),`Div`)}}),il=K({divNoNan_:function(e,t){var n,r=G(e,`a`,`div`),i=G(t,`b`,`div`);r=(n=lt(r,i))[0],i=n[1];var a=rl(r,i),o=tr(a);return Zc(i.equal(o),o,a)}}),al=K({divStrict_:function(e,t){var n=G(e,`a`,`div`),r=G(t,`b`,`div`);return L(n.shape,r.shape,`Error in divideStrict: `),n.div(r)}}),ol=K({floorDiv_:function(e,t){var n,r=G(e,`a`,`floorDiv`),i=G(t,`b`,`floorDiv`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e,t){var n=e.floorDiv(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=yi(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=yi(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}}),`FloorDiv`)}}),sl=K({maximum_:function(e,t){var n,r=G(e,`a`,`maximum`),i=G(t,`b`,`maximum`);return n=lt(r,i),r=n[0],i=n[1],r.dtype===`bool`&&(r=r.toInt(),i=i.toInt()),bi(r.shape,i.shape),V.runKernelFunc((function(e,t){var n=e.maximum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.greaterEqual(r).toFloat())},b:function(){return e.mul(n.less(r).toFloat())}}}),`Maximum`)}}),cl=K({maximumStrict_:function(e,t){var n=G(e,`a`,`maximumStrict`),r=G(t,`b`,`maximumStrict`);return L(n.shape,r.shape,`Error in maximumStrict: `),n.maximum(r)}}),ll=K({minimum_:function(e,t){var n,r=G(e,`a`,`minimum`),i=G(t,`b`,`minimum`);return n=lt(r,i),r=n[0],i=n[1],r.dtype===`bool`&&(r=r.toInt(),i=i.toInt()),bi(r.shape,i.shape),V.runKernelFunc((function(e,t){var n=e.minimum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.lessEqual(r).toFloat())},b:function(){return e.mul(n.greater(r).toFloat())}}}),`Minimum`)}}),ul=K({minimumStrict_:function(e,t){var n=G(e,`a`,`minimumStrict`),r=G(t,`b`,`minimumStrict`);return L(n.shape,r.shape,`Error in minimumStrict: `),n.minimum(r)}}),dl=K({mod_:function(e,t){var n,r=G(e,`a`,`mod`),i=G(t,`b`,`mod`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e,t){var n=e.mod(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=yi(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=yi(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}}))}}),fl=K({modStrict_:function(e,t){var n=G(e,`a`,`modStrict`),r=G(t,`b`,`modStrict`);return L(n.shape,r.shape,`Error in modStrict: `),n.mod(r)}}),pl=K({mul_:function(e,t){var n,r=G(e,`a`,`mul`),i=G(t,`b`,`mul`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e,t){var n=e.multiply(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.mul(r.toFloat()),i=yi(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=yi(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}}),`Mul`)}}),ml=K({mulStrict_:function(e,t){var n=G(e,`a`,`mul`),r=G(t,`b`,`mul`);return L(n.shape,r.shape,`Error in multiplyStrict: `),n.mul(r)}}),hl=K({pow_:function(e,t){var n,r=G(e,`base`,`pow`),i=G(t,`exp`,`pow`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape),o=[r,i];return V.runKernelFunc((function(e,t){var n=e.pow(r,i);return t([r,i,n]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1],i=t[2];return{a:function(){var t=r.toFloat(),i=e.mul(t.mul(n.pow(t.sub(q(1))))),o=yi(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},b:function(){var t=n.greater(0),o=n.log().where(t,tr(n)),s=e.mul(i.mul(o)),c=yi(r.shape,a);return c.length>0&&(s=s.sum(c)),s.reshape(r.shape)}}}),`Pow`,{},o,[!0])}}),gl=K({powStrict_:function(e,t){return L(e.shape,t.shape,`Error in powStrict: `),e.pow(t)}}),_l=K({squaredDifferenceStrict_:function(e,t){var n=G(e,`a`,`squaredDifferenceStrict`),r=G(t,`b`,`squaredDifferenceStrict`);return L(n.shape,r.shape,`Error in squaredDifferenceStrict: `),n.squaredDifference(r)}}),vl=K({sub_:function(e,t){var n,r=G(e,`a`,`sub`),i=G(t,`b`,`sub`);n=lt(r,i),r=n[0],i=n[1];var a=bi(r.shape,i.shape);return V.runKernelFunc((function(e){return e.subtract(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=yi(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=yi(i.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(i.shape)}}}),`Sub`)}}),yl=K({subStrict_:function(e,t){var n=G(e,`a`,`subStrict`),r=G(t,`b`,`subStrict`);return L(n.shape,r.shape,`Error in subStrict: `),n.sub(r)}}),bl=K({equal_:function(e,t){var n,r=G(e,`a`,`equal`),i=G(t,`b`,`equal`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e){return e.equal(r,i)}),{$a:r,$b:i})}}),xl=K({equalStrict_:function(e,t){var n=G(e,`a`,`equalStrict`),r=G(t,`b`,`equalStrict`);return L(n.shape,r.shape,`Error in equalStrict: `),n.equal(r)}}),Sl=K({greater_:function(e,t){var n,r=G(e,`a`,`greater`),i=G(t,`b`,`greater`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e){return e.greater(r,i)}),{a:r,b:i},null,`Greater`)}}),Cl=K({greaterEqual_:function(e,t){var n,r=G(e,`a`,`greaterEqual`),i=G(t,`b`,`greaterEqual`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e,t){var n=e.greaterEqual(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return tr(n)},b:function(){return tr(r)}}}),`GreaterEqual`)}}),wl=K({greaterEqualStrict_:function(e,t){var n=G(e,`a`,`greaterEqualStrict`),r=G(t,`b`,`greaterEqualStrict`);return L(n.shape,r.shape,`Error in greaterEqualStrict: `),n.greaterEqual(r)}}),Tl=K({greaterStrict_:function(e,t){var n=G(e,`a`,`greaterStrict`),r=G(t,`b`,`greaterStrict`);return L(n.shape,r.shape,`Error in greaterStrict: `),n.greater(r)}}),El=K({less_:function(e,t){var n,r=G(e,`a`,`less`),i=G(t,`b`,`less`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e){return e.less(r,i)}),{a:r,b:i},null,`Less`)}}),Dl=K({lessEqual_:function(e,t){var n,r=G(e,`a`,`lessEqual`),i=G(t,`b`,`lessEqual`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e,t){var n=e.lessEqual(r,i);return t([r,i]),n}),{a:r,b:i},null,`LessEqual`)}}),Ol=K({lessEqualStrict_:function(e,t){var n=G(e,`a`,`lessEqualStrict`),r=G(t,`b`,`lessEqualStrict`);return L(n.shape,r.shape,`Error in lessEqualStrict: `),n.lessEqual(r)}}),kl=K({lessStrict_:function(e,t){var n=G(e,`a`,`lessStrict`),r=G(t,`b`,`lessStrict`);return L(n.shape,r.shape,`Error in lessStrict: `),n.less(r)}}),Al=K({notEqual_:function(e,t){var n,r=G(e,`a`,`notEqual`),i=G(t,`b`,`notEqual`);return n=lt(r,i),r=n[0],i=n[1],bi(r.shape,i.shape),V.runKernelFunc((function(e){return e.notEqual(r,i)}),{a:r,b:i},null,`NotEqual`)}}),jl=K({notEqualStrict_:function(e,t){var n=G(e,`a`,`notEqualStrict`),r=G(t,`b`,`notEqualStrict`);return L(n.shape,r.shape,`Error in notEqualStrict: `),n.notEqual(r)}});function Ml(e,t){for(var n=[],r=e;r<t;++r)n.push(r);return n}function Nl(e){for(var t=[],n=0;n<e.length;++n)for(var r=0;r<e[n].length;++r)t.push(e[n][r]);return t}var Pl=K({gather_:function(e,t,n){n===void 0&&(n=0);var r=G(e,`x`,`gather`),i=G(t,`indices`,`gather`,`int32`);n=me(n,r.shape)[0];var a=function(e,t,n){for(var r=e.shape[n],i=[],a=1,o=1,s=0;s<n;s++)i.push(e.shape[s]),a*=e.shape[s];for(s=0;s<t.rank;s++)i.push(t.shape[s]);for(s=n+1;s<e.rank;s++)i.push(e.shape[s]),o*=e.shape[s];return{batchSize:a,sliceSize:o,dimSize:r,outputShape:i}}(r,i,n);return V.runKernelFunc((function(e,t){var a=e.gather(r,i.flatten(),n);return t([i]),a}),{x:r,indices:i},(function(e,t){var i=t[0];return{x:function(){var t=r.shape,a=i.size,o=t.slice(0,n),s=o.length,c=t.slice(n,t.length).slice(1),l=c.length,u=Ml(0,s),d=Ml(s+1,s+1+l),f=Nl([o,[a],c]),p=e.reshape(f),m=i.reshape([a]),h=Nl([[s],u,d]),g=Fl(p.transpose(h),m,r.shape[n]),_=Nn(h);return g=g.transpose(_)},indices:function(){return i}}}),`Gather`,{axis:n}).reshape(a.outputShape)}}),Fl=K({unsortedSegmentSum_:function(e,t,n){var r=G(e,`x`,`unsortedSegmentSum`),i=G(t,`segmentIds`,`unsortedSegmentSum`,`int32`);return I(ce(n),(function(){return`numSegments must be of dtype int`})),V.runKernelFunc((function(e,t){var a=e.unsortedSegmentSum(r,i,n);return t([i]),a}),{$x:r},(function(e,t){var n=t[0];return{$x:function(){return function(e,t){for(var n=Pl(e,sl(t,tr(t))),r=Cl(t,q(0,`int32`)),i=n.rank-r.rank,a=0;a<i;++a)r=Dr(r,a+1);r=qc(r,Yn(n.shape,`bool`));var o=tr(n);return Zc(r,n,o)}(e,n)}}}))}}),Il=function(e,t,n){return w(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,d,f,p,m,h;return T(this,(function(g){switch(g.label){case 0:for(r=G(e,`tensor`,`boolMask`),i=G(t,`mask`,`boolMask`,`bool`),a=n??0,o=i.rank,s=r.shape,I(o>0,(function(){return`mask cannot be scalar`})),L(s.slice(a,a+o),i.shape,`mask's shape must match the first K dimensions of tensor's shape,`),c=1,l=a;l<a+o;l++)c*=s[l];return u=s.slice(0,a).concat([c],s.slice(a+o)),d=r.reshape(u),f=i.reshape([-1]),[4,Qc(f)];case 1:return p=g.sent(),m=p.squeeze([1]),h=Pl(d,m,a),e!==r&&r.dispose(),t!==i&&i.dispose(),m.dispose(),d.dispose(),f.dispose(),p.dispose(),[2,h]}}))}))};function Ll(e,t,n,r,i,a,o){a===void 0&&(a=`NHWC`),I(e.length===t.rank,(function(){return`Length of inShape (`+e.length+`) and rank of dy (`+t.rank+`) must match`}));var s=e,c=t,l=!1;t.rank===3&&(l=!0,c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),s=[1,e[0],e[1],e[2]]),I(s.length===4,(function(){return`Error in conv2dDerInput: inShape must be length 4, but got length `+s.length+`.`})),I(c.rank===4,(function(){return`Error in conv2dDerInput: dy must be rank 4, but got rank `+c.rank})),I(n.rank===4,(function(){return`Error in conv2dDerInput: filter must be rank 4, but got rank `+n.rank}));var u=a===`NHWC`?s[3]:s[1],d=a===`NHWC`?c.shape[3]:c.shape[1];I(u===n.shape[2],(function(){return`Error in conv2dDerInput: depth of input (`+u+`) must match input depth for filter `+n.shape[2]+`.`})),I(d===n.shape[3],(function(){return`Error in conv2dDerInput: depth of output (`+d+`) must match output depth for filter `+n.shape[3]+`.`})),o!=null&&I(ce(i),(function(){return`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+i+`.`}));var f=Mi(a),p=Ci(s,n.shape,r,1,i,o,!1,f),m=V.runKernelFunc((function(e,t){var r=e.conv2dDerInput(c,n,p);return t([n,c]),r}),{dy4D:c,filter:n},(function(e,t){var n=t[0],s=t[1];return{dy4D:function(){return Vl(e,n,r,i,a,1,o)},filter:function(){return Ul(e,s,n.shape,r,i,a,o)}}}));return l?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}function Rl(e){var t=function(e){return typeof e==`number`?[e,e,e]:e.length===2?[e[0],e[1],1]:e}(e),n=t[0],r=t[1],i=t[2];return n===1&&r===1&&i===1}function zl(e,t,n,r,i){I(e.length===t.rank,(function(){return`Length of inShape (`+e.length+`) and rank of dy (`+t.rank+`) must match`}));var a=e,o=t,s=!1;t.rank===4&&(s=!0,o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),a=[1,e[0],e[1],e[2],e[3]]);var c=a[4],l=o.shape[4];I(a.length===5,(function(){return`Error in conv3dDerInput: inShape must be length 5, but got length `+a.length+`.`})),I(o.rank===5,(function(){return`Error in conv3dDerInput: dy must be rank 5, but got rank `+o.rank})),I(n.rank===5,(function(){return`Error in conv3dDerInput: filter must be rank 5, but got rank `+n.rank})),I(c===n.shape[3],(function(){return`Error in conv3dDerInput: depth of input (`+c+`) must match input depth for filter `+n.shape[3]+`.`})),I(l===n.shape[4],(function(){return`Error in conv3dDerInput: depth of output (`+l+`) must match output depth for filter `+n.shape[4]+`.`}));var u=wi(a,n.shape,r,1,i),d=V.runKernelFunc((function(e){return e.conv3dDerInput(o,n,u)}),{dy5D:o});return s?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}var Bl=K({conv1d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NWC`),a===void 0&&(a=1);var s=G(e,`x`,`conv1d`),c=G(t,`filter`,`conv1d`),l=s,u=!1;s.rank===2&&(u=!0,l=s.as3D(1,s.shape[0],s.shape[1])),I(l.rank===3,(function(){return`Error in conv1d: input must be rank 3, but got rank `+l.rank+`.`})),I(c.rank===3,(function(){return`Error in conv1d: filter must be rank 3, but got rank `+c.rank+`.`})),o!=null&&I(ce(r),(function(){return`Error in conv1d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`})),I(l.shape[2]===c.shape[1],(function(){return`Error in conv1d: depth of input (`+l.shape[2]+`) must match input depth for filter `+c.shape[1]+`.`})),I(ji(n,a),(function(){return`Error in conv1D: Either stride or dilation must be 1. Got stride `+n+` and dilation '`+a+`'`})),I(i===`NWC`,(function(){return`Error in conv1d: got dataFormat of `+i+` but only NWC is currently supported.`}));var d=c.as4D(1,c.shape[0],c.shape[1],c.shape[2]),f=Vl(l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),d,[1,n],r,`NHWC`,[1,a],o);return u?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),Vl=K({conv2d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NHWC`),a===void 0&&(a=[1,1]);var s=G(e,`x`,`conv2d`),c=G(t,`filter`,`conv2d`),l=s,u=!1;s.rank===3&&(u=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),I(l.rank===4,(function(){return`Error in conv2d: input must be rank 4, but got rank `+l.rank+`.`})),I(c.rank===4,(function(){return`Error in conv2d: filter must be rank 4, but got rank `+c.rank+`.`})),o!=null&&I(ce(r),(function(){return`Error in conv2d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`}));var d=i===`NHWC`?l.shape[3]:l.shape[1];I(d===c.shape[2],(function(){return`Error in conv2d: depth of input (`+d+`) must match input depth for filter `+c.shape[2]+`.`})),I(ji(n,a),(function(){return`Error in conv2D: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`}));var f=Mi(i),p=Ci(l.shape,c.shape,n,a,r,o,!1,f),m=[c,l],h=V.runKernelFunc((function(e,t){var n=e.conv2d(l,c,p);return t([c,l]),n}),{x:l,filter:c},(function(e,t){var o=t,s=o[0],c=o[1];return I(Ai(a),(function(){return`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+a+`'`})),{x:function(){return Wl(c.shape,e,s,n,r,i)},filter:function(){return Ul(c,e,s.shape,n,r,i)}}}),`Conv2D`,p,m);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),Hl=K({conv3d_:function(e,t,n,r,i,a){i===void 0&&(i=`NDHWC`),a===void 0&&(a=[1,1,1]);var o=G(e,`x`,`conv3d`),s=G(t,`filter`,`conv3d`),c=o,l=!1;o.rank===4&&(l=!0,c=o.as5D(1,o.shape[0],o.shape[1],o.shape[2],o.shape[3])),I(c.rank===5,(function(){return`Error in conv3d: input must be rank 5, but got rank `+c.rank+`.`})),I(s.rank===5,(function(){return`Error in conv3d: filter must be rank 5, but got rank `+s.rank+`.`})),I(c.shape[4]===s.shape[3],(function(){return`Error in conv3d: depth of input (`+c.shape[4]+`) must match input depth for filter `+s.shape[3]+`.`})),I(function(e,t){return Rl(e)||Rl(t)}(n,a),(function(){return`Error in conv3D: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`})),I(i===`NDHWC`,(function(){return`Error in conv3d: got dataFormat of `+i+` but only NDHWC is currently supported.`}));var u=wi(c.shape,s.shape,n,a,r),d=V.runKernelFunc((function(e,t){var n=e.conv3d(c,s,u);return t([c,s]),n}),{x:c,$filter:s},(function(e,t){I(Rl(a),(function(){return`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+a+`'`}));var i=t[0],o=t[1];return{x:function(){return zl(i.shape,e,o,n,r)},$filter:function(){return function(e,t,n,r,i){var a=e;e.rank===4&&(a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));var o=t;o.rank===4&&(o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3])),I(a.rank===5,(function(){return`Error in conv3dDerFilter: input must be rank 5, but got shape `+a.shape+`.`})),I(o.rank===5,(function(){return`Error in conv3dDerFilter: dy must be rank 5, but got shape `+o.shape+`.`})),I(n.length===5,(function(){return`Error in conv3dDerFilter: filterShape must be length 5, but got `+n+`.`})),I(a.shape[4]===n[3],(function(){return`Error in conv3dDerFilter: depth of input `+a.shape[4]+`) must match input depth in filter (`+n[3]+`.`})),I(o.shape[4]===n[4],(function(){return`Error in conv3dDerFilter: depth of dy (`+o.shape[4]+`) must match output depth for filter (`+n[4]+`).`}));var s=wi(a.shape,n,r,1,i);return V.runKernelFunc((function(e){return e.conv3dDerFilter(a,o,s)}),{x5D:a,dy5D:o})}(i,e,o.shape,n,r)}}}));return l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),Ul=K({conv2dDerFilter_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NHWC`);var s=e;e.rank===3&&(s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t;c.rank===3&&(c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),I(s.rank===4,(function(){return`Error in conv2dDerFilter: input must be rank 4, but got shape `+s.shape+`.`})),I(c.rank===4,(function(){return`Error in conv2dDerFilter: dy must be rank 4, but got shape `+c.shape+`.`})),I(n.length===4,(function(){return`Error in conv2dDerFilter: filterShape must be length 4, but got `+n+`.`}));var l=a===`NHWC`?s.shape[3]:s.shape[1],u=a===`NHWC`?c.shape[3]:c.shape[1];I(l===n[2],(function(){return`Error in conv2dDerFilter: depth of input `+l+`) must match input depth in filter (`+n[2]+`.`})),I(u===n[3],(function(){return`Error in conv2dDerFilter: depth of dy (`+u+`) must match output depth for filter (`+n[3]+`).`})),o!=null&&I(ce(i),(function(){return`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+i+`.`}));var d=Mi(a),f=Ci(s.shape,n,r,1,i,o,!1,d);return V.runKernelFunc((function(e){return e.conv2dDerFilter(s,c,f)}),{x4D:s,dy4D:c})}}),Wl=K({conv2dDerInput_:Ll}),Gl=K({depthwiseConv2d_:function(e,t,n,r,i,a,o){i===void 0&&(i=`NHWC`),a===void 0&&(a=[1,1]);var s=G(e,`x`,`depthwiseConv2d`),c=G(t,`filter`,`depthwiseConv2d`),l=s,u=!1;s.rank===3&&(u=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),I(l.rank===4,(function(){return`Error in depthwiseConv2d: input must be rank 4, but got rank `+l.rank+`.`})),I(c.rank===4,(function(){return`Error in depthwiseConv2d: filter must be rank 4, but got rank `+c.rank+`.`})),I(l.shape[3]===c.shape[2],(function(){return`Error in depthwiseConv2d: number of input channels (`+l.shape[3]+`) must match the inChannels dimension in filter `+c.shape[2]+`.`})),a??=[1,1],I(ji(n,a),(function(){return`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+a+`'`})),o!=null&&I(ce(r),(function(){return`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+r+`.`}));var d=Ci(l.shape,c.shape,n,a,r,o,!0),f=[l,c],p=V.runKernelFunc((function(e,t){var n=e.depthwiseConv2D(l,c,d);return t([l,c]),n}),{x:l,filter:c},(function(e,t){I(Ai(a),(function(){return`Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '`+a+`'`}));var n=t[0],r=t[1];return{x:function(){return Kl(n.shape,e,r,d)},filter:function(){return ql(n,e,r.shape,d)}}}),`DepthwiseConv2dNative`,d,f);return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),Kl=K({depthwiseConv2dDerInput_:function(e,t,n,r){var i=t,a=!1;t.rank===3&&(a=!0,i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=V.runKernelFunc((function(e){return e.depthwiseConv2DDerInput(i,n,r)}),{dy4D:i});return a?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}}),ql=K({depthwiseConv2dDerFilter_:function(e,t,n,r){var i=e;e.rank===3&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var a=t;return a.rank===3&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),V.runKernelFunc((function(e){return e.depthwiseConv2DDerFilter(i,a,r)}),{x4D:i,dy4D:a})}}),Jl=K({separableConv2d_:function(e,t,n,r,i,a,o){a===void 0&&(a=[1,1]),o===void 0&&(o=`NHWC`);var s=G(e,`x`,`separableConv2d`),c=G(t,`depthwiseFilter`,`separableConv2d`),l=G(n,`pointwiseFilter`,`separableConv2d`),u=s,d=!1;if(s.rank===3&&(d=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),o===`NCHW`)throw Error(`separableConv2d currently does not support dataFormat NCHW; only NHWC is supported`);I(u.rank===4,(function(){return`Error in separableConv2d: input must be rank 4, but got rank `+u.rank+`.`})),I(c.rank===4,(function(){return`Error in separableConv2d: depthwise filter must be rank 4, but got rank `+c.rank+`.`})),I(l.rank===4,(function(){return`Error in separableConv2d: pointwise filter must be rank 4, but got rank `+c.rank+`.`})),I(l.shape[0]===1,(function(){return`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got `+l.shape[0]+`.`})),I(l.shape[1]===1,(function(){return`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got `+l.shape[1]+`.`}));var f=c.shape[2],p=c.shape[3];I(l.shape[2]===f*p,(function(){return`Error in separableConv2d: the third dimension of pointwise filter must be `+f*p+`, but got `+l.shape[2]+`.`}));var m=Vl(Gl(u,c,r,i,o,a),l,1,`valid`,o);return d?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Yl=K({conv2dTranspose_:function(e,t,n,r,i,a){return Ll(n,G(e,`x`,`conv2dTranspose`),G(t,`filter`,`conv2dTranspose`),r,i,`NHWC`,a)}}),Xl=K({conv3dTranspose_:function(e,t,n,r,i){return zl(n,G(e,`x`,`conv3dTranspose`),G(t,`filter`,`conv3dTranspose`),r,i)}}),Zl=K({matMul_:function(e,t,n,r){var i;n===void 0&&(n=!1),r===void 0&&(r=!1);var a=G(e,`a`,`matMul`),o=G(t,`b`,`matMul`);i=lt(a,o),a=i[0],o=i[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],c=r?o.shape[o.rank-1]:o.shape[o.rank-2],l=n?a.shape[a.rank-1]:a.shape[a.rank-2],u=r?o.shape[o.rank-2]:o.shape[o.rank-1],d=a.shape.slice(0,-2),f=o.shape.slice(0,-2),p=R(d),m=R(f);I(a.rank>=2&&o.rank>=2&&a.rank===o.rank,(function(){return`Error in matMul: inputs must have the same rank of at least 2, got ranks `+a.rank+` and `+o.rank+`.`})),I(z(d,f),(function(){return`Error in matMul: outer dimensions (`+d+`) and (`+f+`) of Tensors with shapes `+a.shape+` and `+o.shape+` must match.`})),I(s===c,(function(){return`Error in matMul: inner shapes (`+s+`) and (`+c+`) of Tensors with shapes `+a.shape+` and `+o.shape+` and transposeA=`+n+` and transposeB=`+r+` must match.`}));var h=a.shape.slice(0,-2).concat([l,u]),g=n?a.as3D(p,s,l):a.as3D(p,l,s),_=r?o.as3D(m,u,c):o.as3D(m,c,u),v={transposeA:n,transposeB:r};return V.runKernelFunc((function(e,t){var i=e.batchMatMul(g,_,n,r);return t([g,_]),i}),{a:g,b:_},(function(e,t){var i=t,a=i[0],o=i[1];return n||r?!n&&r?{a:function(){return e.matMul(o,!1,!1)},b:function(){return e.matMul(a,!0,!1)}}:n&&!r?{a:function(){return o.matMul(e,!1,!0)},b:function(){return a.matMul(e,!1,!1)}}:{a:function(){return o.matMul(e,!0,!0)},b:function(){return e.matMul(a,!0,!0)}}:{a:function(){return e.matMul(o,!1,!0)},b:function(){return a.matMul(e,!0,!1)}}}),`BatchMatMul`,v).reshape(h)}}),Ql=K({dot_:function(e,t){var n=G(e,`t1`,`dot`),r=G(t,`t2`,`dot`);I(!(n.rank!==1&&n.rank!==2||r.rank!==1&&r.rank!==2),(function(){return`Error in dot: inputs must all be rank 1 or 2, but got ranks `+n.rank+` and `+r.rank+`.`}));var i=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];return I(i===a,(function(){return`Error in dot: inner dimensions of inputs must match, but got `+i+` and `+a+`.`})),n.rank===1&&r.rank===1?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():n.rank===1&&r.rank===2?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():n.rank===2&&r.rank===1?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),$l=K({outerProduct_:function(e,t){var n=G(e,`v1`,`outerProduct`),r=G(t,`v2`,`outerProduct`);return I(n.rank===1&&r.rank===1,(function(){return`Error in outerProduct: inputs must be rank 1, but got ranks `+n.rank+` and `+r.rank+`.`})),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),eu=K({reverse_:function(e,t){var n=G(e,`x`,`reverse`);if(n.rank===0)return n.clone();var r=me(t,n.shape);return V.runKernelFunc((function(e){return e.reverse(n,r)}),{$x:n},(function(e){return{$x:function(){return e.reverse(r)}}})).reshapeAs(n)}}),tu=K({reverse1d_:function(e){var t=G(e,`x`,`reverse`);return I(t.rank===1,(function(){return`Error in reverse1D: x must be rank 1 but got rank `+t.rank+`.`})),eu(t,0)}}),nu=K({reverse2d_:function(e,t){var n=G(e,`x`,`reverse`);return I(n.rank===2,(function(){return`Error in reverse2D: x must be rank 2 but got rank `+n.rank+`.`})),eu(n,t)}}),ru=K({reverse3d_:function(e,t){var n=G(e,`x`,`reverse`);return I(n.rank===3,(function(){return`Error in reverse3D: x must be rank 3 but got rank `+n.rank+`.`})),eu(n,t)}}),iu=K({reverse4d_:function(e,t){var n=G(e,`x`,`reverse`);return I(n.rank===4,(function(){return`Error in reverse4D: x must be rank 4 but got rank `+n.rank+`.`})),eu(n,t)}});function au(e,t,n,r,i,a){var o=G(e,`x`,`maxPool`),s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),r??=[1,1],I(s.rank===4,(function(){return`Error in maxPool: input must be rank 4 but got rank `+s.rank+`.`})),I(ji(n,r),(function(){return`Error in maxPool: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+r+`'`})),a!=null&&I(ce(i),(function(){return`Error in maxPool: pad must be an integer when using, dimRoundingMode `+a+` but got pad `+i+`.`}));var l=xi(s.shape,t,n,r,i,a);if(l.filterWidth===1&&l.filterHeight===1&&z(l.inShape,l.outShape))return o.clone();var u=[s],d=V.runKernelFunc((function(e,t){var n=e.maxPool(s,l);return t([s,n]),n}),{x:s},(function(e,a){var o=a[0],s=a[1];return{x:function(){return function(e,t,n,r,i,a,o,s){var c=G(e,`dy`,`maxPoolBackprop`),l=G(t,`input`,`maxPoolBackprop`),u=G(n,`output`,`maxPoolBackprop`);I(l.rank===c.rank,(function(){return`Rank of input (`+l.rank+`) does not match rank of dy (`+c.rank+`)`})),a??=[1,1],I(ji(i,a),(function(){return`Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides `+i+` and dilations '`+a+`'`})),I(c.rank===4,(function(){return`Error in maxPoolBackprop: dy must be rank 4 but got rank `+c.rank+`.`})),I(l.rank===4,(function(){return`Error in maxPoolBackprop: input must be rank 4 but got rank `+l.rank+`.`})),s!=null&&I(ce(o),(function(){return`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode `+s+` but got pad `+o+`.`}));var d=xi(l.shape,r,i,a,o,s);return V.runKernelFunc((function(e){return e.maxPoolBackprop(c,l,u,d)}),{$dy:c,$input:l})}(e,o,s,t,n,r,i)}}}),`MaxPool`,l,u);return c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function ou(e,t,n,r,i,a){var o=G(e,`x`,`avgPool`,`float32`);r??=[1,1],I(ji(n,r),(function(){return`Error in avgPool: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+r+`'`}));var s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(s.rank===4,(function(){return`Error in avgPool: x must be rank 4 but got rank `+s.rank+`.`})),a!=null&&I(ce(i),(function(){return`Error in avgPool: pad must be an integer when using, dimRoundingMode `+a+` but got pad `+i+`.`}));var l=xi(s.shape,t,n,r,i,a);if(l.filterWidth===1&&l.filterHeight===1&&z(l.inShape,l.outShape))return o.clone();var u=V.runKernelFunc((function(e){return e.avgPool(s,l)}),{x:s},(function(e){return{x:function(){return function(e,t,n,r,i,a){var o=G(e,`dy`,`avgPoolBackprop`),s=G(t,`input`,`avgPoolBackprop`);I(s.rank===o.rank,(function(){return`Rank of input (`+s.rank+`) does not match rank of dy (`+o.rank+`)`})),i??=[1,1],I(ji(r,i),(function(){return`Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+i+`'`}));var c=s,l=o,u=!1;s.rank===3&&(u=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(l.rank===4,(function(){return`Error in avgPoolBackprop: dy must be rank 4 but got rank `+l.rank+`.`})),I(c.rank===4,(function(){return`Error in avgPoolBackprop: input must be rank 4 but got rank `+c.rank+`.`}));var d=xi(c.shape,n,r,i,a),f=V.runKernelFunc((function(e){return e.avgPoolBackprop(l,c,d)}),{dy4D:l,input4D:c});return u?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(e,s,t,n,r,i)}}}),`AvgPool`,l);return u=u.cast(o.dtype),c?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}var su=K({maxPool_:function(e,t,n,r,i){return au(e,t,n,1,r,i)}}),cu=K({avgPool_:function(e,t,n,r,i){return ou(e,t,n,1,r,i)}}),lu=K({pool_:function(e,t,n,r,i,a){i??=[1,1],a??=1,r===0&&(r=`valid`);var o=G(e,`x`,`maxPool`),s=o,c=!1;o.rank===3&&(c=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(ji(a,i),(function(){return`Error in pool: Either strides or dilations must be 1. Got strides `+a+` and dilations '`+i+`'`}));var l,u=xi(s.shape,t,a,i,r),d=[u.dilationHeight,u.dilationWidth];l=r===`same`?function(e,t){var n=e.map((function(e,n){return e+(e-1)*(t[n]-1)})).map((function(e){return e-1})),r=n.map((function(e){return Math.floor(e/2)})),i=n.map((function(e,t){return e-r[t]}));return n.map((function(e,t){return[r[t],i[t]]}))}([u.filterHeight,u.filterWidth],d):[[0,0],[0,0]];var f=d[0]===1&&d[1]===1,p=function(e,t,n){var r=n.map((function(e){return e[0]})),i=n.map((function(e){return e[1]})),a=e.concat(r,i),o=t.map((function(e,t){return(e-a[t]%e)%e})),s=i.map((function(e,t){return e+o[t]}));return[t.map((function(e,t){return[r[t],s[t]]})),t.map((function(e,t){return[0,o[t]]}))]}([u.inHeight,u.inWidth],d,l),m=p[0],h=p[1],g=f?r:`valid`,_=f?s:Vr(s,d,m),v=(n===`avg`?function(){return ou(_,t,a,1,g)}:function(){return au(_,t,a,1,g)})(),y=f?v:xr(v,d,h);return c?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}}),uu=K({maxPool3d_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NDHWC`);var s=G(e,`x`,`maxPool3d`),c=s,l=!1;s.rank===4&&(l=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),o??=[1,1,1],I(c.rank===5,(function(){return`Error in maxPool3d: x must be rank 5 but got rank `+c.rank+`.`})),I(a===`NDHWC`,(function(){return`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of `+a})),I(ji(n,o),(function(){return`Error in maxPool3d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+o+`'`})),i!=null&&I(ce(r),(function(){return`Error in maxPool3d: pad must be an integer when using, dimRoundingMode `+i+` but got pad `+r+`.`}));var u=Si(c.shape,t,n,o,r,i,a),d=V.runKernelFunc((function(e,t){var n=e.maxPool3d(c,u);return t([c,n]),n}),{x:c},(function(e,a){var s=a[0],c=a[1];return{x:function(){return function(e,t,n,r,i,a,o,s){var c=G(e,`dy`,`maxPool3dBackprop`),l=G(t,`input`,`maxPool3dBackprop`),u=G(n,`output`,`maxPool3dBackprop`),d=c,f=l,p=u,m=!1;l.rank===4&&(m=!0,d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),f=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),I(d.rank===5,(function(){return`Error in maxPool3dBackprop: dy must be rank 5 but got rank `+d.rank+`.`})),I(f.rank===5,(function(){return`Error in maxPool3dBackprop: input must be rank 5 but got rank `+f.rank+`.`})),I(p.rank===5,(function(){return`Error in maxPool3dBackprop: output must be rank 5 but got rank `+p.rank+`.`})),a??=[1,1,1],I(ji(i,a),(function(){return`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides `+i+` and dilations '`+a+`'`})),s!=null&&I(ce(o),(function(){return`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode `+s+` but got pad `+o+`.`}));var h=Si(f.shape,r,i,a,o,s),g=V.runKernelFunc((function(e){return e.maxPool3dBackprop(d,f,p,h)}),{dy5D:d,input5D:f});return m?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(e,s,c,t,n,o,r,i)}}}));return l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),du=K({avgPool3d_:function(e,t,n,r,i,a,o){a===void 0&&(a=`NDHWC`);var s=G(e,`x`,`avgPool3d`,`float32`),c=s,l=!1;s.rank===4&&(l=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),o??=[1,1,1],I(c.rank===5,(function(){return`Error in avgPool3d: x must be rank 5 but got rank `+c.rank+`.`})),I(a===`NDHWC`,(function(){return`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of `+a})),I(ji(n,o),(function(){return`Error in avgPool3d: Either strides or dilations must be 1. Got strides `+n+` and dilations '`+o+`'`})),i!=null&&I(ce(r),(function(){return`Error in avgPool3d: pad must be an integer when using, dimRoundingMode `+i+` but got pad `+r+`.`}));var u=Si(c.shape,t,n,o,r,i,a),d=V.runKernelFunc((function(e){return e.avgPool3d(c,u)}),{x:c},(function(e){return{x:function(){return function(e,t,n,r,i,a,o){var s=G(e,`dy`,`avgPool3dBackprop`),c=G(t,`input`,`avgPool3dBackprop`),l=s,u=c,d=!1;c.rank===4&&(d=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),u=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),I(l.rank===5,(function(){return`Error in avgPool3dBackprop: dy must be rank 5 but got rank `+l.rank+`.`})),I(u.rank===5,(function(){return`Error in avgPool3dBackprop: input must be rank 5 but got rank `+u.rank+`.`})),i??=[1,1,1],I(ji(r,i),(function(){return`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+i+`'`})),o!=null&&I(ce(a),(function(){return`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode `+o+` but got pad `+a+`.`}));var f=Si(u.shape,n,r,i,a,o),p=V.runKernelFunc((function(e){return e.avgPool3dBackprop(l,u,f)}),{dy5D:l,input5D:u});return d?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}(e,c,t,n,o,r,i)}}}));return d=d.cast(c.dtype),l?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}}),fu=K({slice_:function(e,t,n){var r,i,a=G(e,`x`,`slice`);if(a.rank===0)throw Error(`Slicing scalar is not possible`);(r=typeof t==`number`?[t].concat(Array(a.rank-1).fill(0)):t.length<a.rank?t.concat(Array(a.rank-t.length).fill(0)):t.slice()).forEach((function(e){I(e!==-1,(function(){return`slice() does not support negative begin indexing.`}))})),i=(i=n==null?Array(a.rank).fill(-1):typeof n==`number`?[n].concat(Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(Array(a.rank-n.length).fill(-1)):n).map((function(e,t){return e>=0?e:(I(e===-1,(function(){return`Negative size values should be exactly -1 but got `+e+` for the slice() size at index `+t+`.`})),a.shape[t]-r[t])})),ai(a,r,i);var o=a.shape,s={begin:r,size:i};return V.runKernelFunc((function(e){return e.slice(a,r,i)}),{x:a},(function(e){for(var t=[],n=0;n<e.rank;n++)t.push([r[n],o[n]-r[n]-i[n]]);return{x:function(){return e.pad(t)}}}),`Slice`,s)}}),pu=K({slice1d_:function(e,t,n){var r=G(e,`x`,`slice1d`);return I(r.rank===1,(function(){return`slice1d expects a rank-1 tensor, but got a rank-`+r.rank+` tensor`})),fu(r,[t],[n])}}),mu=K({slice2d_:function(e,t,n){var r=G(e,`x`,`slice2d`);return I(r.rank===2,(function(){return`slice2d expects a rank-2 tensor, but got a rank-`+r.rank+` tensor`})),fu(r,t,n)}}),hu=K({slice3d_:function(e,t,n){var r=G(e,`x`,`slice3d`);return I(r.rank===3,(function(){return`slice3d expects a rank-3 tensor, but got a rank-`+r.rank+` tensor`})),fu(r,t,n)}}),gu=K({slice4d_:function(e,t,n){var r=G(e,`x`,`slice4d`);return I(r.rank===4,(function(){return`slice4d expects a rank-4 tensor, but got a rank-`+r.rank+` tensor`})),fu(r,t,n)}});function _u(e,t,n,r,i){return t.rank<n.rank&&(t=t.reshape(An(t.shape,r))),e.rank<n.rank&&(e=e.reshape(An(e.shape,r))),{x:function(){var r=e.mul(n.equal(t).cast(e.dtype));return i==null?r:r.transpose(i)}}}var vu=K({all_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`all`,`bool`),i=me(t,r.shape),a=i,o=Mn(a,r.rank);o!=null&&(r=r.transpose(o),a=Pn(a.length,r.rank));var s=V.runKernelFunc((function(e){return e.all(r,a)}),{$x:r});if(n){var c=An(s.shape,i);return s.reshape(c)}return s}}),yu=K({any_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`any`,`bool`),i=me(t,r.shape),a=i,o=Mn(a,r.rank);o!=null&&(r=r.transpose(o),a=Pn(a.length,r.rank));var s=V.runKernelFunc((function(e){return e.any(r,a)}),{$x:r});if(n){var c=An(s.shape,i);return s.reshape(c)}return s}}),bu=K({argMax_:function(e,t){t===void 0&&(t=0);var n=G(e,`x`,`argMax`);t??=0;var r=me(t,n.shape),i=Mn(r,n.rank);i!=null&&(n=n.transpose(i),r=Pn(r.length,n.rank));var a={axis:r[0]},o=[n];return V.runKernelFunc((function(e,t){var i=e.argMax(n,r[0]);return t([n]),i}),{x:n},(function(e,t){var n=t[0];return{x:function(){return tr(n)}}}),`ArgMax`,a,o)}}),xu=K({argMin_:function(e,t){t===void 0&&(t=0);var n=G(e,`x`,`argMin`);t??=0;var r=me(t,n.shape),i=Mn(r,n.rank);return i!=null&&(n=n.transpose(i),r=Pn(r.length,n.rank)),V.runKernelFunc((function(e,t){var i=e.argMin(n,r[0]);return t([n]),i}),{$x:n},(function(e,t){var n=t[0];return{$x:function(){return tr(n)}}}))}}),Su=K({logSumExp_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`logSumExp`),i=me(t,r.shape),a=r.max(i,!0),o=r.sub(a).exp().sum(i).log(),s=a.reshape(o.shape).add(o);if(n){var c=An(s.shape,i);return s.reshape(c)}return s}}),Cu=K({max_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`max`),i=r,a=me(t,r.shape),o=a,s=Mn(o,r.rank);s!=null&&(r=r.transpose(s),o=Pn(o.length,r.rank));var c=[r],l=V.runKernelFunc((function(e,t){var n=e.max(r,o);return t([i,n]),n}),{x:r},(function(e,t){return _u(e,t[1],t[0],a,s)}),`Max`,{axes:o},c,[!0]);if(n){var u=An(l.shape,a);l=l.reshape(u)}return l}}),wu=K({mean_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`mean`),i=me(t,r.shape),a=R(kn(r.shape,i)[1]);return pi((function(e){var r=q(a);return{value:(r.dtype===e.dtype?e:e.cast(r.dtype)).div(r).sum(t,n),gradFunc:function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(Yn(e.shape,`float32`)).div(a)}}}))(r)}}),Tu=K({min_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`min`),i=r,a=me(t,r.shape),o=a,s=Mn(o,r.rank);s!=null&&(r=r.transpose(s),o=Pn(o.length,r.rank));var c=[r],l=V.runKernelFunc((function(e,t){var n=e.min(r,o);return t([i,n]),n}),{x:r},(function(e,t){return _u(e,t[1],t[0],a,s)}),`Min`,{axes:o},c,[!0]);if(n){var u=An(l.shape,a);l=l.reshape(u)}return l}}),Eu=K({moments_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=me(t,(e=G(e,`x`,`moments`)).shape),i=e.mean(r,n),a=i.shape;return n||(a=An(i.shape,r)),{mean:i,variance:e.toFloat().sub(i.reshape(a)).square().mean(r,n)}}}),Du=K({sum_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`sum`);r.dtype===`bool`&&(r=r.toInt());var i=me(t,r.shape);return pi((function(e){var t=Mn(i,e.rank),r=i,a=e;t!=null&&(a=e.transpose(t),r=Pn(r.length,e.rank));var o=function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(Yn(e.shape,`float32`))},s={axes:r},c=V.runKernelFunc((function(e){return e.sum(a,r)}),{x:a},(function(e){return{x:function(){return o(e)}}}),`Sum`,s);if(n){var l=An(c.shape,i);c=c.reshape(l)}return{value:c,gradFunc:o}}))(r)}}),Ou=K({prod_:function(e,t,n){t===void 0&&(t=null),n===void 0&&(n=!1);var r=G(e,`x`,`prod`);r.dtype===`bool`&&(r=r.toInt());var i=me(t,r.shape),a=Mn(i,r.rank),o=i,s=r;a!=null&&(s=r.transpose(a),o=Pn(o.length,r.rank));var c=V.runKernelFunc((function(e){return e.prod(s,o)}),{permutedX:s});if(n){var l=An(c.shape,i);c=c.reshape(l)}return c}}),ku=K({elu_:function(e){var t=G(e,`x`,`elu`);return V.runKernelFunc((function(e,n){var r=e.elu(t);return n([r]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return V.runKernelFunc((function(t){return t.eluDer(e,n)}),{dy:e,y:n})}}}))}}),Au=K({leakyRelu_:function(e,t){t===void 0&&(t=.2);var n=G(e,`x`,`leakyRelu`);return sl(q(t).mul(n),n)}}),ju=K({prelu_:function(e,t){var n=G(e,`x`,`prelu`),r=G(t,`alpha`,`prelu`);return V.runKernelFunc((function(e,t){var i=e.prelu(n,r);return t([n,r]),i}),{x:n,alpha:r},(function(e,t){var n=t[0],r=t[1],i=n.greater(0);return{x:function(){return Zc(i,e,e.mul(r))},alpha:function(){var t=Zc(i,tr(e),e.mul(n)),a=yi(r.shape,e.shape);return a.length>0&&(t=t.sum(a)),t.reshape(r.shape)}}}),`Prelu`)}}),Mu=K({relu_:function(e){var t=G(e,`x`,`relu`);return t.dtype===`bool`?t.toInt():V.runKernelFunc((function(e,n){var r=e.relu(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mulStrict(n.step().toFloat())}}}),`Relu`)}}),Nu=K({relu6_:function(e){var t=G(e,`x`,`relu6`);return t.dtype===`bool`?t.toInt():V.runKernelFunc((function(e,n){var r=e.relu6(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return e.mulStrict(r.toFloat())}}}),`Relu6`)}}),Pu=K({selu_:function(e){var t=G(e,`x`,`selu`);return V.runKernelFunc((function(e,n){var r=e.selu(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){var t=n.greater(q(0)),r=q(gs),i=q(_s);return Zc(t,e.mul(i),e.mul(r).mul(n.toFloat().exp()))}}}))}}),Fu=K({transpose_:function(e,t){var n=G(e,`x`,`transpose`);if(t??=n.shape.map((function(e,t){return t})).reverse(),I(n.rank===t.length,(function(){return`Error in transpose: rank of input `+n.rank+` must match length of perm `+t+`.`})),t.forEach((function(e){I(e>=0&&e<n.rank,(function(){return`All entries in 'perm' must be between 0 and `+(n.rank-1)+` but got `+t}))})),n.rank<=1)return n.clone();var r={perm:t};return V.runKernelFunc((function(e){return e.transpose(n,t)}),{x:n},(function(e){var n=Nn(t);return{x:function(){return e.transpose(n)}}}),`Transpose`,r)}}),Iu=K({localResponseNormalization_:function(e,t,n,r,i){t===void 0&&(t=5),n===void 0&&(n=1),r===void 0&&(r=1),i===void 0&&(i=.5);var a=G(e,`x`,`localResponseNormalization`);I(a.rank===4||a.rank===3,(function(){return`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
3740
|
+
rank `+a.rank+`.`})),I(ce(t),(function(){return`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius `+t+`.`}));var o=a,s=!1;a.rank===3&&(s=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var c=V.runKernelFunc((function(e,a){var s=e.localResponseNormalization4D(o,t,n,r,i);return a([o,s]),s}),{x4D:o},(function(e,a){var o=a[0],s=a[1];return{x4D:function(){return V.runKernelFunc((function(a){return a.LRNGrad(e,o,s,t,n,r,i)}),{})}}}));return s?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),Lu=K({norm_:function(e,t,n,r){t===void 0&&(t=`euclidean`),n===void 0&&(n=null),r===void 0&&(r=!1);var i=function e(t,n,r){if(r===void 0&&(r=null),t.rank===0)return t.abs();if(t.rank!==1&&r===null)return e(t.reshape([-1]),n,r);if(t.rank===1||typeof r==`number`||Array.isArray(r)&&r.length===1){if(n===1)return t.abs().sum(r);if(n===1/0)return t.abs().max(r);if(n===-1/0)return t.abs().min(r);if(n===`euclidean`||n===2)return t.abs().pow(q(2,`int32`)).sum(r).sqrt();throw Error(`Error in norm: invalid ord value: `+n)}if(Array.isArray(r)&&r.length===2){if(n===1)return t.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return t.abs().sum(r[1]).max(r[0]);if(n===-1/0)return t.abs().sum(r[1]).min(r[0]);if(n===`fro`||n===`euclidean`)return t.square().sum(r).sqrt();throw Error(`Error in norm: invalid ord value: `+n)}throw Error(`Error in norm: invalid axis: `+r)}(e=G(e,`x`,`norm`),t,n),a=i.shape;if(r){var o=me(n,e.shape);a=An(i.shape,o)}return i.reshape(a)}}),Ru=K({basicLSTMCell_:function(e,t,n,r,i,a){var o=G(e,`forgetBias`,`basicLSTMCell`),s=G(t,`lstmKernel`,`basicLSTMCell`),c=G(n,`lstmBias`,`basicLSTMCell`),l=G(r,`data`,`basicLSTMCell`),u=G(i,`c`,`basicLSTMCell`),d=G(a,`h`,`basicLSTMCell`),f=l.concat(d,1).matMul(s).add(c),p=f.shape[0],m=f.shape[1]/4,h=[p,m],g=f.slice([0,0],h),_=f.slice([0,m],h),v=f.slice([0,2*m],h),y=f.slice([0,3*m],h),b=g.sigmoid().mulStrict(_.tanh()).addStrict(u.mulStrict(o.add(v).sigmoid()));return[b,b.tanh().mulStrict(y.sigmoid())]}}),zu=K({multiRNNCell_:function(e,t,n,r){for(var i=G(t,`data`,`multiRNNCell`),a=En(n,`c`,`multiRNNCell`),o=En(r,`h`,`multiRNNCell`),s=i,c=[],l=0;l<e.length;l++){var u=e[l](s,a[l],o[l]);c.push(u[0]),c.push(u[1]),s=u[1]}var d=[],f=[];for(l=0;l<c.length;l+=2)d.push(c[l]),f.push(c[l+1]);return[d,f]}}),Bu=K({movingAverage_:function(e,t,n,r,i){i===void 0&&(i=!0);var a=G(e,`v`,`movingAverage`),o=G(t,`x`,`movingAverage`),s=G(n,`decay`,`movingAverage`);ut(a,o),I(z(a.shape,o.shape),(function(){return`Shape mismatch in v and x`}));var c=q(1),l=c.sub(s),u=o.sub(a).mul(l);if(i){I(r!=null,(function(){return`When using zeroDebias: true, step is required.`}));var d=G(r,`step`,`movingAverage`);u=u.div(c.sub(hl(s,d)))}return a.add(u)}}),Vu=K({stridedSlice_:function(e,t,n,r,i,a,o,s,c){if(i===void 0&&(i=0),a===void 0&&(a=0),o===void 0&&(o=0),s===void 0&&(s=0),c===void 0&&(c=0),r??=Array(t.length),o!==0)throw Error(`ellipsis mask is not yet supported`);var l=G(e,`x`,`stridedSlice`),u=oi(s),d=l.shape.slice();u.forEach((function(e){t[e]=0,n[e]=1,d.splice(e,0,1)})),l=l.reshape(d);for(var f=0;f<l.rank;f++)t[f]=ci(i,t,r,l.shape,f),n[f]=li(a,n,r,l.shape,f),r[f]=r[f]||1;var p=oi(c);p.forEach((function(e){n[e]=t[e]+1,r[e]=1}));var m=si(t,n,r),h=m.filter((function(e,t){return p.indexOf(t)===-1}));return r.every((function(e){return e===1}))?fu(l,t,m).reshape(h):V.runKernelFunc((function(e){return e.stridedSlice(l,t,n,r)}),{$x:l}).reshape(h)}}),Hu=K({topk_:function(e,t,n){t===void 0&&(t=1),n===void 0&&(n=!0);var r=G(e,`x`,`topk`);if(r.rank===0)throw Error(`topk() expects the input to be of rank 1 or higher`);var i=r.shape[r.shape.length-1];if(t>i)throw Error(`'k' passed to topk() must be <= the last dimension (`+i+`) but got `+t);var a=V.runKernelFunc((function(e){return e.topk(r,t,n)}),{$x:r});return{values:a[0],indices:a[1]}}}),Uu=K({scatterND_:function(e,t,n){var r=G(e,`indices`,`scatterND`,`int32`),i=G(t,`updates`,`scatterND`);return ri(i,r,n),V.runKernelFunc((function(e){return e.scatterND(r,i,n)}),{indices:r,updates:i},null,`ScatterNd`,{shape:n})}}),Wu=K({fft_:function(e){I(e.dtype===`complex64`,(function(){return`The dtype for tf.spectral.fft() must be complex64 but got `+e.dtype+`.`}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return V.runKernelFunc((function(e){return e.fft(r)}),{input:e}).reshape(e.shape)}}),Gu=K({ifft_:function(e){I(e.dtype===`complex64`,(function(){return`The dtype for tf.spectral.ifft() must be complex64 but got `+e.dtype+`.`}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return V.runKernelFunc((function(e){return e.ifft(r)}),{input:e}).reshape(e.shape)}}),Ku=K({rfft_:function(e,t){I(e.dtype===`float32`,(function(){return`The dtype for rfft() must be real value but got `+e.dtype}));var n,r=e.shape[e.shape.length-1],i=e.size/r;if(t!=null&&t<r){var a=e.shape.map((function(e){return 0})),o=e.shape.map((function(e){return e}));o[e.shape.length-1]=t,n=e.slice(a,o),r=t}else if(t!=null&&t>r){var s=e.shape.map((function(e){return e}));s[e.shape.length-1]=t-r,n=e.concat(Xn(s),e.shape.length-1),r=t}else n=e;var c=n.zerosLike(),l=Wu(Ln(n,c).as2D(i,r)),u=Math.floor(r/2)+1,d=Rn(l),f=zn(l),p=d.split([u,r-u],d.shape.length-1),m=f.split([u,r-u],f.shape.length-1),h=n.shape.slice();return h[n.shape.length-1]=u,Ln(p[0],m[0]).reshape(h)}}),qu=K({irfft_:function(e){var t=e.shape[e.shape.length-1],n=e.size/t;if(t<=2){var r=e.as2D(n,t),i=Gu(r);return Rn(i)}var a=[n,2*(t-1)],o=Rn(e).as2D(n,t),s=zn(e).as2D(n,t),c=o.slice([0,1],[n,t-2]).reverse(1),l=s.slice([0,1],[n,t-2]).reverse(1).mul(q(-1));return r=Ln(o.concat(c,1),s.concat(l,1)).as2D(a[0],a[1]),i=Gu(r),Rn(i)}}),Ju=Object.freeze({fft:Wu,ifft:Gu,rfft:Ku,irfft:qu}),Yu=K({sparseToDense_:function(e,t,n,r){r===void 0&&(r=0);var i=G(e,`sparseIndices`,`sparseToDense`,`int32`),a=G(t,`sparseValues`,`sparseToDense`),o=G(r,`defaultValue`,`sparseToDense`,a.dtype);return function(e,t,n,r){if(e.dtype!==`int32`)throw Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was `+e.dtype+`.`);if(e.rank>2)throw Error(`sparseIndices should be a scalar, vector, or matrix, but got shape `+e.shape+`.`);var i=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw Error(`outputShape has incorrect number of elements:, `+n.length+`, should be: `+a+`.`);var o=t.size;if(t.rank!==0&&(t.rank!==1||o!==i))throw Error(`sparseValues has incorrect shape `+t.shape+`, should be [] or [`+i+`]`);if(t.dtype!==r.dtype)throw Error(`sparseValues.dtype must match defaultValues.dtype`)}(i,a,n,o),V.runKernelFunc((function(e){return e.sparseToDense(i,a,n,o)}),{$sparseIndices:i,$sparseValues:a,$defaultValue:o})}}),Xu=K({gatherND_:function(e,t){var n=G(t,`indices`,`gatherND`,`int32`),r=G(e,`x`,`gatherND`);return V.runKernelFunc((function(e){return e.gatherND(r,n)}),{x:r,indices:n},null,`GatherNd`)}}),Zu=K({diag_:function(e){var t=G(e,`x`,`diag`).flatten(),n=e.shape.concat(e.shape);return V.runKernelFunc((function(e){return e.diag(t)}),{$x:t}).reshape(n)}}),Qu=K({dropout_:function(e,t,n,r){var i=G(e,`x`,`dropout`);if(I(i.dtype===`float32`,(function(){return`x has to be a floating point tensor since it's going to be scaled, but got a `+i.dtype+` tensor instead.`})),I(t>=0&&t<1,(function(){return`rate must be a float in the range [0, 1), but got `+t+`.`})),t===0)return e instanceof $e?i.clone():i;var a=function(e,t){if(t==null)return e.shape.slice();if(z(e.shape,t))return t;if(e.shape.length===t.length){for(var n=[],r=0;r<e.shape.length;r++)t[r]==null&&e.shape[r]!=null?n.push(e.shape[r]):n.push(t[r]);return n}return t}(i,n),o=1-t,s=zr(a,0,1,`float32`,r).add(o).floor().div(o);return i.mul(s)}});function $u(e,t,n){for(var r=1-e%2,i=new Float32Array(e),a=0;a<e;++a){var o=2*Math.PI*a/(e+r-1);i[a]=t-n*Math.cos(o)}return Hn(i,`float32`)}var ed=K({hannWindow_:function(e){return $u(e,.5,.5)}}),td=K({hammingWindow_:function(e){return $u(e,.54,.46)}}),nd=K({frame_:function(e,t,n,r,i){r===void 0&&(r=!1),i===void 0&&(i=0);for(var a=0,o=[];a+t<=e.size;)o.push(fu(e,a,t)),a+=n;if(r)for(;a<e.size;){var s=a+t-e.size,c=nr([fu(e,a,t-s),Zn([s],i)]);o.push(c),a+=n}return o.length===0?Un([],[0,t]):nr(o).as2D(o.length,t)}}),rd=K({stft_:function(e,t,n,r,i){var a;i===void 0&&(i=ed),r??=(a=t,Math.floor(2**Math.ceil(Math.log(a)/Math.log(2))));for(var o=nd(e,t,n),s=pl(o,i(t)),c=[],l=0;l<o.shape[0];l++)c.push(Ku(s.slice([l,0],[1,t]),r));return nr(c)}}),id=Object.freeze({hannWindow:ed,hammingWindow:td,frame:nd,stft:rd}),ad,od=function(e,t,n){return n===void 0&&(n=1),w(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,d,f,p,m,h,g;return T(this,(function(_){switch(_.label){case 0:return r=G(e,`predictions`,`inTopK`),i=G(t,`targets`,`inTopK`),I(r.rank>1,(function(){return`inTopK() expects the predictions to be of rank 2 or higher, but got `+r.rank})),I(r.rank-1===i.rank,(function(){return`predictions rank should be 1 larger than targets rank, but got predictions rank `+r.rank+` and targets rank `+i.rank})),L(r.shape.slice(0,r.shape.length-1),i.shape,`predictions's shape should be align with the targets' shape, except the last dimension.`),a=r.shape[r.shape.length-1],I(n>0&&n<=a,(function(){return`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (`+a+`), but got `+n})),[4,r.data()];case 1:return o=_.sent(),[4,i.data()];case 2:for(s=_.sent(),c=[o.length/a,a],u=c[1],d=ge(`bool`,l=c[0]),f=0;f<l;f++){for(p=f*u,m=o.subarray(p,p+u),h=[],g=0;g<m.length;g++)h.push({value:m[g],index:g});for(h.sort((function(e,t){return t.value-e.value})),d[f]=0,g=0;g<n;g++)if(h[g].index===s[f]){d[f]=1;break}}return e!==r&&r.dispose(),t!==i&&i.dispose(),[2,Bn(d,i.shape,`bool`)]}}))}))};(function(e){e[e.NONE=0]=`NONE`,e[e.MEAN=1]=`MEAN`,e[e.SUM=2]=`SUM`,e[e.SUM_BY_NONZERO_WEIGHTS=3]=`SUM_BY_NONZERO_WEIGHTS`})(ad||={});var sd=K({absoluteDifference_:function(e,t,n,r){r===void 0&&(r=ad.SUM_BY_NONZERO_WEIGHTS);var i=G(e,`labels`,`absoluteDifference`),a=G(t,`predictions`,`absoluteDifference`),o=null;return n!=null&&(o=G(n,`weights`,`absoluteDifference`)),L(i.shape,a.shape,`Error in absoluteDifference: `),cd(i.sub(a).abs(),o,r)}}),cd=K({computeWeightedLoss_:function(e,t,n){n===void 0&&(n=ad.SUM_BY_NONZERO_WEIGHTS);var r=G(e,`losses`,`computeWeightedLoss`),i=null;t!=null&&(i=G(t,`weights`,`computeWeightedLoss`));var a=i==null?r:r.mul(i);if(n===ad.NONE)return a;if(n===ad.SUM)return a.sum();if(n===ad.MEAN){if(i==null)return a.mean();var o=r.size/i.size,s=a.sum().div(i.sum());return o>1?s.div(q(o)):s}if(n===ad.SUM_BY_NONZERO_WEIGHTS){if(i==null)return a.sum().div(q(r.size));var c=i.mul(Yn(r.shape)).notEqual(q(0)).sum().toFloat();return a.sum().div(c)}throw Error(`Unknown reduction: `+n)}}),ld=K({cosineDistance_:function(e,t,n,r,i){i===void 0&&(i=ad.SUM_BY_NONZERO_WEIGHTS);var a=G(e,`labels`,`cosineDistance`),o=G(t,`predictions`,`cosineDistance`),s=null;return r!=null&&(s=G(r,`weights`,`cosineDistance`)),L(a.shape,o.shape,`Error in cosineDistance: `),cd(q(1).sub(a.mul(o).sum(n,!0)),s,i)}}),ud=K({hingeLoss_:function(e,t,n,r){r===void 0&&(r=ad.SUM_BY_NONZERO_WEIGHTS);var i=G(e,`labels`,`hingeLoss`),a=G(t,`predictions`,`hingeLoss`),o=null;n!=null&&(o=G(n,`weights`,`hingeLoss`)),L(i.shape,a.shape,`Error in hingeLoss: `);var s=q(1);return i=q(2).mul(i).sub(s),cd(s.sub(i.mul(a)).relu(),o,r)}}),dd=K({huberLoss_:function(e,t,n,r,i){r===void 0&&(r=1),i===void 0&&(i=ad.SUM_BY_NONZERO_WEIGHTS);var a=G(e,`labels`,`huberLoss`),o=G(t,`predictions`,`huberLoss`),s=null;n!=null&&(s=G(n,`weights`,`huberLoss`)),L(a.shape,o.shape,`Error in huberLoss: `);var c=q(r),l=o.sub(a).abs(),u=ll(l,c),d=l.sub(u);return cd(q(.5).mul(u.square()).add(c.mul(d)),s,i)}}),fd=K({logLoss_:function(e,t,n,r,i){r===void 0&&(r=1e-7),i===void 0&&(i=ad.SUM_BY_NONZERO_WEIGHTS);var a=G(e,`labels`,`logLoss`),o=G(t,`predictions`,`logLoss`),s=null;n!=null&&(s=G(n,`weights`,`logLoss`)),L(a.shape,o.shape,`Error in logLoss: `);var c=q(1),l=q(r);return cd(a.mul(o.add(l).log()).neg().sub(c.sub(a).mul(c.sub(o).add(l).log())),s,i)}}),pd=K({meanSquaredError_:function(e,t,n,r){r===void 0&&(r=ad.SUM_BY_NONZERO_WEIGHTS);var i=G(e,`labels`,`meanSquaredError`),a=G(t,`predictions`,`meanSquaredError`),o=null;return n!=null&&(o=G(n,`weights`,`meanSquaredError`)),L(i.shape,a.shape,`Error in meanSquaredError: `),cd(i.squaredDifference(a),o,r)}}),md=K({sigmoidCrossEntropy_:function(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=ad.SUM_BY_NONZERO_WEIGHTS);var a=G(e,`multiClassLabels`,`sigmoidCrossEntropy`),o=G(t,`logits`,`sigmoidCrossEntropy`),s=null;if(n!=null&&(s=G(n,`weights`,`sigmoidCrossEntropy`)),L(a.shape,o.shape,`Error in sigmoidCrossEntropy: `),r>0){var c=q(r),l=q(1),u=q(.5);a=a.mul(l.sub(c)).add(u.mul(c))}return cd(function(e,t){var n=G(e,`labels`,`sigmoidCrossEntropyWithLogits`),r=G(t,`logits`,`sigmoidCrossEntropyWithLogits`);L(n.shape,r.shape,`Error in sigmoidCrossEntropyWithLogits: `);var i=r.relu(),a=r.mul(n),o=r.abs().neg().exp().log1p();return i.sub(a).add(o)}(a,o),s,i)}}),hd=K({softmaxCrossEntropy_:function(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=ad.SUM_BY_NONZERO_WEIGHTS);var a=G(e,`onehotLabels`,`softmaxCrossEntropy`),o=G(t,`logits`,`softmaxCrossEntropy`),s=null;if(n!=null&&(s=G(n,`weights`,`softmaxCrossEntropy`)),L(a.shape,o.shape,`Error in softmaxCrossEntropy: `),r>0){var c=q(r),l=q(1),u=q(a.shape[1]);a=a.mul(l.sub(c)).add(c.div(u))}return cd(function(e,t,n){if(n===void 0&&(n=-1),n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank `+t.rank+` and dim was `+n);return pi((function(e,t,r){var i=t.logSumExp([n],!0),a=t.toFloat().sub(i);return r([e,a]),{value:a.mul(e).neg().sum([n]),gradFunc:function(e,t){var r=t[0],i=t[1],a=An(e.shape,[n]);return[e.reshape(a).mul(r.toFloat().sub(i.exp())),e.reshape(a).mul(i.exp().sub(r.toFloat()))]}}}))(e,t)}(a,o),s,i)}}),gd=Object.freeze({get Reduction(){return ad},absoluteDifference:sd,computeWeightedLoss:cd,cosineDistance:ld,hingeLoss:ud,huberLoss:dd,logLoss:fd,meanSquaredError:pd,sigmoidCrossEntropy:md,softmaxCrossEntropy:hd});function _d(e,t){return t===void 0&&(t=!1),V.tidy((function(){if(e.shape.length!==2)throw Error(`qr2d() requires a 2D Tensor, but got a `+e.shape.length+`D Tensor.`);for(var n=e.shape[0],r=e.shape[1],i=Or(n),a=e.clone(),o=Un([[1]],[1,1]),s=o.clone(),c=n>=r?r:n,l=function(e){var t,c=a,l=s,u=i;t=V.tidy((function(){var t=a.slice([e,e],[n-e,1]),c=t.norm(),l=a.slice([e,e],[1,1]),u=Un([[-1]]).where(l.greater(0),Un([[1]])),d=l.sub(u.mul(c)),f=t.div(d);s=f.shape[0]===1?o.clone():o.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var p=u.matMul(d).div(c).neg(),m=a.slice([e,0],[n-e,r]),h=p.mul(s);if(e===0)a=m.sub(h.matMul(s.transpose().matMul(m)));else{var g=m.sub(h.matMul(s.transpose().matMul(m)));a=a.slice([0,0],[e,r]).concat(g,0)}var _=i.slice([0,e],[n,i.shape[1]-e]);if(e===0)i=_.sub(_.matMul(s).matMul(h.transpose()));else{var v=_.sub(_.matMul(s).matMul(h.transpose()));i=i.slice([0,0],[n,e]).concat(v,1)}return[s,a,i]})),s=t[0],a=t[1],i=t[2],xn([c,l,u])},u=0;u<c;++u)l(u);return!t&&n>r&&(i=i.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[i,a]}))}var vd=K({bandPart_:function(e,t,n){if(t%1!=0)throw Error(`bandPart(): numLower must be an integer, got `+t+`.`);if(n%1!=0)throw Error(`bandPart(): numUpper must be an integer, got `+n+`.`);var r=G(e,`a`,`bandPart`);if(r.rank<2)throw Error(`bandPart(): Rank must be at least 2, got `+r.rank+`.`);var i=r.shape,a=r.shape.slice(-2),o=a[0],s=a[1];if(!(t<=o))throw Error(`bandPart(): numLower (`+t+`) must not be greater than the number of rows (`+o+`).`);if(!(n<=s))throw Error(`bandPart(): numUpper (`+n+`) must not be greater than the number of columns (`+s+`).`);t<0&&(t=o),n<0&&(n=s);var c=vl($n(0,o,1,`int32`).reshape([-1,1]),$n(0,s,1,`int32`)),l=qc(c.lessEqual(q(+t,`int32`)),c.greaterEqual(q(-n,`int32`))),u=Xn([o,s],r.dtype);return Ur(Kr(r.reshape([-1,o,s])).map((function(e){return Zc(l,e,u)}))).reshape(i)}}),yd=K({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,I(e!=null&&e.length>0,(function(){return`Gram-Schmidt process: input must not be null, undefined, or empty`}));for(var n=e[0].shape[0],r=function(t){I(e[t].shape[0]===n,(function(){return`Gram-Schmidt: Non-unique lengths found in the input vectors: (`+e[t].shape[0]+` vs. `+n+`)`}))},i=1;i<e.length;++i)r(i)}else t=!0,e=sr(e,e.shape[0],0).map((function(e){return Hr(e,[0])}));I(e.length<=e[0].shape[0],(function(){return`Gram-Schmidt: Number of vectors (`+e.length+`) exceeds number of dimensions (`+e[0].shape[0]+`).`}));var a=[],o=e,s=function(e){a.push(V.tidy((function(){var t=o[e];if(e>0)for(var n=0;n<e;++n){var r=Du(a[n].mulStrict(t)).mul(a[n]);t=t.sub(r)}return t.div(Lu(t,`euclidean`))})))};for(i=0;i<e.length;++i)s(i);return t?Ur(a,0):a}}),bd=K({qr_:function(e,t){if(t===void 0&&(t=!1),e.rank<2)throw Error(`qr() requires input tensor to have a rank >= 2, but got rank `+e.rank);if(e.rank===2)return _d(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce((function(e,t){return e*t})),r=Kr(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],a=[];return r.forEach((function(e){var n=_d(e,t),r=n[0],o=n[1];i.push(r),a.push(o)})),[Ur(i,0).reshape(e.shape),Ur(a,0).reshape(e.shape)]}}),xd=Object.freeze({bandPart:vd,gramSchmidt:yd,qr:bd});function Sd(e,t,n,r,i,a){r??=.5,i??=-1/0,a??=0;var o=e.shape[0];return n=Math.min(n,o),I(0<=r&&r<=1,(function(){return`iouThreshold must be in [0, 1], but was '`+r+`'`})),I(e.rank===2,(function(){return`boxes must be a 2D tensor, but was of rank '`+e.rank+`'`})),I(e.shape[1]===4,(function(){return`boxes must have 4 columns, but 2nd dimension was `+e.shape[1]})),I(t.rank===1,(function(){return`scores must be a 1D tensor`})),I(t.shape[0]===o,(function(){return`scores has incompatible shape with boxes. Expected `+o+`, but was `+t.shape[0]})),I(0<=a&&a<=1,(function(){return`softNmsSigma must be in [0, 1], but was '`+a+`'`})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i,softNmsSigma:a}}var Cd=K({resizeBilinear_:function(e,t,n){n===void 0&&(n=!1);var r=G(e,`images`,`resizeBilinear`);I(r.rank===3||r.rank===4,(function(){return`Error in resizeBilinear: x must be rank 3 or 4, but got rank `+r.rank+`.`})),I(t.length===2,(function(){return`Error in resizeBilinear: new shape must 2D, but got shape `+t+`.`}));var i=r,a=!1;r.rank===3&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],c=V.runKernelFunc((function(e,t){return t([i]),e.resizeBilinear(i,o,s,n)}),{x:i},(function(e,t){return{x:function(){return V.runKernelFunc((function(r){return r.resizeBilinearBackprop(e,t[0],n)}),{})}}}),`ResizeBilinear`,{alignCorners:n,newHeight:o,newWidth:s});return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),wd=K({resizeNearestNeighbor_:function(e,t,n){n===void 0&&(n=!1);var r=G(e,`images`,`resizeNearestNeighbor`);I(r.rank===3||r.rank===4,(function(){return`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank `+r.rank+`.`})),I(t.length===2,(function(){return`Error in resizeNearestNeighbor: new shape must 2D, but got shape `+t+`.`})),I(r.dtype===`float32`||r.dtype===`int32`,(function(){return"`images` must have `int32` or `float32` as dtype"}));var i=r,a=!1;r.rank===3&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],c=V.runKernelFunc((function(e,t){return t([i]),e.resizeNearestNeighbor(i,o,s,n)}),{batchImages:i},(function(e,t){return{batchImages:function(){return V.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(e,t[0],n)}),{})}}}));return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),Td=K({nonMaxSuppression_:function(e,t,n,r,i){r===void 0&&(r=.5),i===void 0&&(i=-1/0);var a=G(e,`boxes`,`nonMaxSuppression`),o=G(t,`scores`,`nonMaxSuppression`),s=Sd(a,o,n,r,i);n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold;var c={maxOutputSize:n,iouThreshold:r,scoreThreshold:i};return V.runKernelFunc((function(e){return e.nonMaxSuppression(a,o,n,r,i)}),{boxes:a,scores:o},null,`NonMaxSuppressionV3`,c)}}),Ed=function(e,t,n,r,i){return r===void 0&&(r=.5),i===void 0&&(i=-1/0),w(this,void 0,void 0,(function(){var a,o,s,c,l,u,d;return T(this,(function(f){switch(f.label){case 0:return a=G(e,`boxes`,`nonMaxSuppressionAsync`),o=G(t,`scores`,`nonMaxSuppressionAsync`),s=Sd(a,o,n,r,i),n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,[4,Promise.all([a.data(),o.data()])];case 1:return c=f.sent(),l=c[0],u=c[1],d=Hi(l,u,n,r,i),a!==e&&a.dispose(),o!==t&&o.dispose(),[2,d]}}))}))},Dd=K({nonMaxSuppressionWithScore_:function(e,t,n,r,i,a){r===void 0&&(r=.5),i===void 0&&(i=-1/0),a===void 0&&(a=0);var o=G(e,`boxes`,`nonMaxSuppression`),s=G(t,`scores`,`nonMaxSuppression`),c=Sd(o,s,n,r,i,a),l={maxOutputSize:n=c.maxOutputSize,iouThreshold:r=c.iouThreshold,scoreThreshold:i=c.scoreThreshold,softNmsSigma:a=c.softNmsSigma},u=V.runKernel(`NonMaxSuppressionV5`,{boxes:o,scores:s},l);return{selectedIndices:u[0],selectedScores:u[1]}}}),Od=function(e,t,n,r,i,a){return r===void 0&&(r=.5),i===void 0&&(i=-1/0),a===void 0&&(a=0),w(this,void 0,void 0,(function(){var o,s,c,l,u,d,f;return T(this,(function(p){switch(p.label){case 0:return o=G(e,`boxes`,`nonMaxSuppressionAsync`),s=G(t,`scores`,`nonMaxSuppressionAsync`),c=Sd(o,s,n,r,i,a),n=c.maxOutputSize,r=c.iouThreshold,i=c.scoreThreshold,a=c.softNmsSigma,[4,Promise.all([o.data(),s.data()])];case 1:return l=p.sent(),u=l[0],d=l[1],f=Ui(u,d,n,r,i,a),o!==e&&o.dispose(),s!==t&&s.dispose(),[2,f]}}))}))},kd=K({cropAndResize_:function(e,t,n,r,i,a){var o=G(e,`image`,`cropAndResize`),s=G(t,`boxes`,`cropAndResize`,`float32`),c=G(n,`boxInd`,`cropAndResize`,`int32`);i||=`bilinear`,a||=0;var l=s.shape[0];return I(o.rank===4,(function(){return`Error in cropAndResize: image must be rank 4,but got rank `+o.rank+`.`})),I(s.rank===2&&s.shape[1]===4,(function(){return`Error in cropAndResize: boxes must be have size [`+l+`,4] but had shape `+s.shape+`.`})),I(c.rank===1&&c.shape[0]===l,(function(){return`Error in cropAndResize: boxInd must be have size [`+l+`] but had shape `+s.shape+`.`})),I(r.length===2,(function(){return`Error in cropAndResize: cropSize must be of length 2, but got length `+r.length+`.`})),I(r[0]>=1&&r[1]>=1,(function(){return`cropSize must be atleast [1,1], but was `+r})),I(i===`bilinear`||i===`nearest`,(function(){return`method must be bilinear or nearest, but was `+i})),V.runKernelFunc((function(e,t){return e.cropAndResize(o,s,c,r,i,a)}),{images:o,boxes:s,boxInd:c},null,`CropAndResize`,{method:i,extrapolationValue:a,cropSize:r})}}),Ad=Object.freeze({resizeBilinear:Cd,resizeNearestNeighbor:wd,nonMaxSuppression:Td,nonMaxSuppressionAsync:Ed,nonMaxSuppressionWithScore:Dd,nonMaxSuppressionWithScoreAsync:Od,cropAndResize:kd}),jd=function(e,t){return!(e>0)||t===`linear`},Md=function(e,t,n){if(n==null||n===`linear`)return e;if(n===`relu`)return e.mul(t.step());throw Error(`Gradient for activation `+n+` has not been implemented yet.`)},Nd=function(e,t){var n=t,r=yi(e.shape,t.shape);return r.length>0&&(n=n.sum(r)),n.reshape(e.shape)},Pd=function(e,t,n){if(t===`linear`)return e;if(t===`relu`)return Mu(e);if(t===`elu`)return ku(e);if(t===`relu6`)return Nu(e);if(t===`prelu`)return ju(e,n);throw Error(`Unknown fused activation `+t+`.`)},Fd=K({fusedMatMul_:function(e){var t,n=e.a,r=e.b,i=e.transposeA,a=i!==void 0&&i,o=e.transposeB,s=o!==void 0&&o,c=e.bias,l=e.activation,u=l===void 0?`linear`:l,d=e.preluActivationWeights;if(!1===jd(V.state.gradientDepth,u)){var f=Zl(n,r,a,s);return c!=null&&(f=$c(f,c)),Pd(f,u,d)}var p=G(n,`a`,`fused matMul`),m=G(r,`b`,`fused matMul`);t=lt(p,m),p=t[0],m=t[1];var h=a?p.shape[p.rank-2]:p.shape[p.rank-1],g=s?m.shape[m.rank-1]:m.shape[m.rank-2],_=a?p.shape[p.rank-1]:p.shape[p.rank-2],v=s?m.shape[m.rank-2]:m.shape[m.rank-1],y=p.shape.slice(0,-2),b=m.shape.slice(0,-2),x=R(y),S=R(b);I(p.rank>=2&&m.rank>=2&&p.rank===m.rank,(function(){return`Error in fused matMul: inputs must have the same rank of at least 2, got ranks `+p.rank+` and `+m.rank+`.`})),I(z(y,b),(function(){return`Error in fused matMul: outer dimensions (`+y+`) and (`+b+`) of Tensors with shapes `+p.shape+` and `+m.shape+` must match.`})),I(h===g,(function(){return`Error in fused matMul: inner shapes (`+h+`) and (`+g+`) of Tensors with shapes `+p.shape+` and `+m.shape+` and transposeA=`+a+` and transposeB=`+s+` must match.`}));var C,w,T=p.shape.slice(0,-2).concat([_,v]),E=a?p.as3D(x,h,_):p.as3D(x,_,h),D=s?m.as3D(S,v,g):m.as3D(S,g,v);c!=null&&bi(T,(C=lt(C=G(c,`bias`,`fused matMul`),p)[0]).shape),d!=null&&(w=G(d,`prelu weights`,`fused matMul`));var O={a:E,b:D};c!=null&&(O.bias=C),d!=null&&(O.preluActivationWeights=w);var k=[E,D];return V.runKernelFunc((function(e,t){var n=e.fusedBatchMatMul({a:E,b:D,transposeA:a,transposeB:s,bias:C,activation:u,preluActivationWeights:w});return t([E,D,n]),n}),O,(function(e,t){var n=t[0],r=t[1],i=t[2],o=Md(e,i,u),l={};return c!=null&&(l={bias:function(){return Nd(C,o)}}),Object.assign(a||s?!a&&s?{a:function(){return o.matMul(r,!1,!1)},b:function(){return o.matMul(n,!0,!1)}}:a&&!s?{a:function(){return r.matMul(o,!1,!0)},b:function(){return n.matMul(o,!1,!1)}}:{a:function(){return r.matMul(o,!0,!0)},b:function(){return o.matMul(n,!0,!0)}}:{a:function(){return o.matMul(r,!1,!0)},b:function(){return n.matMul(o,!0,!1)}},l)}),`_FusedMatMul`,{transposeA:a,transposeB:s,activation:u},k,[!0]).reshape(T)}}),Id=K({fusedConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,a=e.dataFormat,o=a===void 0?`NHWC`:a,s=e.dilations,c=s===void 0?[1,1]:s,l=e.dimRoundingMode,u=e.bias,d=e.activation,f=d===void 0?`linear`:d,p=e.preluActivationWeights;if(f||=`linear`,!1===jd(V.state.gradientDepth,f)){var m=Vl(t,n,r,i,o,c,l);return u!=null&&(m=$c(m,u)),Pd(m,f,p)}var h=G(t,`x`,`conv2d`),g=G(n,`filter`,`conv2d`),_=h,v=!1;h.rank===3&&(v=!0,_=h.as4D(1,h.shape[0],h.shape[1],h.shape[2])),I(_.rank===4,(function(){return`Error in fused conv2d: input must be rank 4, but got rank `+_.rank+`.`})),I(g.rank===4,(function(){return`Error in fused conv2d: filter must be rank 4, but got rank `+g.rank+`.`})),l!=null&&I(ce(i),(function(){return`Error in fused conv2d: pad must be an integer when using, dimRoundingMode `+l+` but got pad `+i+`.`})),I(_.shape[3]===g.shape[2],(function(){return`Error in conv2d: depth of input (`+_.shape[3]+`) must match input depth for filter `+g.shape[2]+`.`})),I(ji(r,c),(function(){return`Error in conv2D: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+c+`'`})),I(o===`NHWC`,(function(){return`Error in conv2d: got dataFormat of `+o+` but only NHWC is currently supported.`}));var y,b,x=Ci(_.shape,g.shape,r,c,i,l);u!=null&&(y=lt(y=G(u,`bias`,`fused conv2d`),h)[0],bi(x.outShape,y.shape)),p!=null&&(b=G(p,`prelu weights`,`fused conv2d`));var S={x:_,filter:g};u!=null&&(S.bias=y),p!=null&&(S.preluActivationWeights=b);var C=[g,_],w=V.runKernelFunc((function(e,t){var n=e.fusedConv2d({input:_,filter:g,convInfo:x,bias:y,activation:f,preluActivationWeights:b});return t([g,_,n]),n}),S,(function(e,t){var n=t,a=n[0],o=n[1],s=n[2],l=Md(e,s,f);I(Ai(c),(function(){return`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '`+c+`'`}));var d={};return u!=null&&(d={bias:function(){return Nd(y,l)}}),Object.assign({x:function(){return Wl(o.shape,l,a,r,i)},filter:function(){return Ul(o,l,a.shape,r,i)}},d)}),`FusedConv2D`,{convInfo:x,activation:f},C,[!0]);return v?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),Ld=K({fusedDepthwiseConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,a=e.dataFormat,o=a===void 0?`NHWC`:a,s=e.dilations,c=s===void 0?[1,1]:s,l=e.dimRoundingMode,u=e.bias,d=e.activation,f=d===void 0?`linear`:d,p=e.preluActivationWeights;if(!1===jd(V.state.gradientDepth,f)){var m=Gl(t,n,r,i,o,c,l);return u!=null&&(m=$c(m,u)),Pd(m,f,p)}var h=G(t,`x`,`depthwiseConv2d`),g=G(n,`filter`,`depthwiseConv2d`),_=h,v=!1;h.rank===3&&(v=!0,_=h.as4D(1,h.shape[0],h.shape[1],h.shape[2])),I(_.rank===4,(function(){return`Error in fused depthwiseConv2d: input must be rank 4, but got rank `+_.rank+`.`})),I(g.rank===4,(function(){return`Error in fused depthwiseConv2d: filter must be rank 4, but got rank `+g.rank+`.`})),I(_.shape[3]===g.shape[2],(function(){return`Error in fused depthwiseConv2d: number of input channels (`+_.shape[3]+`) must match the inChannels dimension in filter `+g.shape[2]+`.`})),c??=[1,1],I(ji(r,c),(function(){return`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides `+r+` and dilations '`+c+`'`})),l!=null&&I(ce(i),(function(){return`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode `+l+` but got pad `+i+`.`}));var y,b,x=Ci(_.shape,g.shape,r,c,i,l,!0);u!=null&&(y=lt(y=G(u,`bias`,`fused conv2d`),h)[0],bi(x.outShape,y.shape)),p!=null&&(b=G(p,`prelu weights`,`fused depthwiseConv2d`));var S={x:_,filter:g};u!=null&&(S.bias=y),p!=null&&(S.preluActivationWeights=b);var C=[g,_],w=V.runKernelFunc((function(e,t){var n=e.fusedDepthwiseConv2D({input:_,filter:g,convInfo:x,bias:y,activation:f,preluActivationWeights:b});return t([g,_,n]),n}),S,(function(e,t){I(Ai(c),(function(){return`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '`+c+`'`}));var n=t[0],r=t[1],i=t[2],a=Md(e,i,f),o={};return u!=null&&(o={bias:function(){return Nd(y,a)}}),Object.assign({x:function(){return Kl(r.shape,a,n,x)},filter:function(){return ql(r,a,n.shape,x)}},o)}),`FusedDepthwiseConv2D`,{convInfo:x,activation:f},C,[!0]);return v?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),Rd=Object.freeze({matMul:Fd,conv2d:Id,depthwiseConv2d:Ld}),zd=Object.freeze({image:Ad,linalg:xd,losses:gd,spectral:Ju,fused:Rd,signal:id,square:Xs,squaredDifference:Qs,conv1d:Bl,conv2d:Vl,conv3d:Hl,depthwiseConv2d:Gl,separableConv2d:Jl,conv2dTranspose:Yl,conv3dTranspose:Xl,op:K,batchNormalization2d:zc,batchNormalization3d:Bc,batchNormalization4d:Vc,batchNormalization:Hc,batchNorm:Uc,batchNorm2d:Wc,batchNorm3d:Gc,batchNorm4d:Kc,booleanMaskAsync:Il,complex:Ln,real:Rn,imag:zn,concat:nr,concat1d:rr,concat2d:ir,concat3d:ar,concat4d:or,split:sr,matMul:Zl,dot:Ql,outerProduct:$l,reverse:eu,reverse1d:tu,reverse2d:nu,reverse3d:ru,reverse4d:iu,maxPool:su,avgPool:cu,pool:lu,maxPool3d:uu,avgPool3d:du,slice:fu,slice1d:pu,slice2d:mu,slice3d:hu,slice4d:gu,abs:$s,acos:ec,acosh:tc,asin:nc,asinh:rc,atan:ic,atanh:ac,ceil:oc,clipByValue:sc,cos:cc,cosh:lc,erf:uc,exp:dc,expm1:fc,floor:pc,log:mc,log1p:hc,logSigmoid:gc,neg:_c,reciprocal:vc,round:yc,rsqrt:bc,sigmoid:xc,sign:Sc,isNaN:Cc,isInf:wc,isFinite:Tc,sin:Ec,sinh:Dc,softplus:Oc,sqrt:kc,step:Ac,tan:jc,tanh:Mc,all:vu,any:yu,argMax:bu,argMin:xu,logSumExp:Su,max:Cu,mean:wu,min:Tu,moments:Eu,sum:Du,prod:Ou,equal:bl,equalStrict:xl,greater:Sl,greaterEqual:Cl,greaterEqualStrict:wl,greaterStrict:Tl,less:El,lessEqual:Dl,lessEqualStrict:Ol,lessStrict:kl,notEqual:Al,notEqualStrict:jl,add:$c,addN:el,addStrict:tl,atan2:nl,div:rl,divNoNan:il,divStrict:al,floorDiv:ol,maximum:sl,maximumStrict:cl,minimum:ll,minimumStrict:ul,mod:dl,modStrict:fl,mul:pl,mulStrict:ml,pow:hl,powStrict:gl,squaredDifferenceStrict:_l,sub:vl,subStrict:yl,elu:ku,leakyRelu:Au,prelu:ju,relu:Mu,relu6:Nu,selu:Pu,logicalAnd:qc,logicalNot:Jc,logicalOr:Yc,logicalXor:Xc,where:Zc,whereAsync:Qc,buffer:J,print:br,batchToSpaceND:xr,broadcastTo:Sr,cast:Cr,clone:wr,cumsum:Tr,depthToSpace:Er,expandDims:Dr,eye:Or,multinomial:kr,oneHot:Ar,pad:jr,pad1d:Mr,pad2d:Nr,pad3d:Pr,pad4d:Fr,rand:Ir,randomNormal:Lr,randomGamma:Rr,randomUniform:zr,reshape:Br,spaceToBatchND:Vr,squeeze:Hr,stack:Ur,tile:Wr,truncatedNormal:Gr,unstack:Kr,setdiff1dAsync:qr,fill:Zn,linspace:Qn,ones:Yn,range:$n,scalar:q,tensor:Bn,tensor1d:Hn,tensor2d:Un,tensor3d:Wn,tensor4d:Gn,tensor5d:Kn,tensor6d:qn,variable:Jn,zeros:Xn,onesLike:er,zerosLike:tr,transpose:Fu,softmax:mi,logSoftmax:hi,localResponseNormalization:Iu,norm:Lu,gather:Pl,unsortedSegmentSum:Fl,basicLSTMCell:Ru,multiRNNCell:zu,movingAverage:Bu,stridedSlice:Vu,topk:Hu,scatterND:Uu,fft:Wu,ifft:Gu,rfft:Ku,irfft:qu,sparseToDense:Yu,gatherND:Xu,diag:Zu,dropout:Qu,hannWindow:ed,hammingWindow:td,frame:nd,stft:rd,inTopKAsync:od});function X(e,t){Array.isArray(e)||(e=[e]),e.forEach((function(e){e!=null&&I(e.dtype!==`complex64`,(function(){return t+` does not support complex64 tensors.`}))}))}function Bd(e,t,n,r){if(n===`linear`)return e.linear(t);if(n===`relu`)return e.relu(t);if(n===`elu`)return e.elu(t);if(n===`relu6`)return e.relu6(t);if(n===`prelu`)return e.prelu(t,r);throw Error(`Activation `+n+` has not been implemented for the CPU backend.`)}var Vd=function(e){function t(){var t=e.call(this)||this;return t.blockSize=48,t.firstUse=!0,t.data=new gi(t,V),t}return C(t,e),t.prototype.write=function(e,t,n){this.firstUse&&(this.firstUse=!1,O().get(`IS_NODE`)&&Cn(`
|
|
3741
3741
|
============================
|
|
3742
3742
|
Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
3743
|
-
============================`));var r={};return this.data.set(r,{values:e,dtype:n}),r},t.prototype.move=function(e,t,n,r){this.data.set(e,{values:t,dtype:r})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){return[2,this.readSync(e)]}))}))},t.prototype.readSync=function(e){var t=this.data.get(e),n=t.dtype,r=t.complexTensors;return n===`complex64`?Ci(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),n=t;if(e.dtype===`string`)try{n=t.map((function(e){return Ee(e)}))}catch{throw Error(`Failed to decode encoded string bytes into utf-8`)}return K(e.shape,e.dtype,n)},t.prototype.makeOutput=function(e,t,n){var r=this.write(e,t,n);return z.makeTensorFromDataId(r,t,n,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){return t=Ce(),e(),[2,{kernelMs:Ce()-t}]}))}))},t.prototype.memory=function(){return{unreliable:!0,reasons:[`The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less.`]}},t.prototype.complex=function(e,t){var n=this.makeOutput(null,e.shape,`complex64`);return this.data.get(n.dataId).complexTensors={real:z.keep(e.clone()),imag:z.keep(t.clone())},n},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(X(e,`slice`),Qr(e.shape,t,n)){var r=$r(t,e.strides),i=M(n);return On(this.readSync(e.dataId).subarray(r,r+i),n,e.dtype)}for(var a=K(n,e.dtype),o=this.bufferSync(e),s=0;s<a.size;++s){var c=a.indexToLoc(s).map((function(e,n){return e+t[n]}));a.values[s]=o.get.apply(o,c)}return a.toTensor()},t.prototype.stridedSlice=function(e,t,n,r){X(e,`stridedSlice`);var i=Yr(t,n,r);if(i.some((function(e){return e===0})))return On([],i);for(var a=K(i,e.dtype),o=this.bufferSync(e),s=0;s<a.size;s++){for(var c=a.indexToLoc(s),l=Array(c.length),u=0;u<l.length;u++)l[u]=c[u]*r[u]+t[u];a.set.apply(a,[o.get.apply(o,l)].concat(c))}return a.toTensor()},t.prototype.diag=function(e){for(var t=this.readSync(e.dataId),n=K([e.size,e.size],e.dtype),r=n.values,i=0;i<t.length;i++)r[i*e.size+i]=t[i];return n.toTensor()},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=Array(e.rank-1),i=0,a=0;a<e.rank;a++)a!==t&&(r[i++]=e.shape[a]);var o=Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=Array(n);for(a=0;a<c.length;a++)o[t]=a,c[a]=this.slice(e,o,s).reshape(r);return c},t.prototype.reverse=function(e,t){X(e,`reverse`);for(var n=K(e.shape,e.dtype),r=this.bufferSync(e),i=function(i){var a=n.indexToLoc(i),o=a.slice();t.forEach((function(t){return o[t]=e.shape[t]-1-o[t]})),n.set.apply(n,[r.get.apply(r,o)].concat(a))},a=0;a<n.size;a++)i(a);return n.toTensor()},t.prototype.concat=function(e,t){var n=this;if(e[0].dtype===`complex64`){var r=e.map((function(e){return En(e)})),i=e.map((function(e){return Dn(e)}));return Tn(this.concat(r,t),this.concat(i,t))}var a=e.map((function(e){var n=M(e.shape.slice(t));return e.as2D(-1,n)})),o=wn(a.map((function(e){return e.shape})),1),s=K(o,e[0].dtype).values;if(a[0].shape[0]===1){var c=0;a.forEach((function(e){s.set(n.readSync(e.dataId),c),c+=e.size}))}else{var l=0;a.forEach((function(e){for(var t=n.readSync(e.dataId),r=0,i=0;i<e.shape[0];++i)for(var a=i*o[1]+l,c=0;c<e.shape[1];++c)s[a+c]=t[r++];l+=e.shape[1]}))}return On(s,wn(e.map((function(e){return e.shape})),t),e[0].dtype)},t.prototype.neg=function(e){return X(e,`neg`),this.multiply(G(-1),e)},t.prototype.add=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e+n,imag:t+r}})):this.broadcastedBinaryOp(e,t,Ye(e.dtype,t.dtype),(function(e,t){return e+t}))},t.prototype.addN=function(e){var t=this;X(e,`addN`);for(var n=e.map((function(e){return t.readSync(e.dataId)})),r=K(e[0].shape,e[0].dtype),i=r.values,a=0;a<e.length;a++)for(var o=n[a],s=0;s<i.length;s++)i[s]+=o[s];return r.toTensor()},t.prototype.softmax=function(e,t){var n=L([t],e.shape),r=this.max(e,n),i=vn(r.shape,n),a=this.subtract(e,r.reshape(i)),o=this.exp(a),s=this.sum(o,n).reshape(i);return this.realDivide(o,s)},t.prototype.subtract=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e-n,imag:t-r}})):this.broadcastedBinaryOp(e,t,Ye(e.dtype,t.dtype),(function(e,t){return e-t}))},t.prototype.pow=function(e,t){return X([e,t],`pow`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return e**+t}))},t.prototype.batchMatMul=function(e,t,n,r){X([e,t],`matMul`);for(var i=n?e.shape[1]:e.shape[2],a=n?e.shape[2]:e.shape[1],o=r?t.shape[1]:t.shape[2],s=e.shape[0],c=this.readSync(e.dataId),l=this.readSync(t.dataId),u=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],d=u[0],f=u[1],p=u[2],m=r?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],h=m[0],g=m[1],_=m[2],v=a*o,y=K([s,a,o],e.dtype),b=y.values,x=this.blockSize,S=0;S<s;S++)for(var C=0;C<a;C+=x)for(var w=0;w<o;w+=x)for(var T=0;T<i;T+=x)for(var E=Math.min(C+x,a),D=Math.min(w+x,o),O=Math.min(T+x,i),k=C;k<E;k++)for(var A=w;A<D;A++){for(var j=0,M=T;M<O;M++)j+=c[S*d+k*f+M*p]*l[M*h+A*g+S*_];b[S*v+(k*o+A)]+=j}return y.toTensor()},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=this.batchMatMul(t,n,r,i);return a&&(c=this.add(c,a)),o&&(c=Ed(this,c,o,s)),c},t.prototype.multiply=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e*n-t*r,imag:e*r+t*n}})):this.broadcastedBinaryOp(e,t,Ye(e.dtype,t.dtype),(function(e,t){return e*t}))},t.prototype.realDivide=function(e,t){return X([e,t],`realDivide`),this.broadcastedBinaryOp(e,t,`float32`,(function(e,t){return e/t}))},t.prototype.floorDiv=function(e,t){return X([e,t],`floorDiv`),this.broadcastedBinaryOp(e,t,`int32`,(function(e,t){return Math.floor(e/t)}))},t.prototype.sum=function(e,t){X(e,`sum`),yn(`sum`,t,e.rank);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,Ye(e.dtype,`int32`)),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=0,f=0;f<o;++f)d+=c[u+f];s[l]=d}return a},t.prototype.prod=function(e,t){X(e,`sum`);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,Ye(e.dtype,`int32`)),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=1,f=0;f<o;++f)d*=c[u+f];s[l]=d}return a},t.prototype.unsortedSegmentSum=function(e,t,n){X(e,`unsortedSegmentSum`);for(var r=[],i=e.rank-t.rank,a=0;a<i;++a)t=t.expandDims(a+1);for(a=0;a<n;++a){var o=ol(G(a,`int32`),t).asType(`float32`).mul(e).sum(0);r.push(o)}return jr(r)},t.prototype.argMin=function(e,t){X(e,`argMin`);var n=[t];yn(`argMin`,n,e.rank);for(var r=_n(e.shape,n),i=r[0],a=r[1],o=Rn(i,`int32`),s=M(a),c=this.readSync(o.dataId),l=this.readSync(e.dataId),u=0;u<c.length;++u){for(var d=u*s,f=l[d],p=0,m=0;m<s;++m){var h=l[d+m];h<f&&(f=h,p=m)}c[u]=p}return o},t.prototype.argMax=function(e,t){X(e,`argMax`);var n=[t];yn(`argMax`,n,e.rank);for(var r=_n(e.shape,n),i=r[0],a=r[1],o=Rn(i,`int32`),s=M(a),c=this.readSync(o.dataId),l=this.readSync(e.dataId),u=0;u<c.length;++u){for(var d=u*s,f=l[d],p=0,m=0;m<s;++m){var h=l[d+m];h>f&&(f=h,p=m)}c[u]=p}return o},t.prototype.cumsum=function(e,t,n,r){if(X(e,`cumsum`),t!==e.rank-1)throw Error(`backend.cumsum in CPU expects an inner-most axis=`+(e.rank-1)+` but got axis=`+t);for(var i=Ye(e.dtype,`int32`),a=Rn(e.shape,i),o=this.readSync(a.dataId),s=this.readSync(e.dataId),c=e.shape[e.rank-1],l=r?function(e,t){return e+c-t-1}:function(e,t){return e+t},u=0;u<s.length;u+=c)for(var d=0;d<c;d++){var f=l(u,d);if(d===0)o[f]=n?0:s[f];else{var p=l(u,d-1);o[f]=n?s[p]+o[p]:s[f]+o[p]}}return a},t.prototype.equal=function(e,t){return X([e,t],`equal`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e===t?1:0}))},t.prototype.notEqual=function(e,t){return X([e,t],`notEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e===t?0:1}))},t.prototype.less=function(e,t){return X([e,t],`less`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e<t?1:0}))},t.prototype.lessEqual=function(e,t){return X([e,t],`lessEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e<=t?1:0}))},t.prototype.greater=function(e,t){return X([e,t],`greater`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e>t?1:0}))},t.prototype.greaterEqual=function(e,t){return X([e,t],`greaterEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e>=t?1:0}))},t.prototype.logicalNot=function(e){X(e,`logicalNot`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)n[r]=t[r]?0:1;return this.makeOutput(n,e.shape,`bool`)},t.prototype.logicalAnd=function(e,t){return X([e,t],`logicalAnd`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e&&t}))},t.prototype.logicalOr=function(e,t){return X([e,t],`logicalOr`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e||t}))},t.prototype.select=function(e,t,n){X([e,t,n],`select`);for(var r=this.readSync(e.dataId),i=this.readSync(t.dataId),a=this.readSync(n.dataId),o=Rn(t.shape,Ye(t.dtype,n.dtype)),s=this.readSync(o.dataId),c=0,l=e.rank===0||e.rank>1||t.rank===1?1:M(t.shape.slice(1)),u=0;u<r.length;u++)for(var d=0;d<l;d++)r[u]===1?s[c++]=i[u]:s[c++]=a[u];return o},t.prototype.where=function(e){X([e],`where`);var t=this.readSync(e.dataId);return Ri(e.shape,t)},t.prototype.topk=function(e,t,n){return X(e,`topk`),Li(this.readSync(e.dataId),e.shape,e.dtype,t)},t.prototype.min=function(e,t){X(e,`min`),yn(`min`,t,e.rank);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,e.dtype),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];p<d&&(d=p)}s[l]=d}return a},t.prototype.minimum=function(e,t){return X([e,t],`minimum`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.min(e,t)}))},t.prototype.mod=function(e,t){return X([e,t],`mod`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}))},t.prototype.max=function(e,t){X(e,`max`),yn(`max`,t,e.rank);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,e.dtype),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];p>d&&(d=p)}s[l]=d}return a},t.prototype.maximum=function(e,t){return X([e,t],`maximum`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.max(e,t)}))},t.prototype.all=function(e,t){X(e,`all`),yn(`all`,t,e.rank);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,e.dtype),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];d&&=p}s[l]=d}return a},t.prototype.any=function(e,t){X(e,`any`),yn(`any`,t,e.rank);for(var n=_n(e.shape,t),r=n[0],i=n[1],a=Rn(r,e.dtype),o=M(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];d||=p}s[l]=d}return a},t.prototype.squaredDifference=function(e,t){return X([e,t],`squaredDifference`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e-t;return n*n}))},t.prototype.ceil=function(e){X(e,`ceil`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.ceil(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.floor=function(e){X(e,`floor`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.floor(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.sign=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)t[r]<0?n[r]=-1:t[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,e.shape,`float32`)},t.prototype.isNaN=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isNaN(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.isInf=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Math.abs(t[r])===1/0&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.isFinite=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isFinite(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.round=function(e){X(e,`round`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=Math.floor(t[r]);t[r]-i<.5?n[r]=Math.floor(t[r]):t[r]-i>.5?n[r]=Math.ceil(t[r]):n[r]=i%2==0?i:i+1}return this.makeOutput(n,e.shape,`float32`)},t.prototype.exp=function(e){X(e,`exp`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.exp(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.expm1=function(e){X(e,`expm1`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.expm1(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.log=function(e){X(e,`log`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.log1p=function(e){X(e,`log1p`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log1p(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.sqrt=function(e){X(e,`sqrt`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.sqrt(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.rsqrt=function(e){X(e,`rsqrt`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=1/Math.sqrt(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.reciprocal=function(e){X(e,`reciprocal`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=1/t[r];return this.makeOutput(n,e.shape,`float32`)},t.prototype.linear=function(e){return e},t.prototype.relu=function(e){X(e,`relu`);for(var t=Rn(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.max(0,r[i]);return t},t.prototype.relu6=function(e){X(e,`relu`);for(var t=Rn(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.min(Math.max(0,r[i]),6);return t},t.prototype.prelu=function(e,t){return X([e,t],`prelu`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return e<0?t*e:e}))},t.prototype.elu=function(e){X(e,`elu`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=n[r];t[r]=i>=0?i:Math.exp(i)-1}return this.makeOutput(t,e.shape,`float32`)},t.prototype.eluDer=function(e,t){X([e,t],`eluDer`);for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),i=this.readSync(e.dataId),a=0;a<r.length;++a){var o=r[a];n[a]=o>=1?i[a]:i[a]*(o+1)}return this.makeOutput(n,t.shape,`float32`)},t.prototype.selu=function(e){X(e,`selu`);for(var t=rs,n=is,r=new Float32Array(e.size),i=this.readSync(e.dataId),a=0;a<i.length;++a){var o=i[a];r[a]=o>=0?n*o:t*(Math.exp(o)-1)}return this.makeOutput(r,e.shape,`float32`)},t.prototype.clip=function(e,t,n){X(e,`clip`);for(var r=new Float32Array(e.size),i=this.readSync(e.dataId),a=0;a<i.length;++a){var o=i[a];r[a]=o>n?n:o<t?t:o}return this.makeOutput(r,e.shape,`float32`)},t.prototype.abs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.abs(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.complexAbs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<e.size;++r){var i=n[2*r],a=n[2*r+1];t[r]=Math.hypot(i,a)}return this.makeOutput(t,e.shape,`float32`)},t.prototype.int=function(e){X(e,`int`);for(var t=new Int32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=n[r];return this.makeOutput(t,e.shape,`int32`)},t.prototype.sigmoid=function(e){X(e,`sigmoid`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(t,e.shape,`float32`)},t.prototype.softplus=function(e){X(e,`softplus`);for(var t=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var a=r[i]>-t,o=r[i]<t,s=Math.exp(r[i]),c=void 0;c=o?s:a?r[i]:Math.log(1+s),n[i]=c}return this.makeOutput(n,e.shape,`float32`)},t.prototype.sin=function(e){X(e,`sin`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sin(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.cos=function(e){X(e,`cos`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cos(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.tan=function(e){X(e,`tan`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.tan(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.asin=function(e){X(e,`asin`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asin(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.acos=function(e){X(e,`acos`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acos(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atan=function(e){X(e,`atan`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atan(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atan2=function(e,t){return X([e,t],`atan2`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.atan2(e,t)}))},t.prototype.sinh=function(e){X(e,`sinh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sinh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.cosh=function(e){X(e,`cosh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cosh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.tanh=function(e){X(e,`tanh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=F(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.asinh=function(e){X(e,`asinh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asinh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.acosh=function(e){X(e,`acosh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acosh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atanh=function(e){X(e,`atanh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atanh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.erf=function(e){X(e,`erf`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=Math.sign(n[r]),a=Math.abs(n[r]),o=1/(1+.3275911*a);t[r]=i*(1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-a*a))}return this.makeOutput(t,e.shape,`float32`)},t.prototype.step=function(e,t){t===void 0&&(t=0),X(e,`step`);for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var a=r[i];isNaN(a)?n[i]=NaN:n[i]=a>0?1:t}return this.makeOutput(n,e.shape,`float32`)},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights,s=this.conv2d(t,n,r);return i&&(s=this.add(s,i)),a&&(s=Ed(this,s,a,o)),s},t.prototype.conv2d=function(e,t,n){X([e,t],`conv2d`);for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,l=n.dataFormat===`channelsLast`,u=K(n.outShape,e.dtype),d=e.strides[0],f=l?e.strides[1]:e.strides[2],p=l?e.strides[2]:1,m=l?1:e.strides[1],h=u.strides[0],g=l?u.strides[1]:u.strides[2],_=l?u.strides[2]:1,v=l?1:u.strides[1],y=this.readSync(e.dataId),b=this.readSync(t.dataId),x=u.values,S=0;S<n.batchSize;++S)for(var C=S*d,w=S*h,T=0;T<n.outHeight;++T)for(var E=w+T*g,D=T*n.strideHeight-c,O=0;O<r;O++){var k=D+O*a;if(!(k<0||k>=n.inHeight))for(var A=O*t.strides[0],j=C+k*f,M=0;M<n.outWidth;++M)for(var N=E+M*_,P=M*n.strideWidth-s,F=0;F<i;F++){var I=P+F*o;if(!(I<0||I>=n.inWidth))for(var ee=j+I*p,te=A+F*t.strides[1],ne=0;ne<n.inChannels;++ne){for(var L=y[ee+ne*m],re=0;re<n.outChannels;++re)x[N+re*v]+=L*b[te+re];te+=n.outChannels}}}return u.toTensor()},t.prototype.conv3d=function(e,t,n){for(var r=n.filterDepth,i=n.filterHeight,a=n.filterWidth,o=n.dilationDepth,s=n.dilationHeight,c=n.dilationWidth,l=n.padInfo.front,u=n.padInfo.left,d=n.padInfo.top,f=K(n.outShape,e.dtype),p=this.readSync(e.dataId),m=this.readSync(t.dataId),h=f.values,g=0;g<n.batchSize;++g)for(var _=g*e.strides[0],v=g*f.strides[0],y=0;y<n.outDepth;++y)for(var b=v+y*f.strides[1],x=y*n.strideDepth-l,S=0;S<r;S++){var C=x+S*o;if(!(C<0||C>=n.inDepth))for(var w=S*t.strides[0],T=_+C*e.strides[1],E=0;E<n.outHeight;++E)for(var D=b+E*f.strides[2],O=E*n.strideHeight-d,k=0;k<i;k++){var A=O+k*s;if(!(A<0||A>=n.inHeight))for(var j=w+k*t.strides[1],M=T+A*e.strides[2],N=0;N<n.outWidth;++N)for(var P=D+N*n.outChannels,F=N*n.strideWidth-u,I=0;I<a;I++){var ee=F+I*c;if(!(ee<0||ee>=n.inWidth))for(var te=j+I*t.strides[2],ne=M+ee*n.inChannels,L=te,re=0;re<n.inChannels;++re){for(var ie=p[ne+re],ae=0;ae<n.outChannels;++ae)h[P+ae]+=ie*m[L+ae];L+=n.outChannels}}}}return f.toTensor()},t.prototype.conv2dDerInput=function(e,t,n){X([e,t],`conv2dDerInput`);for(var r=K(n.inShape,`float32`),i=r.values,a=this.readSync(e.dataId),o=this.readSync(t.dataId),s=t.strides,c=s[0],l=s[1],u=s[2],d=n.batchSize,f=n.filterHeight,p=n.filterWidth,m=n.inChannels,h=n.inHeight,g=n.inWidth,_=n.outChannels,v=n.outHeight,y=n.outWidth,b=n.strideHeight,x=n.strideWidth,S=n.dataFormat,C=f-1-n.padInfo.top,w=p-1-n.padInfo.left,T=S===`channelsLast`,E=r.strides[0],D=T?r.strides[1]:r.strides[2],O=T?r.strides[2]:1,k=T?1:r.strides[1],A=e.strides[0],j=T?e.strides[1]:e.strides[2],M=T?e.strides[2]:1,N=T?1:e.strides[1],P=0;P<d;++P)for(var F=0;F<m;++F)for(var I=0;I<h;++I)for(var ee=I-C,te=Math.max(0,Math.ceil(ee/b)),ne=Math.min(v,(f+ee)/b),L=0;L<g;++L){for(var re=L-w,ie=Math.max(0,Math.ceil(re/x)),ae=Math.min(y,(p+re)/x),oe=0,se=te;se<ne;++se)for(var ce=se*b-ee,le=ie;le<ae;++le)for(var ue=A*P+j*se+M*le,de=c*(f-1-ce)+l*(p-1-(le*x-re))+u*F,fe=0;fe<_;++fe)oe+=a[ue+N*fe]*o[de+fe];i[E*P+D*I+O*L+k*F]=oe}return r.toTensor()},t.prototype.conv3dDerInput=function(e,t,n){for(var r=K(n.inShape,`float32`),i=r.values,a=r.strides,o=a[0],s=a[1],c=a[2],l=a[3],u=this.readSync(e.dataId),d=e.strides,f=d[0],p=d[1],m=d[2],h=d[3],g=this.readSync(t.dataId),_=t.strides,v=_[0],y=_[1],b=_[2],x=_[3],S=n.batchSize,C=n.filterDepth,w=n.filterHeight,T=n.filterWidth,E=n.inChannels,D=n.inDepth,O=n.inHeight,k=n.inWidth,A=n.outChannels,j=n.outDepth,M=n.outHeight,N=n.outWidth,P=n.strideDepth,F=n.strideHeight,I=n.strideWidth,ee=C-1-n.padInfo.front,te=w-1-n.padInfo.top,ne=T-1-n.padInfo.left,L=0;L<S;++L)for(var re=0;re<E;++re)for(var ie=0;ie<D;++ie)for(var ae=ie-ee,oe=Math.max(0,Math.ceil(ae/P)),se=Math.min(j,(C+ae)/P),ce=0;ce<O;++ce)for(var le=ce-te,ue=Math.max(0,Math.ceil(le/F)),de=Math.min(M,(w+le)/F),fe=0;fe<k;++fe){for(var pe=fe-ne,me=Math.max(0,Math.ceil(pe/I)),he=Math.min(N,(T+pe)/I),ge=0,_e=oe;_e<se;++_e)for(var ve=_e*P-ae,ye=ue;ye<de;++ye)for(var be=ye*F-le,xe=me;xe<he;++xe)for(var Se=f*L+p*_e+m*ye+h*xe,Ce=v*(C-1-ve)+y*(w-1-be)+b*(T-1-(xe*I-pe))+x*re,we=0;we<A;++we)ge+=u[Se+we]*g[Ce+we];i[o*L+s*ie+c*ce+l*fe+re]=ge}return r.toTensor()},t.prototype.conv2dDerFilter=function(e,t,n){X([e,t],`conv2dDerFilter`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dataFormat===`channelsLast`,c=K(n.filterShape,`float32`),l=n.padInfo.left,u=n.padInfo.top,d=this.bufferSync(e),f=this.bufferSync(t),p=0;p<a;++p)for(var m=Math.max(0,Math.ceil((u-p)/r)),h=Math.min(n.outHeight,(n.inHeight+u-p)/r),g=0;g<o;++g)for(var _=Math.max(0,Math.ceil((l-g)/i)),v=Math.min(n.outWidth,(n.inWidth+l-g)/i),y=0;y<n.inChannels;++y)for(var b=0;b<n.outChannels;++b){for(var x=0,S=0;S<n.batchSize;++S)for(var C=m;C<h;++C)for(var w=p+C*r-u,T=_;T<v;++T){var E=g+T*i-l;x+=s?d.get(S,w,E,y)*f.get(S,C,T,b):d.get(S,y,w,E)*f.get(S,b,C,T)}c.set(x,p,g,y,b)}return c.toTensor()},t.prototype.conv3dDerFilter=function(e,t,n){for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,c=n.filterWidth,l=K(n.filterShape,`float32`),u=l.values,d=l.strides,f=d[0],p=d[1],m=d[2],h=d[3],g=this.readSync(t.dataId),_=t.strides,v=_[0],y=_[1],b=_[2],x=_[3],S=this.readSync(e.dataId),C=e.strides,w=C[0],T=C[1],E=C[2],D=C[3],O=n.padInfo.front,k=n.padInfo.left,A=n.padInfo.top,j=0;j<o;++j)for(var M=Math.max(0,Math.ceil((O-j)/r)),N=Math.min(n.outDepth,(n.inDepth+O-j)/r),P=j*f,F=0;F<s;++F)for(var I=Math.max(0,Math.ceil((A-F)/i)),ee=Math.min(n.outHeight,(n.inHeight+A-F)/i),te=F*p+P,ne=0;ne<c;++ne)for(var L=Math.max(0,Math.ceil((k-ne)/a)),re=Math.min(n.outWidth,(n.inWidth+k-ne)/a),ie=ne*m+te,ae=0;ae<n.inChannels;++ae)for(var oe=ae*h+ie,se=0;se<n.outChannels;++se){for(var ce=0,le=0;le<n.batchSize;++le)for(var ue=le*w,de=le*v,fe=M;fe<N;++fe)for(var pe=(j+fe*r-O)*T+ue,me=fe*y+de,he=I;he<ee;++he)for(var ge=(F+he*i-A)*E+pe,_e=he*b+me,ve=L;ve<re;++ve){var ye=ve*x+_e;ce+=S[(ne+ve*a-k)*D+ge+ae]*g[ye+se]}u[oe+se]=ce}return l.toTensor()},t.prototype.fusedDepthwiseConv2D=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights,s=this.depthwiseConv2D(t,n,r);return i&&(s=this.add(s,i)),a&&(s=Ed(this,s,a,o)),s},t.prototype.depthwiseConv2D=function(e,t,n){X([e,t],`depthwiseConv2D`);for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,u=K(n.outShape,e.dtype),d=this.readSync(e.dataId),f=this.readSync(t.dataId),p=u.values,m=0;m<n.batchSize;++m)for(var h=m*e.strides[0],g=m*u.strides[0],_=0;_<n.outHeight;++_)for(var v=g+_*u.strides[1],y=_*n.strideHeight-s,b=0;b<r;++b){var x=y+b*a;if(!(x<0||x>=n.inHeight))for(var S=b*t.strides[0],C=h+x*e.strides[1],w=0;w<n.outWidth;++w)for(var T=v+w*u.strides[2],E=w*n.strideWidth-c,D=0;D<i;++D){var O=E+D*o;if(!(O<0||O>=n.inWidth))for(var k=S+D*t.strides[1],A=C+O*n.inChannels,j=T,M=k,N=0;N<n.inChannels;++N){for(var P=d[A+N],F=0;F<l;++F)p[j+F]+=P*f[M+F];j+=l,M+=l}}}return u.toTensor()},t.prototype.depthwiseConv2DDerInput=function(e,t,n){X([e,t],`depthwiseConv2DDerInput`);for(var r=K(n.inShape,`float32`),i=r.values,a=r.strides,o=a[0],s=a[1],c=a[2],l=this.readSync(e.dataId),u=e.strides,d=u[0],f=u[1],p=u[2],m=this.readSync(t.dataId),h=t.strides,g=h[0],_=h[1],v=h[2],y=n.batchSize,b=n.filterHeight,x=n.filterWidth,S=n.inChannels,C=n.inHeight,w=n.inWidth,T=n.outChannels,E=n.outHeight,D=n.outWidth,O=n.strideHeight,k=n.strideWidth,A=b-1-n.padInfo.top,j=x-1-n.padInfo.left,M=T/S,N=0;N<y;++N)for(var P=0;P<S;++P)for(var F=0;F<C;++F)for(var I=F-A,ee=Math.max(0,Math.ceil(I/O)),te=Math.min(E,(b+I)/O),ne=0;ne<w;++ne){for(var L=ne-j,re=Math.max(0,Math.ceil(L/k)),ie=Math.min(D,(x+L)/k),ae=0,oe=ee;oe<te;++oe)for(var se=oe*O-I,ce=re;ce<ie;++ce)for(var le=d*N+f*oe+p*ce,ue=g*(b-1-se)+_*(x-1-(ce*k-L))+v*P,de=0;de<M;++de)ae+=l[le+(P*M+de)]*m[ue+de];i[o*N+s*F+c*ne+P]=ae}return r.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){X([e,t],`depthwiseConv2DDerFilter`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=K(n.filterShape,`float32`),c=n.padInfo.left,l=n.padInfo.top,u=n.outChannels/n.inChannels,d=this.bufferSync(e),f=this.bufferSync(t),p=0;p<a;++p)for(var m=Math.max(0,Math.ceil((l-p)/r)),h=Math.min(n.outHeight,(n.inHeight+l-p)/r),g=0;g<o;++g)for(var _=Math.max(0,Math.ceil((c-g)/i)),v=Math.min(n.outWidth,(n.inWidth+c-g)/i),y=0;y<n.outChannels;++y){for(var b=Math.trunc(y/u),x=y%u,S=0,C=0;C<n.batchSize;++C)for(var w=m;w<h;++w)for(var T=p+w*r-l,E=_;E<v;++E){var D=g+E*i-c;S+=d.get(C,T,D,b)*f.get(C,w,E,y)}s.set(S,p,g,b,x)}return s.toTensor()},t.prototype.tile=function(e,t){return X(e,`tile`),Ii(this.bufferSync(e),t)},t.prototype.pad=function(e,t,n){X(e,`pad`);var r=t.map((function(t,n){return t[0]+e.shape[n]+t[1]})),i=t.map((function(e){return e[0]})),a=this.bufferSync(e),o=K(r,e.dtype);n!==0&&o.values.fill(n);for(var s=0;s<e.size;s++){var c=a.indexToLoc(s),l=c.map((function(e,t){return e+i[t]}));o.set.apply(o,[a.get.apply(a,c)].concat(l))}return o.toTensor()},t.prototype.transpose=function(e,t){X(e,`transpose`);for(var n=Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[t[r]];var i=this.readSync(e.dataId),a=K(n,e.dtype),o=this.bufferSync(e);for(r=0;r<e.size;++r){for(var s=o.indexToLoc(r),c=Array(s.length),l=0;l<c.length;l++)c[l]=s[t[l]];var u=a.locToIndex(c);a.values[u]=i[r]}return a.toTensor()},t.prototype.gather=function(e,t,n){X([e,t],`gather`);var r=e.shape.slice(),i=this.readSync(t.dataId);r[n]=i.length;for(var a=K(r,e.dtype),o=this.bufferSync(e),s=0;s<a.size;++s){var c=a.indexToLoc(s),l=c.slice();l[n]=i[c[n]];var u=o.locToIndex(l);a.values[s]=o.values[u]}return a.toTensor()},t.prototype.batchToSpaceND=function(e,t,n){X([e],`batchToSpaceND`);var r=t.reduce((function(e,t){return e*t})),i=Ir(e.shape,t,r),a=Lr(i.length,t.length),o=Rr(e.shape,t,r),s=zr(n,t.length),c=Br(o,n,t.length);return e.reshape(i).transpose(a).reshape(o).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){X([e],`spaceToBatchND`);var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var a=1+t.length;a<e.shape.length;++a)i.push([0,0]);var o=e.pad(i),s=Ir(o.shape,t,r,!1),c=Lr(s.length,t.length,!1),l=Rr(o.shape,t,r,!1);return o.reshape(s).transpose(c).reshape(l)},t.prototype.pool=function(e,t,n){X(e,`pool`);for(var r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,u=t.padInfo.left,d=n===`max`?-1/0:1/0,f=this.readSync(e.dataId),p=K(t.outShape,e.dtype),m=p.values,h=t.outShape[1]*t.outShape[2]*t.outShape[3],g=t.outShape[2]*t.outShape[3],_=t.outShape[3],v=0;v<t.batchSize;++v)for(var y=v*h,b=v*e.strides[0],x=0;x<t.inChannels;++x)for(var S=0;S<t.outHeight;++S)for(var C=S*r-l,w=Math.max(0,C),T=Math.min(t.inHeight,s+C),E=y+S*g,D=0;D<t.outWidth;++D){for(var O=D*i-u,k=Math.max(0,O),A=Math.min(t.inWidth,c+O),j=d,M=0,N=0,P=w;P<T;P+=a){for(var F=b+P*e.strides[1],I=k;I<A;I+=o){var ee=f[F+I*e.strides[2]+x];n===`max`&&ee>j?j=ee:n===`avg`&&(M+=ee,N++)}if(isNaN(j))break}m[E+D*_+x]=n===`avg`?M/N:j}return p.toTensor()},t.prototype.maxPool=function(e,t){return this.pool(e,t,`max`)},t.prototype.maxPoolPositions=function(e,t){for(var n=K(t.outShape,`int32`),r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,u=t.padInfo.left,d=this.bufferSync(e),f=0;f<t.batchSize;++f)for(var p=0;p<t.inChannels;++p)for(var m=0;m<t.outHeight;++m){for(var h=m*r-l,g=h;g<0;)g+=a;for(var _=Math.min(t.inHeight,s+h),v=0;v<t.outWidth;++v){for(var y=v*i-u,b=y;b<0;)b+=o;for(var x=Math.min(t.inWidth,c+y),S=-1/0,C=-1,w=g;w<_;w+=a)for(var T=w-h,E=b;E<x;E+=o){var D=E-y,O=d.get(f,w,E,p);O>S&&(S=O,C=T*c+D)}n.set(C,f,m,v,p)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(e,t,n,r){X([t,n],`maxPoolBackprop`);for(var i=this.maxPoolPositions(t,r),a=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterHeight,u=r.effectiveFilterWidth,d=u-1-r.padInfo.left,f=l-1-r.padInfo.top,p=K(t.shape,`float32`),m=this.bufferSync(i),h=this.bufferSync(e),g=0;g<r.batchSize;++g)for(var _=0;_<r.inChannels;++_)for(var v=0;v<r.inHeight;++v)for(var y=0;y<r.inWidth;++y){for(var b=v-f,x=y-d,S=0,C=0;C<l;C+=s){var w=(b+C)/a;if(!(w<0||w>=r.outHeight||Math.floor(w)!==w))for(var T=0;T<u;T+=c){var E=(x+T)/o;if(!(E<0||E>=r.outWidth||Math.floor(E)!==E)){var D=l*u-1-m.get(g,w,E,_)===C*u+T?1:0;D!==0&&(S+=h.get(g,w,E,_)*D)}}}p.set(S,g,v,y,_)}return p.toTensor()},t.prototype.avgPoolBackprop=function(e,t,n){X([e,t],`avgPoolBackprop`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,c=n.dilationWidth,l=n.effectiveFilterHeight,u=n.effectiveFilterWidth,d=u-1-n.padInfo.left,f=l-1-n.padInfo.top,p=K(t.shape,`float32`),m=1/(a*o),h=this.bufferSync(e),g=0;g<n.batchSize;++g)for(var _=0;_<n.inChannels;++_)for(var v=0;v<n.inHeight;++v)for(var y=0;y<n.inWidth;++y){for(var b=v-f,x=y-d,S=0,C=0;C<l;C+=s){var w=(b+C)/r;if(!(w<0||w>=n.outHeight||Math.floor(w)!==w))for(var T=0;T<u;T+=c){var E=(x+T)/i;E<0||E>=n.outWidth||Math.floor(E)!==E||(S+=h.get(g,w,E,_))}}p.set(S*m,g,v,y,_)}return p.toTensor()},t.prototype.pool3d=function(e,t,n){X(e,`pool3d`);for(var r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.front,p=t.padInfo.top,m=t.padInfo.left,h=n===`max`?-1/0:1/0,g=this.readSync(e.dataId),_=K(t.outShape,e.dtype),v=_.values,y=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],b=t.outShape[2]*t.outShape[3]*t.outShape[4],x=t.outShape[3]*t.outShape[4],S=t.outShape[4],C=0;C<t.batchSize;++C)for(var w=C*y,T=C*e.strides[0],E=0;E<t.inChannels;++E)for(var D=0;D<t.outDepth;++D){for(var O=D*r-f,k=O;k<0;)k+=o;for(var A=Math.min(t.inDepth,l+O),j=w+D*b,M=0;M<t.outHeight;++M){for(var N=M*i-p,P=N;P<0;)P+=s;for(var F=Math.min(t.inHeight,u+N),I=j+M*x,ee=0;ee<t.outWidth;++ee){for(var te=ee*a-m,ne=te;ne<0;)ne+=c;for(var L=Math.min(t.inWidth,d+te),re=I+ee*S,ie=h,ae=0,oe=0,se=k;se<A;se+=o){for(var ce=T+se*e.strides[1],le=P;le<F;le+=s){for(var ue=ce+le*e.strides[2],de=ne;de<L;de+=c){var fe=g[ue+de*e.strides[3]+E];if(n===`max`&&fe>ie?ie=fe:n===`avg`&&(ae+=fe,oe++),isNaN(ie))break}if(isNaN(ie))break}if(isNaN(ie))break}v[re+E]=n===`avg`?ae/oe:ie}}}return _.toTensor()},t.prototype.avgPool3d=function(e,t){return X(e,`avgPool3d`),this.pool3d(e,t,`avg`).toFloat()},t.prototype.avgPool3dBackprop=function(e,t,n){X([e,t],`avgPool3dBackprop`);for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,c=n.filterWidth,l=n.dilationDepth,u=n.dilationHeight,d=n.dilationWidth,f=n.effectiveFilterDepth,p=n.effectiveFilterHeight,m=n.effectiveFilterWidth,h=f-1-n.padInfo.front,g=m-1-n.padInfo.left,_=p-1-n.padInfo.top,v=K(t.shape,`float32`),y=1/(o*s*c),b=this.bufferSync(e),x=0;x<n.batchSize;++x)for(var S=0;S<n.inChannels;++S)for(var C=0;C<n.inDepth;++C)for(var w=0;w<n.inHeight;++w)for(var T=0;T<n.inWidth;++T){for(var E=C-h,D=w-_,O=T-g,k=0,A=0;A<f;A+=l){var j=(E+A)/r;if(!(j<0||j>=n.outDepth||Math.floor(j)!==j))for(var M=0;M<p;M+=u){var N=(D+M)/i;if(!(N<0||N>=n.outHeight||Math.floor(N)!==N))for(var P=0;P<m;P+=d){var F=(O+P)/a;F<0||F>=n.outWidth||Math.floor(F)!==F||(k+=b.get(x,j,N,F,S))}}}v.set(k*y,x,C,w,T,S)}return v.toTensor()},t.prototype.maxPool3d=function(e,t){return X(e,`maxPool3d`),this.pool3d(e,t,`max`).toFloat()},t.prototype.maxPool3dPositions=function(e,t){for(var n=K(t.outShape,`int32`),r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.front,p=t.padInfo.top,m=t.padInfo.left,h=this.bufferSync(e),g=0;g<t.batchSize;++g)for(var _=0;_<t.inChannels;++_)for(var v=0;v<t.outDepth;++v){for(var y=v*r-f,b=y;b<0;)b+=o;for(var x=Math.min(t.inDepth,l+y),S=0;S<t.outHeight;++S){for(var C=S*i-p,w=C;w<0;)w+=s;for(var T=Math.min(t.inHeight,u+C),E=0;E<t.outWidth;++E){for(var D=E*a-m,O=D;O<0;)O+=c;for(var k=Math.min(t.inWidth,d+D),A=-1/0,j=-1,M=b;M<x;M+=o)for(var N=M-y,P=w;P<T;P+=s)for(var F=P-C,I=O;I<k;I+=c){var ee=I-D,te=h.get(g,M,P,I,_);te>=A&&(A=te,j=N*u*d+F*u+ee)}n.set(j,g,v,S,E,_)}}}return n.toTensor()},t.prototype.maxPool3dBackprop=function(e,t,n,r){X([t,n],`maxPool3dBackprop`);for(var i=this.maxPool3dPositions(t,r),a=r.strideDepth,o=r.strideHeight,s=r.strideWidth,c=r.dilationDepth,l=r.dilationHeight,u=r.dilationWidth,d=r.effectiveFilterDepth,f=r.effectiveFilterHeight,p=r.effectiveFilterWidth,m=d-1-r.padInfo.front,h=p-1-r.padInfo.left,g=f-1-r.padInfo.top,_=K(t.shape,`float32`),v=this.bufferSync(i),y=this.bufferSync(e),b=0;b<r.batchSize;++b)for(var x=0;x<r.inChannels;++x)for(var S=0;S<r.inDepth;++S)for(var C=0;C<r.inHeight;++C)for(var w=0;w<r.inWidth;++w){for(var T=S-m,E=C-g,D=w-h,O=0,k=0;k<d;k+=c){var A=(T+k)/a;if(!(A<0||A>=r.outDepth||Math.floor(A)!==A))for(var j=0;j<f;j+=l){var M=(E+j)/o;if(!(M<0||M>=r.outHeight||Math.floor(M)!==M))for(var N=0;N<p;N+=u){var P=(D+N)/s;if(!(P<0||P>=r.outWidth||Math.floor(P)!==P)){var F=d*f*p-1-v.get(b,A,M,P,x)===k*f*p+j*p+N?1:0;F!==0&&(O+=y.get(b,A,M,P,x)*F)}}}}_.set(O,b,S,C,w,x)}return _.toTensor()},t.prototype.cast=function(e,t){return bi(e,t,this)},t.prototype.reshape=function(e,t){return xi(e,t)},t.prototype.avgPool=function(e,t){return X(e,`avgPool`),this.pool(e,t,`avg`).toFloat()},t.prototype.resizeBilinear=function(e,t,n,r){X(e,`resizeBilinear`);for(var i=e.shape,a=i[0],o=i[1],s=i[2],c=i[3],l=this.readSync(e.dataId),u=new Float32Array(M([a,t,n,c])),d=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0,m=d[0]/f[0],h=d[1]/f[1],g=0;g<a;g++)for(var _=0;_<t;_++)for(var v=m*_,y=Math.floor(v),b=v-y,x=Math.min(o-1,Math.ceil(v)),S=g*e.strides[0]+y*e.strides[1],C=g*e.strides[0]+x*e.strides[1],w=0;w<n;w++)for(var T=h*w,E=Math.floor(T),D=T-E,O=Math.min(s-1,Math.ceil(T)),k=S+E*e.strides[2],A=C+E*e.strides[2],j=S+O*e.strides[2],N=C+O*e.strides[2],P=0;P<c;P++){var F=l[k+P],I=l[A+P],ee=F+(l[j+P]-F)*D,te=ee+(I+(l[N+P]-I)*D-ee)*b;u[p++]=te}return On(u,[a,t,n,c])},t.prototype.resizeBilinearBackprop=function(e,t,n){X([e,t],`resizeBilinearBackprop`);for(var r=t.shape,i=r[0],a=r[1],o=r[2],s=r[3],c=e.shape,l=c[1],u=c[2],d=new Float32Array(i*a*o*s),f=[n&&l>1?a-1:a,n&&u>1?o-1:o],p=[n&&l>1?l-1:l,n&&u>1?u-1:u],m=f[0]/p[0],h=f[1]/p[1],g=this.readSync(e.dataId),_=0,v=0;v<i;v++)for(var y=v*t.strides[0],b=0;b<l;b++)for(var x=b*m,S=Math.floor(x),C=Math.min(Math.ceil(x),a-1),w=y+S*t.strides[1],T=y+C*t.strides[1],E=x-S,D=1-E,O=0;O<u;O++)for(var k=O*h,A=Math.floor(k),j=Math.min(Math.ceil(k),o-1),M=k-A,N=1-M,P=w+A*t.strides[2],F=w+j*t.strides[2],I=T+A*t.strides[2],ee=T+j*t.strides[2],te=D*N,ne=D*M,L=E*N,re=E*M,ie=0;ie<s;ie++){var ae=g[_++];d[P+ie]+=ae*te,d[F+ie]+=ae*ne,d[I+ie]+=ae*L,d[ee+ie]+=ae*re}return Nn(d,[i,o,a,s],t.dtype)},t.prototype.resizeNearestNeighbor=function(e,t,n,r){X(e,`resizeNearestNeighbor`);for(var i=e.shape,a=i[0],o=i[1],s=i[2],c=i[3],l=this.readSync(e.dataId),u=new Float32Array(a*t*n*c),d=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=d[0]/f[0],m=d[1]/f[1],h=0,g=0;g<a;g++)for(var _=g*e.strides[0],v=0;v<t;v++)for(var y=p*v,b=_+Math.min(o-1,r?Math.round(y):Math.floor(y))*e.strides[1],x=0;x<n;x++)for(var S=m*x,C=b+Math.min(s-1,r?Math.round(S):Math.floor(S))*e.strides[2],w=0;w<c;w++){var T=l[C+w];u[h++]=T}return On(u,[a,t,n,c],e.dtype)},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){X([e,t],`resizeNearestNeighborBackprop`);for(var r=t.shape,i=r[0],a=r[1],o=r[2],s=r[3],c=e.shape,l=c[1],u=c[2],d=new Float32Array(i*a*o*s),f=this.readSync(e.dataId),p=[n&&l>1?a-1:a,n&&u>1?o-1:o],m=[n&&l>1?l-1:l,n&&u>1?u-1:u],h=p[0]/m[0],g=p[1]/m[1],_=1/h,v=1/g,y=2*Math.ceil(_)+2,b=2*Math.ceil(v)+2,x=0;x<i;x++)for(var S=x*t.strides[0],C=0;C<a;C++)for(var w=S+C*t.strides[1],T=Math.floor(C*_),E=Math.floor(T-y/2),D=0;D<o;D++)for(var O=w+D*t.strides[2],k=Math.floor(D*v),A=Math.floor(k-b/2),j=0;j<s;j++){for(var M=0,N=0;N<y;N++){var P=N+E;if(!(P<0||P>=l)){var F=S+P*e.strides[1],I=P*h;if(C===Math.min(a-1,n?Math.round(I):Math.floor(I)))for(var ee=0;ee<b;ee++){var te=ee+A;if(!(te<0||te>=u)){var ne=F+te*e.strides[2],L=te*g;D===Math.min(o-1,n?Math.round(L):Math.floor(L))&&(M+=f[ne+j])}}}}d[O+j]=M}return Nn(d,t.shape,t.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,a){X([e,t,n,i,a],`batchNorm`);for(var o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=this.readSync(n.dataId),l=i?this.readSync(i.dataId):new Float32Array([1]),u=a?this.readSync(a.dataId):new Float32Array([0]),d=new Float32Array(o.length),f=u.length,p=l.length,m=c.length,h=s.length,g=0,_=0,v=0,y=0,b=0;b<o.length;++b)d[b]=u[g++]+(o[b]-s[_++])*l[v++]/Math.sqrt(c[y++]+r),g>=f&&(g=0),_>=h&&(_=0),v>=p&&(v=0),y>=m&&(y=0);return Nn(d,e.shape)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){X(e,`localResponseNormalization4D`);var a=e.shape[3],o=a-1,s=this.readSync(e.dataId),c=e.size,l=new Float32Array(c);function u(e){for(var n=e%a,r=e-n+Math.max(0,n-t),i=e-n+Math.min(n+t,o),c=0;r<=i;r++){var l=s[r];c+=l*l}return c}for(var d=0;d<c;d++){var f=u(d);l[d]=s[d]*(n+r*f)**+-i}return Nn(l,e.shape)},t.prototype.LRNGrad=function(e,t,n,r,i,a,o){X(e,`LRNGrad`);for(var s=e.shape[3],c=this.readSync(e.dataId),l=this.readSync(t.dataId),u=this.readSync(n.dataId),d=new Float32Array(e.size),f=e.size,p=0;p<f;p++){for(var m=p%s,h=p-m+Math.max(0,m-r),g=p-m+Math.min(s,m+r+1),_=0,v=h;v<g;v++)_+=l[v]**2;for(_=a*_+i,v=h;v<g;v++){var y=-2*a*o*l[v]*u[p]/_;p===v&&(y+=_**+-o),y*=c[p],d[v]+=y}}return Nn(d,e.shape)},t.prototype.multinomial=function(e,t,n,r){X(e,`multinomial`);for(var i=t?e:ni(e),a=i.shape[0],o=i.shape[1],s=Rn([a,n],`int32`),c=this.readSync(s.dataId),l=this.readSync(i.dataId),u=0;u<a;++u){var d=u*o,f=new Float32Array(o-1);f[0]=l[d];for(var p=1;p<f.length;++p)f[p]=f[p-1]+l[d+p];for(var m=ir(r.toString()),h=u*n,g=0;g<n;++g){var _=m();c[h+g]=f.length;for(var v=0;v<f.length;v++)if(_<f[v]){c[h+g]=v;break}}}return s},t.prototype.oneHot=function(e,t,n,r){X(e,`oneHot`);var i=new Float32Array(e.size*t);i.fill(r);for(var a=this.readSync(e.dataId),o=0;o<e.size;++o)a[o]>=0&&a[o]<t&&(i[o*t+a[o]]=n);return jn(i,[e.size,t],`int32`)},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return X(e,`nonMaxSuppression`),ki(this.readSync(e.dataId),this.readSync(t.dataId),n,r,i)},t.prototype.fft=function(e){return this.fftBatch(e,!1)},t.prototype.ifft=function(e){return this.fftBatch(e,!0)},t.prototype.fftBatch=function(e,t){for(var n=e.shape[0],r=e.shape[1],i=K(e.shape,`float32`),a=K(e.shape,`float32`),o=En(e).as2D(n,r),s=Dn(e).as2D(n,r),c=0;c<n;c++)for(var l=o.slice([c,0],[1,r]),u=s.slice([c,0],[1,r]),d=Tn(l,u),f=this.readSync(this.fftImpl(d,t).dataId),p=0;p<r;p++){var m=wi(f,p);i.values[c*r+p]=m.real,a.values[c*r+p]=m.imag}return Tn(i.toTensor(),a.toTensor()).as2D(n,r)},t.prototype.fftImpl=function(e,t){var n=e.as1D(),r=n.size;if(this.isExponentOf2(r)){var i=this.fftRadix2(n,r,t).as2D(e.shape[0],e.shape[1]);return t&&(i=Tn(En(i).div(G(r)),Dn(i).div(G(r)))),i}var a=this.readSync(e.dataId),o=function(e){for(var t=new Float32Array(e.length/2),n=new Float32Array(e.length/2),r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}(this.fourierTransformByMatmul(a,r,t));return Tn(o.real,o.imag).as2D(e.shape[0],e.shape[1])},t.prototype.isExponentOf2=function(e){return(e&e-1)==0},t.prototype.fftRadix2=function(e,t,n){if(t===1)return e;var r=this.readSync(e.dataId),i=t/2,a=function(e){for(var t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=0;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),o=Tn(a.real,a.imag).as1D(),s=function(e){for(var t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=2;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),c=Tn(s.real,s.imag).as1D();o=this.fftRadix2(o,i,n),c=this.fftRadix2(c,i,n);var l=function(e,t){for(var n=new Float32Array(e/2),r=new Float32Array(e/2),i=0;i<Math.ceil(e/2);i++){var a=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(a),r[i]=Math.sin(a)}return{real:n,imag:r}}(t,n),u=Tn(l.real,l.imag).mul(c),d=o.add(u),f=o.sub(u);return Tn(En(d).concat(En(f)),Dn(d).concat(Dn(f))).as1D()},t.prototype.fourierTransformByMatmul=function(e,t,n){for(var r=new Float32Array(2*t),i=0;i<t;i++){for(var a=0,o=0,s=0;s<t;s++){var c=Ei(i*s,t,n),l=wi(e,s);a+=l.real*c.real-l.imag*c.imag,o+=l.real*c.imag+l.imag*c.real}n&&(a/=t,o/=t),Ti(r,a,o,i)}return r},t.prototype.depthToSpace=function(e,t,n){O(n===`NHWC`,(function(){return`Only NHWC dataFormat supported on CPU for depthToSpace. Got `+n})),O(t>1,(function(){return`blockSize should be > 1 for depthToSpace, but was: `+t}));for(var r=e.shape[0],i=e.shape[1],a=e.shape[2],o=e.shape[3],s=i*t,c=a*t,l=o/(t*t),u=this.readSync(e.dataId),d=new Float32Array(r*s*c*l),f=0,p=0;p<r;++p)for(var m=0;m<s;++m)for(var h=Math.floor(m/t),g=m%t,_=0;_<c;++_)for(var v=Math.floor(_/t),y=(g*t+_%t)*l,b=0;b<l;++b){var x=b+y+o*(v+a*(h+i*p));d[f++]=u[x]}return Nn(d,[r,s,c,l])},t.prototype.broadcastedBinaryOp=function(e,t,n,r){var i=J(e.shape,t.shape),a=K(i,n),o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=oi(e.shape,i),l=oi(t.shape,i),u=a.values;if(c.length+l.length===0)for(var d=0;d<u.length;++d)u[d]=r(o[d%o.length],s[d%s.length]);else{var f=this.bufferSync(e),p=this.bufferSync(t),m=function(n){var i=a.indexToLoc(n),d=i.slice(-e.rank);c.forEach((function(e){return d[e]=0}));var m=f.locToIndex(d),h=i.slice(-t.rank);l.forEach((function(e){return h[e]=0}));var g=p.locToIndex(h);u[n]=r(o[m],s[g])};for(d=0;d<u.length;++d)m(d)}return a.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(e,t,n){var r=J(e.shape,t.shape),i=K(r,`float32`),a=K(r,`float32`),o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=oi(e.shape,r),l=oi(t.shape,r),u=i.values,d=a.values;if(c.length+l.length===0)for(var f=0;f<u.length;f++){var p=f%o.length,m=f%s.length,h=n(o[2*p],o[2*p+1],s[2*m],s[2*m+1]);u[f]=h.real,d[f]=h.imag}else{var g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),_=this.bufferSync(this.data.get(t.dataId).complexTensors.real),v=function(r){var a=i.indexToLoc(r),f=a.slice(-e.rank);c.forEach((function(e){return f[e]=0}));var p=g.locToIndex(f),m=a.slice(-t.rank);l.forEach((function(e){return m[e]=0}));var h=_.locToIndex(m),v=n(o[2*p],o[2*p+1],s[2*h],s[2*h+1]);u[r]=v.real,d[r]=v.imag};for(f=0;f<u.length;f++)v(f)}return this.complex(i.toTensor(),a.toTensor())},t.prototype.split=function(e,t,n){return Fi(e,t,n)},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32},t.prototype.epsilon=function(){return 1e-7},t.prototype.cropAndResize=function(e,t,n,r,i,a){for(var o=e.shape,s=o[0],c=o[1],l=o[2],u=o[3],d=t.shape[0],f=r[0],p=r[1],m=K([d,f,p,u],`float32`),h=this.readSync(t.dataId),g=this.readSync(n.dataId),_=this.readSync(e.dataId),v=e.strides,y=m.strides,b=0;b<d;b++){var x=4*b,S=h[x],C=h[x+1],w=h[x+2],T=h[x+3],E=g[b];if(!(E>=s))for(var D=f>1?(w-S)*(c-1)/(f-1):0,O=p>1?(T-C)*(l-1)/(p-1):0,k=0;k<f;k++){var A=f>1?S*(c-1)+k*D:.5*(S+w)*(c-1);if(A<0||A>c-1)for(var j=0;j<p;j++)for(var M=0;M<u;M++){var N=M+j*y[2]+k*y[1]+b*y[0];m.values[N]=a}else if(i===`bilinear`){var P=Math.floor(A),F=Math.ceil(A),I=A-P;for(j=0;j<p;j++)if((se=p>1?C*(l-1)+j*O:.5*(C+T)*(l-1))<0||se>l-1)for(M=0;M<u;M++)N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=a;else{var ee=Math.floor(se),te=Math.ceil(se),ne=se-ee;for(M=0;M<u;M++){var L=_[N=M+ee*v[2]+P*v[1]+E*v[0]],re=_[N=M+te*v[2]+P*v[1]+E*v[0]],ie=_[N=M+ee*v[2]+F*v[1]+E*v[0]],ae=L+(re-L)*ne,oe=ie+(_[N=M+te*v[2]+F*v[1]+E*v[0]]-ie)*ne;N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=ae+(oe-ae)*I}}}else for(j=0;j<p;++j){var se;if((se=p>1?C*(l-1)+j*O:.5*(C+T)*(l-1))<0||se>l-1)for(M=0;M<u;M++)N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=a;else{var ce=Math.round(se),le=Math.round(A);for(M=0;M<u;M++){var ue=M+ce*v[2]+le*v[1]+E*v[0],de=M+j*y[2]+k*y[1]+b*y[0];m.values[de]=_[ue]}}}}}return m.toTensor()},t.prototype.sparseToDense=function(e,t,n,r){var i=Kr(0,e,n),a=i.sliceRank,o=i.numUpdates,s=i.sliceSize,c=i.strides,l=i.outputSize;return this.scatter(e,t,n,l,s,o,a,c,r,!1)},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=Vr(e,t),a=i[0],o=i[1],s=i[2],c=i[3];if(o===0)return On([],a,e.dtype);for(var l=new Re([o,s],e.dtype),u=this.readSync(t.dataId),d=this.readSync(e.dataId),f=0;f<o;f++){for(var p=[],m=0,h=0;h<r;h++){var g=u[f*r+h];m+=g*c[h],p.push(g)}if(m<0||m>=e.size/s)throw Error(`Invalid indices: `+p+` does not index into `+e.shape);for(var _=0;_<s;_++)l.values[f*s+_]=d[m*s+_]}return l.toTensor().reshape(a)},t.prototype.scatterND=function(e,t,n){var r=Kr(0,e,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,c=r.outputSize,l=G(0);return this.scatter(e,t,n,c,o,a,i,s,l,!0)},t.prototype.fill=function(e,t,n){var r=ae(n||=he(t),M(e));return r.fill(t),z.makeTensor(r,e,n,this)},t.prototype.onesLike=function(e){if(e.dtype===`string`)throw Error(`onesLike is not supported for string tensors`);return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){var t=ae(e.dtype,M(e.shape));return this.makeOutput(t,e.shape,e.dtype)},t.prototype.linspace=function(e,t,n){return Si(e,t,n)},t.prototype.scatter=function(e,t,n,r,i,a,o,s,c,l){var u=[r/i,i],d=this.readSync(e.dataId),f=this.readSync(t.dataId);if(r===0)return On([],n,t.dtype);var p=new Re(u,t.dtype);p.values.fill(this.readSync(c.dataId)[0]);for(var m=0;m<a;m++){for(var h=[],g=0,_=0;_<o;_++){var v=d[m*o+_];h.push(v),g+=v*s[_]}if(g<0||g>=r/i)throw Error(`Invalid indices: `+h+` does not index into `+n);for(var y=0;y<i;y++)l?p.values[g*i+y]+=f[m*i+y]:p.values[g*i+y]=t.rank===0?f[0]:f[m*i+y]}return p.toTensor().reshape(n)},t}(ai);z.registerBackend(`cpu`,(function(){return new Dd}),1);for(var Od=0,kd=[{kernelName:`NonMaxSuppressionV5`,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t,a=i.boxes,o=i.scores,s=r,c=s.maxOutputSize,l=s.iouThreshold,u=s.scoreThreshold,d=s.softNmsSigma,f=n;X(a,`NonMaxSuppressionWithScore`);var p=Ai(f.data.get(a.dataId).values,f.data.get(o.dataId).values,c,l,u,d);return[p.selectedIndices,p.selectedScores]}},{kernelName:`Square`,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n;X(r,`square`);for(var a=i.data.get(r.dataId).values,o=new Float32Array(a.length),s=0;s<a.length;++s){var c=a[s];o[s]=c*c}return{dataId:i.write(o,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:Ls,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,a=r.b,o=n;X([i,a],Ls);var s=o.data.get(i.dataId).values,c=o.data.get(a.dataId).values,l=function(e,t,n,r,i,a){var o=J(e,t),s=o.length,c=ve(o),l=ie(i,M(o)),u=e.length,d=t.length,f=ve(e),p=ve(t),m=oi(e,o),h=oi(t,o);if(m.length+h.length===0)for(var g=0;g<l.length;++g)l[g]=a(n[g%n.length],r[g%r.length]);else{var _=function(e){var t=Oe(e,s,c),i=t.slice(-u);m.forEach((function(e){return i[e]=0}));var o=De(i,u,f),g=t.slice(-d);h.forEach((function(e){return g[e]=0}));var _=De(g,d,p);l[e]=a(n[o],r[_])};for(g=0;g<l.length;++g)_(g)}return[l,o]}(i.shape,a.shape,s,c,i.dtype,(function(e,t){var n=e-t;return n*n})),u=l[0],d=l[1];return{dataId:o.write(u,d,i.dtype),shape:d,dtype:i.dtype}}}];Od<kd.length;Od++)x(kd[Od]);for(var Ad,jd=function(e){this.variableNames=[`A`];var t=Wi(),n=e[0],r=e[1];this.outputShape=e,this.userCode=`
|
|
3743
|
+
============================`));var r={};return this.data.set(r,{values:e,dtype:n}),r},t.prototype.move=function(e,t,n,r){this.data.set(e,{values:t,dtype:r})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){return[2,this.readSync(e)]}))}))},t.prototype.readSync=function(e){var t=this.data.get(e),n=t.dtype,r=t.complexTensors;return n===`complex64`?Ii(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),n=t;if(e.dtype===`string`)try{n=t.map((function(e){return Re(e)}))}catch{throw Error(`Failed to decode encoded string bytes into utf-8`)}return J(e.shape,e.dtype,n)},t.prototype.makeOutput=function(e,t,n){var r=this.write(e,t,n);return V.makeTensorFromDataId(r,t,n,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){return t=Fe(),e(),[2,{kernelMs:Fe()-t}]}))}))},t.prototype.memory=function(){return{unreliable:!0,reasons:[`The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less.`]}},t.prototype.complex=function(e,t){var n=this.makeOutput(null,e.shape,`complex64`);return this.data.get(n.dataId).complexTensors={real:V.keep(e.clone()),imag:V.keep(t.clone())},n},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(X(e,`slice`),ui(e.shape,t,n)){var r=di(t,e.strides),i=R(n);return Bn(this.readSync(e.dataId).subarray(r,r+i),n,e.dtype)}for(var a=J(n,e.dtype),o=this.bufferSync(e),s=0;s<a.size;++s){var c=a.indexToLoc(s).map((function(e,n){return e+t[n]}));a.values[s]=o.get.apply(o,c)}return a.toTensor()},t.prototype.stridedSlice=function(e,t,n,r){X(e,`stridedSlice`);var i=si(t,n,r);if(i.some((function(e){return e===0})))return Bn([],i);for(var a=J(i,e.dtype),o=this.bufferSync(e),s=0;s<a.size;s++){for(var c=a.indexToLoc(s),l=Array(c.length),u=0;u<l.length;u++)l[u]=c[u]*r[u]+t[u];a.set.apply(a,[o.get.apply(o,l)].concat(c))}return a.toTensor()},t.prototype.diag=function(e){for(var t=this.readSync(e.dataId),n=J([e.size,e.size],e.dtype),r=n.values,i=0;i<t.length;i++)r[i*e.size+i]=t[i];return n.toTensor()},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=Array(e.rank-1),i=0,a=0;a<e.rank;a++)a!==t&&(r[i++]=e.shape[a]);var o=Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=Array(n);for(a=0;a<c.length;a++)o[t]=a,c[a]=this.slice(e,o,s).reshape(r);return c},t.prototype.reverse=function(e,t){X(e,`reverse`);for(var n=J(e.shape,e.dtype),r=this.bufferSync(e),i=function(i){var a=n.indexToLoc(i),o=a.slice();t.forEach((function(t){return o[t]=e.shape[t]-1-o[t]})),n.set.apply(n,[r.get.apply(r,o)].concat(a))},a=0;a<n.size;a++)i(a);return n.toTensor()},t.prototype.concat=function(e,t){var n=this;if(e[0].dtype===`complex64`){var r=e.map((function(e){return Rn(e)})),i=e.map((function(e){return zn(e)}));return Ln(this.concat(r,t),this.concat(i,t))}var a=e.map((function(e){var n=R(e.shape.slice(t));return e.as2D(-1,n)})),o=In(a.map((function(e){return e.shape})),1),s=J(o,e[0].dtype).values;if(a[0].shape[0]===1){var c=0;a.forEach((function(e){s.set(n.readSync(e.dataId),c),c+=e.size}))}else{var l=0;a.forEach((function(e){for(var t=n.readSync(e.dataId),r=0,i=0;i<e.shape[0];++i)for(var a=i*o[1]+l,c=0;c<e.shape[1];++c)s[a+c]=t[r++];l+=e.shape[1]}))}return Bn(s,In(e.map((function(e){return e.shape})),t),e[0].dtype)},t.prototype.neg=function(e){return X(e,`neg`),this.multiply(q(-1),e)},t.prototype.add=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e+n,imag:t+r}})):this.broadcastedBinaryOp(e,t,st(e.dtype,t.dtype),(function(e,t){return e+t}))},t.prototype.addN=function(e){var t=this;X(e,`addN`);for(var n=e.map((function(e){return t.readSync(e.dataId)})),r=J(e[0].shape,e[0].dtype),i=r.values,a=0;a<e.length;a++)for(var o=n[a],s=0;s<i.length;s++)i[s]+=o[s];return r.toTensor()},t.prototype.softmax=function(e,t){var n=me([t],e.shape),r=this.max(e,n),i=An(r.shape,n),a=this.subtract(e,r.reshape(i)),o=this.exp(a),s=this.sum(o,n).reshape(i);return this.realDivide(o,s)},t.prototype.subtract=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e-n,imag:t-r}})):this.broadcastedBinaryOp(e,t,st(e.dtype,t.dtype),(function(e,t){return e-t}))},t.prototype.pow=function(e,t){return X([e,t],`pow`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return e**+t}))},t.prototype.batchMatMul=function(e,t,n,r){X([e,t],`matMul`);for(var i=n?e.shape[1]:e.shape[2],a=n?e.shape[2]:e.shape[1],o=r?t.shape[1]:t.shape[2],s=e.shape[0],c=this.readSync(e.dataId),l=this.readSync(t.dataId),u=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],d=u[0],f=u[1],p=u[2],m=r?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],h=m[0],g=m[1],_=m[2],v=a*o,y=J([s,a,o],e.dtype),b=y.values,x=this.blockSize,S=0;S<s;S++)for(var C=0;C<a;C+=x)for(var w=0;w<o;w+=x)for(var T=0;T<i;T+=x)for(var E=Math.min(C+x,a),D=Math.min(w+x,o),O=Math.min(T+x,i),k=C;k<E;k++)for(var A=w;A<D;A++){for(var j=0,M=T;M<O;M++)j+=c[S*d+k*f+M*p]*l[M*h+A*g+S*_];b[S*v+(k*o+A)]+=j}return y.toTensor()},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,a=e.bias,o=e.activation,s=e.preluActivationWeights,c=this.batchMatMul(t,n,r,i);return a&&(c=this.add(c,a)),o&&(c=Bd(this,c,o,s)),c},t.prototype.multiply=function(e,t){return e.dtype===`complex64`||t.dtype===`complex64`?this.broadcastedBinaryComplexOp(e.cast(`complex64`),t.cast(`complex64`),(function(e,t,n,r){return{real:e*n-t*r,imag:e*r+t*n}})):this.broadcastedBinaryOp(e,t,st(e.dtype,t.dtype),(function(e,t){return e*t}))},t.prototype.realDivide=function(e,t){return X([e,t],`realDivide`),this.broadcastedBinaryOp(e,t,`float32`,(function(e,t){return e/t}))},t.prototype.floorDiv=function(e,t){return X([e,t],`floorDiv`),this.broadcastedBinaryOp(e,t,`int32`,(function(e,t){return Math.floor(e/t)}))},t.prototype.sum=function(e,t){X(e,`sum`),jn(`sum`,t,e.rank);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,st(e.dtype,`int32`)),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=0,f=0;f<o;++f)d+=c[u+f];s[l]=d}return a},t.prototype.prod=function(e,t){X(e,`sum`);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,st(e.dtype,`int32`)),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=1,f=0;f<o;++f)d*=c[u+f];s[l]=d}return a},t.prototype.unsortedSegmentSum=function(e,t,n){X(e,`unsortedSegmentSum`);for(var r=[],i=e.rank-t.rank,a=0;a<i;++a)t=t.expandDims(a+1);for(a=0;a<n;++a){var o=bl(q(a,`int32`),t).asType(`float32`).mul(e).sum(0);r.push(o)}return Ur(r)},t.prototype.argMin=function(e,t){X(e,`argMin`);var n=[t];jn(`argMin`,n,e.rank);for(var r=kn(e.shape,n),i=r[0],a=r[1],o=Xn(i,`int32`),s=R(a),c=this.readSync(o.dataId),l=this.readSync(e.dataId),u=0;u<c.length;++u){for(var d=u*s,f=l[d],p=0,m=0;m<s;++m){var h=l[d+m];h<f&&(f=h,p=m)}c[u]=p}return o},t.prototype.argMax=function(e,t){X(e,`argMax`);var n=[t];jn(`argMax`,n,e.rank);for(var r=kn(e.shape,n),i=r[0],a=r[1],o=Xn(i,`int32`),s=R(a),c=this.readSync(o.dataId),l=this.readSync(e.dataId),u=0;u<c.length;++u){for(var d=u*s,f=l[d],p=0,m=0;m<s;++m){var h=l[d+m];h>f&&(f=h,p=m)}c[u]=p}return o},t.prototype.cumsum=function(e,t,n,r){if(X(e,`cumsum`),t!==e.rank-1)throw Error(`backend.cumsum in CPU expects an inner-most axis=`+(e.rank-1)+` but got axis=`+t);for(var i=st(e.dtype,`int32`),a=Xn(e.shape,i),o=this.readSync(a.dataId),s=this.readSync(e.dataId),c=e.shape[e.rank-1],l=r?function(e,t){return e+c-t-1}:function(e,t){return e+t},u=0;u<s.length;u+=c)for(var d=0;d<c;d++){var f=l(u,d);if(d===0)o[f]=n?0:s[f];else{var p=l(u,d-1);o[f]=n?s[p]+o[p]:s[f]+o[p]}}return a},t.prototype.equal=function(e,t){return X([e,t],`equal`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e===t?1:0}))},t.prototype.notEqual=function(e,t){return X([e,t],`notEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e===t?0:1}))},t.prototype.less=function(e,t){return X([e,t],`less`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e<t?1:0}))},t.prototype.lessEqual=function(e,t){return X([e,t],`lessEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e<=t?1:0}))},t.prototype.greater=function(e,t){return X([e,t],`greater`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e>t?1:0}))},t.prototype.greaterEqual=function(e,t){return X([e,t],`greaterEqual`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e>=t?1:0}))},t.prototype.logicalNot=function(e){X(e,`logicalNot`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)n[r]=t[r]?0:1;return this.makeOutput(n,e.shape,`bool`)},t.prototype.logicalAnd=function(e,t){return X([e,t],`logicalAnd`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e&&t}))},t.prototype.logicalOr=function(e,t){return X([e,t],`logicalOr`),this.broadcastedBinaryOp(e,t,`bool`,(function(e,t){return e||t}))},t.prototype.select=function(e,t,n){X([e,t,n],`select`);for(var r=this.readSync(e.dataId),i=this.readSync(t.dataId),a=this.readSync(n.dataId),o=Xn(t.shape,st(t.dtype,n.dtype)),s=this.readSync(o.dataId),c=0,l=e.rank===0||e.rank>1||t.rank===1?1:R(t.shape.slice(1)),u=0;u<r.length;u++)for(var d=0;d<l;d++)r[u]===1?s[c++]=i[u]:s[c++]=a[u];return o},t.prototype.where=function(e){X([e],`where`);var t=this.readSync(e.dataId);return Zi(e.shape,t)},t.prototype.topk=function(e,t,n){return X(e,`topk`),Xi(this.readSync(e.dataId),e.shape,e.dtype,t)},t.prototype.min=function(e,t){X(e,`min`),jn(`min`,t,e.rank);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,e.dtype),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];p<d&&(d=p)}s[l]=d}return a},t.prototype.minimum=function(e,t){return X([e,t],`minimum`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.min(e,t)}))},t.prototype.mod=function(e,t){return X([e,t],`mod`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}))},t.prototype.max=function(e,t){X(e,`max`),jn(`max`,t,e.rank);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,e.dtype),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];p>d&&(d=p)}s[l]=d}return a},t.prototype.maximum=function(e,t){return X([e,t],`maximum`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.max(e,t)}))},t.prototype.all=function(e,t){X(e,`all`),jn(`all`,t,e.rank);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,e.dtype),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];d&&=p}s[l]=d}return a},t.prototype.any=function(e,t){X(e,`any`),jn(`any`,t,e.rank);for(var n=kn(e.shape,t),r=n[0],i=n[1],a=Xn(r,e.dtype),o=R(i),s=this.readSync(a.dataId),c=this.readSync(e.dataId),l=0;l<s.length;++l){for(var u=l*o,d=c[u],f=0;f<o;++f){var p=c[u+f];d||=p}s[l]=d}return a},t.prototype.squaredDifference=function(e,t){return X([e,t],`squaredDifference`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e-t;return n*n}))},t.prototype.ceil=function(e){X(e,`ceil`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.ceil(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.floor=function(e){X(e,`floor`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.floor(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.sign=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)t[r]<0?n[r]=-1:t[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,e.shape,`float32`)},t.prototype.isNaN=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isNaN(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.isInf=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Math.abs(t[r])===1/0&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.isFinite=function(e){X(e,`x`);for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isFinite(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,`bool`)},t.prototype.round=function(e){X(e,`round`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=Math.floor(t[r]);t[r]-i<.5?n[r]=Math.floor(t[r]):t[r]-i>.5?n[r]=Math.ceil(t[r]):n[r]=i%2==0?i:i+1}return this.makeOutput(n,e.shape,`float32`)},t.prototype.exp=function(e){X(e,`exp`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.exp(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.expm1=function(e){X(e,`expm1`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.expm1(t[r]);return this.makeOutput(n,e.shape,`float32`)},t.prototype.log=function(e){X(e,`log`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.log1p=function(e){X(e,`log1p`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log1p(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.sqrt=function(e){X(e,`sqrt`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.sqrt(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.rsqrt=function(e){X(e,`rsqrt`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=1/Math.sqrt(i)}return this.makeOutput(n,e.shape,`float32`)},t.prototype.reciprocal=function(e){X(e,`reciprocal`);for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=1/t[r];return this.makeOutput(n,e.shape,`float32`)},t.prototype.linear=function(e){return e},t.prototype.relu=function(e){X(e,`relu`);for(var t=Xn(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.max(0,r[i]);return t},t.prototype.relu6=function(e){X(e,`relu`);for(var t=Xn(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.min(Math.max(0,r[i]),6);return t},t.prototype.prelu=function(e,t){return X([e,t],`prelu`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return e<0?t*e:e}))},t.prototype.elu=function(e){X(e,`elu`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=n[r];t[r]=i>=0?i:Math.exp(i)-1}return this.makeOutput(t,e.shape,`float32`)},t.prototype.eluDer=function(e,t){X([e,t],`eluDer`);for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),i=this.readSync(e.dataId),a=0;a<r.length;++a){var o=r[a];n[a]=o>=1?i[a]:i[a]*(o+1)}return this.makeOutput(n,t.shape,`float32`)},t.prototype.selu=function(e){X(e,`selu`);for(var t=gs,n=_s,r=new Float32Array(e.size),i=this.readSync(e.dataId),a=0;a<i.length;++a){var o=i[a];r[a]=o>=0?n*o:t*(Math.exp(o)-1)}return this.makeOutput(r,e.shape,`float32`)},t.prototype.clip=function(e,t,n){X(e,`clip`);for(var r=new Float32Array(e.size),i=this.readSync(e.dataId),a=0;a<i.length;++a){var o=i[a];r[a]=o>n?n:o<t?t:o}return this.makeOutput(r,e.shape,`float32`)},t.prototype.abs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.abs(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.complexAbs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<e.size;++r){var i=n[2*r],a=n[2*r+1];t[r]=Math.hypot(i,a)}return this.makeOutput(t,e.shape,`float32`)},t.prototype.int=function(e){X(e,`int`);for(var t=new Int32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=n[r];return this.makeOutput(t,e.shape,`int32`)},t.prototype.sigmoid=function(e){X(e,`sigmoid`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(t,e.shape,`float32`)},t.prototype.softplus=function(e){X(e,`softplus`);for(var t=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var a=r[i]>-t,o=r[i]<t,s=Math.exp(r[i]),c=void 0;c=o?s:a?r[i]:Math.log(1+s),n[i]=c}return this.makeOutput(n,e.shape,`float32`)},t.prototype.sin=function(e){X(e,`sin`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sin(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.cos=function(e){X(e,`cos`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cos(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.tan=function(e){X(e,`tan`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.tan(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.asin=function(e){X(e,`asin`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asin(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.acos=function(e){X(e,`acos`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acos(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atan=function(e){X(e,`atan`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atan(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atan2=function(e,t){return X([e,t],`atan2`),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.atan2(e,t)}))},t.prototype.sinh=function(e){X(e,`sinh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sinh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.cosh=function(e){X(e,`cosh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cosh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.tanh=function(e){X(e,`tanh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=le(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.asinh=function(e){X(e,`asinh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asinh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.acosh=function(e){X(e,`acosh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acosh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.atanh=function(e){X(e,`atanh`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atanh(n[r]);return this.makeOutput(t,e.shape,`float32`)},t.prototype.erf=function(e){X(e,`erf`);for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=Math.sign(n[r]),a=Math.abs(n[r]),o=1/(1+.3275911*a);t[r]=i*(1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-a*a))}return this.makeOutput(t,e.shape,`float32`)},t.prototype.step=function(e,t){t===void 0&&(t=0),X(e,`step`);for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var a=r[i];isNaN(a)?n[i]=NaN:n[i]=a>0?1:t}return this.makeOutput(n,e.shape,`float32`)},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights,s=this.conv2d(t,n,r);return i&&(s=this.add(s,i)),a&&(s=Bd(this,s,a,o)),s},t.prototype.conv2d=function(e,t,n){X([e,t],`conv2d`);for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,l=n.dataFormat===`channelsLast`,u=J(n.outShape,e.dtype),d=e.strides[0],f=l?e.strides[1]:e.strides[2],p=l?e.strides[2]:1,m=l?1:e.strides[1],h=u.strides[0],g=l?u.strides[1]:u.strides[2],_=l?u.strides[2]:1,v=l?1:u.strides[1],y=this.readSync(e.dataId),b=this.readSync(t.dataId),x=u.values,S=0;S<n.batchSize;++S)for(var C=S*d,w=S*h,T=0;T<n.outHeight;++T)for(var E=w+T*g,D=T*n.strideHeight-c,O=0;O<r;O++){var k=D+O*a;if(!(k<0||k>=n.inHeight))for(var A=O*t.strides[0],j=C+k*f,M=0;M<n.outWidth;++M)for(var N=E+M*_,P=M*n.strideWidth-s,F=0;F<i;F++){var ee=P+F*o;if(!(ee<0||ee>=n.inWidth))for(var te=j+ee*p,ne=A+F*t.strides[1],re=0;re<n.inChannels;++re){for(var ie=y[te+re*m],ae=0;ae<n.outChannels;++ae)x[N+ae*v]+=ie*b[ne+ae];ne+=n.outChannels}}}return u.toTensor()},t.prototype.conv3d=function(e,t,n){for(var r=n.filterDepth,i=n.filterHeight,a=n.filterWidth,o=n.dilationDepth,s=n.dilationHeight,c=n.dilationWidth,l=n.padInfo.front,u=n.padInfo.left,d=n.padInfo.top,f=J(n.outShape,e.dtype),p=this.readSync(e.dataId),m=this.readSync(t.dataId),h=f.values,g=0;g<n.batchSize;++g)for(var _=g*e.strides[0],v=g*f.strides[0],y=0;y<n.outDepth;++y)for(var b=v+y*f.strides[1],x=y*n.strideDepth-l,S=0;S<r;S++){var C=x+S*o;if(!(C<0||C>=n.inDepth))for(var w=S*t.strides[0],T=_+C*e.strides[1],E=0;E<n.outHeight;++E)for(var D=b+E*f.strides[2],O=E*n.strideHeight-d,k=0;k<i;k++){var A=O+k*s;if(!(A<0||A>=n.inHeight))for(var j=w+k*t.strides[1],M=T+A*e.strides[2],N=0;N<n.outWidth;++N)for(var P=D+N*n.outChannels,F=N*n.strideWidth-u,ee=0;ee<a;ee++){var te=F+ee*c;if(!(te<0||te>=n.inWidth))for(var ne=j+ee*t.strides[2],re=M+te*n.inChannels,ie=ne,ae=0;ae<n.inChannels;++ae){for(var I=p[re+ae],L=0;L<n.outChannels;++L)h[P+L]+=I*m[ie+L];ie+=n.outChannels}}}}return f.toTensor()},t.prototype.conv2dDerInput=function(e,t,n){X([e,t],`conv2dDerInput`);for(var r=J(n.inShape,`float32`),i=r.values,a=this.readSync(e.dataId),o=this.readSync(t.dataId),s=t.strides,c=s[0],l=s[1],u=s[2],d=n.batchSize,f=n.filterHeight,p=n.filterWidth,m=n.inChannels,h=n.inHeight,g=n.inWidth,_=n.outChannels,v=n.outHeight,y=n.outWidth,b=n.strideHeight,x=n.strideWidth,S=n.dataFormat,C=f-1-n.padInfo.top,w=p-1-n.padInfo.left,T=S===`channelsLast`,E=r.strides[0],D=T?r.strides[1]:r.strides[2],O=T?r.strides[2]:1,k=T?1:r.strides[1],A=e.strides[0],j=T?e.strides[1]:e.strides[2],M=T?e.strides[2]:1,N=T?1:e.strides[1],P=0;P<d;++P)for(var F=0;F<m;++F)for(var ee=0;ee<h;++ee)for(var te=ee-C,ne=Math.max(0,Math.ceil(te/b)),re=Math.min(v,(f+te)/b),ie=0;ie<g;++ie){for(var ae=ie-w,I=Math.max(0,Math.ceil(ae/x)),L=Math.min(y,(p+ae)/x),oe=0,se=ne;se<re;++se)for(var R=se*b-te,z=I;z<L;++z)for(var ce=A*P+j*se+M*z,le=c*(f-1-R)+l*(p-1-(z*x-ae))+u*F,ue=0;ue<_;++ue)oe+=a[ce+N*ue]*o[le+ue];i[E*P+D*ee+O*ie+k*F]=oe}return r.toTensor()},t.prototype.conv3dDerInput=function(e,t,n){for(var r=J(n.inShape,`float32`),i=r.values,a=r.strides,o=a[0],s=a[1],c=a[2],l=a[3],u=this.readSync(e.dataId),d=e.strides,f=d[0],p=d[1],m=d[2],h=d[3],g=this.readSync(t.dataId),_=t.strides,v=_[0],y=_[1],b=_[2],x=_[3],S=n.batchSize,C=n.filterDepth,w=n.filterHeight,T=n.filterWidth,E=n.inChannels,D=n.inDepth,O=n.inHeight,k=n.inWidth,A=n.outChannels,j=n.outDepth,M=n.outHeight,N=n.outWidth,P=n.strideDepth,F=n.strideHeight,ee=n.strideWidth,te=C-1-n.padInfo.front,ne=w-1-n.padInfo.top,re=T-1-n.padInfo.left,ie=0;ie<S;++ie)for(var ae=0;ae<E;++ae)for(var I=0;I<D;++I)for(var L=I-te,oe=Math.max(0,Math.ceil(L/P)),se=Math.min(j,(C+L)/P),R=0;R<O;++R)for(var z=R-ne,ce=Math.max(0,Math.ceil(z/F)),le=Math.min(M,(w+z)/F),ue=0;ue<k;++ue){for(var de=ue-re,fe=Math.max(0,Math.ceil(de/ee)),pe=Math.min(N,(T+de)/ee),me=0,he=oe;he<se;++he)for(var ge=he*P-L,_e=ce;_e<le;++_e)for(var ve=_e*F-z,ye=fe;ye<pe;++ye)for(var be=f*ie+p*he+m*_e+h*ye,xe=v*(C-1-ge)+y*(w-1-ve)+b*(T-1-(ye*ee-de))+x*ae,Se=0;Se<A;++Se)me+=u[be+Se]*g[xe+Se];i[o*ie+s*I+c*R+l*ue+ae]=me}return r.toTensor()},t.prototype.conv2dDerFilter=function(e,t,n){X([e,t],`conv2dDerFilter`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dataFormat===`channelsLast`,c=J(n.filterShape,`float32`),l=n.padInfo.left,u=n.padInfo.top,d=this.bufferSync(e),f=this.bufferSync(t),p=0;p<a;++p)for(var m=Math.max(0,Math.ceil((u-p)/r)),h=Math.min(n.outHeight,(n.inHeight+u-p)/r),g=0;g<o;++g)for(var _=Math.max(0,Math.ceil((l-g)/i)),v=Math.min(n.outWidth,(n.inWidth+l-g)/i),y=0;y<n.inChannels;++y)for(var b=0;b<n.outChannels;++b){for(var x=0,S=0;S<n.batchSize;++S)for(var C=m;C<h;++C)for(var w=p+C*r-u,T=_;T<v;++T){var E=g+T*i-l;x+=s?d.get(S,w,E,y)*f.get(S,C,T,b):d.get(S,y,w,E)*f.get(S,b,C,T)}c.set(x,p,g,y,b)}return c.toTensor()},t.prototype.conv3dDerFilter=function(e,t,n){for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,c=n.filterWidth,l=J(n.filterShape,`float32`),u=l.values,d=l.strides,f=d[0],p=d[1],m=d[2],h=d[3],g=this.readSync(t.dataId),_=t.strides,v=_[0],y=_[1],b=_[2],x=_[3],S=this.readSync(e.dataId),C=e.strides,w=C[0],T=C[1],E=C[2],D=C[3],O=n.padInfo.front,k=n.padInfo.left,A=n.padInfo.top,j=0;j<o;++j)for(var M=Math.max(0,Math.ceil((O-j)/r)),N=Math.min(n.outDepth,(n.inDepth+O-j)/r),P=j*f,F=0;F<s;++F)for(var ee=Math.max(0,Math.ceil((A-F)/i)),te=Math.min(n.outHeight,(n.inHeight+A-F)/i),ne=F*p+P,re=0;re<c;++re)for(var ie=Math.max(0,Math.ceil((k-re)/a)),ae=Math.min(n.outWidth,(n.inWidth+k-re)/a),I=re*m+ne,L=0;L<n.inChannels;++L)for(var oe=L*h+I,se=0;se<n.outChannels;++se){for(var R=0,z=0;z<n.batchSize;++z)for(var ce=z*w,le=z*v,ue=M;ue<N;++ue)for(var de=(j+ue*r-O)*T+ce,fe=ue*y+le,pe=ee;pe<te;++pe)for(var me=(F+pe*i-A)*E+de,he=pe*b+fe,ge=ie;ge<ae;++ge){var _e=ge*x+he;R+=S[(re+ge*a-k)*D+me+L]*g[_e+se]}u[oe+se]=R}return l.toTensor()},t.prototype.fusedDepthwiseConv2D=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,a=e.activation,o=e.preluActivationWeights,s=this.depthwiseConv2D(t,n,r);return i&&(s=this.add(s,i)),a&&(s=Bd(this,s,a,o)),s},t.prototype.depthwiseConv2D=function(e,t,n){X([e,t],`depthwiseConv2D`);for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,u=J(n.outShape,e.dtype),d=this.readSync(e.dataId),f=this.readSync(t.dataId),p=u.values,m=0;m<n.batchSize;++m)for(var h=m*e.strides[0],g=m*u.strides[0],_=0;_<n.outHeight;++_)for(var v=g+_*u.strides[1],y=_*n.strideHeight-s,b=0;b<r;++b){var x=y+b*a;if(!(x<0||x>=n.inHeight))for(var S=b*t.strides[0],C=h+x*e.strides[1],w=0;w<n.outWidth;++w)for(var T=v+w*u.strides[2],E=w*n.strideWidth-c,D=0;D<i;++D){var O=E+D*o;if(!(O<0||O>=n.inWidth))for(var k=S+D*t.strides[1],A=C+O*n.inChannels,j=T,M=k,N=0;N<n.inChannels;++N){for(var P=d[A+N],F=0;F<l;++F)p[j+F]+=P*f[M+F];j+=l,M+=l}}}return u.toTensor()},t.prototype.depthwiseConv2DDerInput=function(e,t,n){X([e,t],`depthwiseConv2DDerInput`);for(var r=J(n.inShape,`float32`),i=r.values,a=r.strides,o=a[0],s=a[1],c=a[2],l=this.readSync(e.dataId),u=e.strides,d=u[0],f=u[1],p=u[2],m=this.readSync(t.dataId),h=t.strides,g=h[0],_=h[1],v=h[2],y=n.batchSize,b=n.filterHeight,x=n.filterWidth,S=n.inChannels,C=n.inHeight,w=n.inWidth,T=n.outChannels,E=n.outHeight,D=n.outWidth,O=n.strideHeight,k=n.strideWidth,A=b-1-n.padInfo.top,j=x-1-n.padInfo.left,M=T/S,N=0;N<y;++N)for(var P=0;P<S;++P)for(var F=0;F<C;++F)for(var ee=F-A,te=Math.max(0,Math.ceil(ee/O)),ne=Math.min(E,(b+ee)/O),re=0;re<w;++re){for(var ie=re-j,ae=Math.max(0,Math.ceil(ie/k)),I=Math.min(D,(x+ie)/k),L=0,oe=te;oe<ne;++oe)for(var se=oe*O-ee,R=ae;R<I;++R)for(var z=d*N+f*oe+p*R,ce=g*(b-1-se)+_*(x-1-(R*k-ie))+v*P,le=0;le<M;++le)L+=l[z+(P*M+le)]*m[ce+le];i[o*N+s*F+c*re+P]=L}return r.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){X([e,t],`depthwiseConv2DDerFilter`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=J(n.filterShape,`float32`),c=n.padInfo.left,l=n.padInfo.top,u=n.outChannels/n.inChannels,d=this.bufferSync(e),f=this.bufferSync(t),p=0;p<a;++p)for(var m=Math.max(0,Math.ceil((l-p)/r)),h=Math.min(n.outHeight,(n.inHeight+l-p)/r),g=0;g<o;++g)for(var _=Math.max(0,Math.ceil((c-g)/i)),v=Math.min(n.outWidth,(n.inWidth+c-g)/i),y=0;y<n.outChannels;++y){for(var b=Math.trunc(y/u),x=y%u,S=0,C=0;C<n.batchSize;++C)for(var w=m;w<h;++w)for(var T=p+w*r-l,E=_;E<v;++E){var D=g+E*i-c;S+=d.get(C,T,D,b)*f.get(C,w,E,y)}s.set(S,p,g,b,x)}return s.toTensor()},t.prototype.tile=function(e,t){return X(e,`tile`),Yi(this.bufferSync(e),t)},t.prototype.pad=function(e,t,n){X(e,`pad`);var r=t.map((function(t,n){return t[0]+e.shape[n]+t[1]})),i=t.map((function(e){return e[0]})),a=this.bufferSync(e),o=J(r,e.dtype);n!==0&&o.values.fill(n);for(var s=0;s<e.size;s++){var c=a.indexToLoc(s),l=c.map((function(e,t){return e+i[t]}));o.set.apply(o,[a.get.apply(a,c)].concat(l))}return o.toTensor()},t.prototype.transpose=function(e,t){X(e,`transpose`);for(var n=Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[t[r]];var i=this.readSync(e.dataId),a=J(n,e.dtype),o=this.bufferSync(e);for(r=0;r<e.size;++r){for(var s=o.indexToLoc(r),c=Array(s.length),l=0;l<c.length;l++)c[l]=s[t[l]];var u=a.locToIndex(c);a.values[u]=i[r]}return a.toTensor()},t.prototype.gather=function(e,t,n){X([e,t],`gather`);var r=e.shape.slice(),i=this.readSync(t.dataId);r[n]=i.length;for(var a=J(r,e.dtype),o=this.bufferSync(e),s=0;s<a.size;++s){var c=a.indexToLoc(s),l=c.slice();l[n]=i[c[n]];var u=o.locToIndex(l);a.values[s]=o.values[u]}return a.toTensor()},t.prototype.batchToSpaceND=function(e,t,n){X([e],`batchToSpaceND`);var r=t.reduce((function(e,t){return e*t})),i=Jr(e.shape,t,r),a=Yr(i.length,t.length),o=Xr(e.shape,t,r),s=Zr(n,t.length),c=Qr(o,n,t.length);return e.reshape(i).transpose(a).reshape(o).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){X([e],`spaceToBatchND`);var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var a=1+t.length;a<e.shape.length;++a)i.push([0,0]);var o=e.pad(i),s=Jr(o.shape,t,r,!1),c=Yr(s.length,t.length,!1),l=Xr(o.shape,t,r,!1);return o.reshape(s).transpose(c).reshape(l)},t.prototype.pool=function(e,t,n){X(e,`pool`);for(var r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,u=t.padInfo.left,d=n===`max`?-1/0:1/0,f=this.readSync(e.dataId),p=J(t.outShape,e.dtype),m=p.values,h=t.outShape[1]*t.outShape[2]*t.outShape[3],g=t.outShape[2]*t.outShape[3],_=t.outShape[3],v=0;v<t.batchSize;++v)for(var y=v*h,b=v*e.strides[0],x=0;x<t.inChannels;++x)for(var S=0;S<t.outHeight;++S)for(var C=S*r-l,w=Math.max(0,C),T=Math.min(t.inHeight,s+C),E=y+S*g,D=0;D<t.outWidth;++D){for(var O=D*i-u,k=Math.max(0,O),A=Math.min(t.inWidth,c+O),j=d,M=0,N=0,P=w;P<T;P+=a){for(var F=b+P*e.strides[1],ee=k;ee<A;ee+=o){var te=f[F+ee*e.strides[2]+x];n===`max`&&te>j?j=te:n===`avg`&&(M+=te,N++)}if(isNaN(j))break}m[E+D*_+x]=n===`avg`?M/N:j}return p.toTensor()},t.prototype.maxPool=function(e,t){return this.pool(e,t,`max`)},t.prototype.maxPoolPositions=function(e,t){for(var n=J(t.outShape,`int32`),r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,u=t.padInfo.left,d=this.bufferSync(e),f=0;f<t.batchSize;++f)for(var p=0;p<t.inChannels;++p)for(var m=0;m<t.outHeight;++m){for(var h=m*r-l,g=h;g<0;)g+=a;for(var _=Math.min(t.inHeight,s+h),v=0;v<t.outWidth;++v){for(var y=v*i-u,b=y;b<0;)b+=o;for(var x=Math.min(t.inWidth,c+y),S=-1/0,C=-1,w=g;w<_;w+=a)for(var T=w-h,E=b;E<x;E+=o){var D=E-y,O=d.get(f,w,E,p);O>S&&(S=O,C=T*c+D)}n.set(C,f,m,v,p)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(e,t,n,r){X([t,n],`maxPoolBackprop`);for(var i=this.maxPoolPositions(t,r),a=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterHeight,u=r.effectiveFilterWidth,d=u-1-r.padInfo.left,f=l-1-r.padInfo.top,p=J(t.shape,`float32`),m=this.bufferSync(i),h=this.bufferSync(e),g=0;g<r.batchSize;++g)for(var _=0;_<r.inChannels;++_)for(var v=0;v<r.inHeight;++v)for(var y=0;y<r.inWidth;++y){for(var b=v-f,x=y-d,S=0,C=0;C<l;C+=s){var w=(b+C)/a;if(!(w<0||w>=r.outHeight||Math.floor(w)!==w))for(var T=0;T<u;T+=c){var E=(x+T)/o;if(!(E<0||E>=r.outWidth||Math.floor(E)!==E)){var D=l*u-1-m.get(g,w,E,_)===C*u+T?1:0;D!==0&&(S+=h.get(g,w,E,_)*D)}}}p.set(S,g,v,y,_)}return p.toTensor()},t.prototype.avgPoolBackprop=function(e,t,n){X([e,t],`avgPoolBackprop`);for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,c=n.dilationWidth,l=n.effectiveFilterHeight,u=n.effectiveFilterWidth,d=u-1-n.padInfo.left,f=l-1-n.padInfo.top,p=J(t.shape,`float32`),m=1/(a*o),h=this.bufferSync(e),g=0;g<n.batchSize;++g)for(var _=0;_<n.inChannels;++_)for(var v=0;v<n.inHeight;++v)for(var y=0;y<n.inWidth;++y){for(var b=v-f,x=y-d,S=0,C=0;C<l;C+=s){var w=(b+C)/r;if(!(w<0||w>=n.outHeight||Math.floor(w)!==w))for(var T=0;T<u;T+=c){var E=(x+T)/i;E<0||E>=n.outWidth||Math.floor(E)!==E||(S+=h.get(g,w,E,_))}}p.set(S*m,g,v,y,_)}return p.toTensor()},t.prototype.pool3d=function(e,t,n){X(e,`pool3d`);for(var r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.front,p=t.padInfo.top,m=t.padInfo.left,h=n===`max`?-1/0:1/0,g=this.readSync(e.dataId),_=J(t.outShape,e.dtype),v=_.values,y=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],b=t.outShape[2]*t.outShape[3]*t.outShape[4],x=t.outShape[3]*t.outShape[4],S=t.outShape[4],C=0;C<t.batchSize;++C)for(var w=C*y,T=C*e.strides[0],E=0;E<t.inChannels;++E)for(var D=0;D<t.outDepth;++D){for(var O=D*r-f,k=O;k<0;)k+=o;for(var A=Math.min(t.inDepth,l+O),j=w+D*b,M=0;M<t.outHeight;++M){for(var N=M*i-p,P=N;P<0;)P+=s;for(var F=Math.min(t.inHeight,u+N),ee=j+M*x,te=0;te<t.outWidth;++te){for(var ne=te*a-m,re=ne;re<0;)re+=c;for(var ie=Math.min(t.inWidth,d+ne),ae=ee+te*S,I=h,L=0,oe=0,se=k;se<A;se+=o){for(var R=T+se*e.strides[1],z=P;z<F;z+=s){for(var ce=R+z*e.strides[2],le=re;le<ie;le+=c){var ue=g[ce+le*e.strides[3]+E];if(n===`max`&&ue>I?I=ue:n===`avg`&&(L+=ue,oe++),isNaN(I))break}if(isNaN(I))break}if(isNaN(I))break}v[ae+E]=n===`avg`?L/oe:I}}}return _.toTensor()},t.prototype.avgPool3d=function(e,t){return X(e,`avgPool3d`),this.pool3d(e,t,`avg`).toFloat()},t.prototype.avgPool3dBackprop=function(e,t,n){X([e,t],`avgPool3dBackprop`);for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,c=n.filterWidth,l=n.dilationDepth,u=n.dilationHeight,d=n.dilationWidth,f=n.effectiveFilterDepth,p=n.effectiveFilterHeight,m=n.effectiveFilterWidth,h=f-1-n.padInfo.front,g=m-1-n.padInfo.left,_=p-1-n.padInfo.top,v=J(t.shape,`float32`),y=1/(o*s*c),b=this.bufferSync(e),x=0;x<n.batchSize;++x)for(var S=0;S<n.inChannels;++S)for(var C=0;C<n.inDepth;++C)for(var w=0;w<n.inHeight;++w)for(var T=0;T<n.inWidth;++T){for(var E=C-h,D=w-_,O=T-g,k=0,A=0;A<f;A+=l){var j=(E+A)/r;if(!(j<0||j>=n.outDepth||Math.floor(j)!==j))for(var M=0;M<p;M+=u){var N=(D+M)/i;if(!(N<0||N>=n.outHeight||Math.floor(N)!==N))for(var P=0;P<m;P+=d){var F=(O+P)/a;F<0||F>=n.outWidth||Math.floor(F)!==F||(k+=b.get(x,j,N,F,S))}}}v.set(k*y,x,C,w,T,S)}return v.toTensor()},t.prototype.maxPool3d=function(e,t){return X(e,`maxPool3d`),this.pool3d(e,t,`max`).toFloat()},t.prototype.maxPool3dPositions=function(e,t){for(var n=J(t.outShape,`int32`),r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=t.padInfo.front,p=t.padInfo.top,m=t.padInfo.left,h=this.bufferSync(e),g=0;g<t.batchSize;++g)for(var _=0;_<t.inChannels;++_)for(var v=0;v<t.outDepth;++v){for(var y=v*r-f,b=y;b<0;)b+=o;for(var x=Math.min(t.inDepth,l+y),S=0;S<t.outHeight;++S){for(var C=S*i-p,w=C;w<0;)w+=s;for(var T=Math.min(t.inHeight,u+C),E=0;E<t.outWidth;++E){for(var D=E*a-m,O=D;O<0;)O+=c;for(var k=Math.min(t.inWidth,d+D),A=-1/0,j=-1,M=b;M<x;M+=o)for(var N=M-y,P=w;P<T;P+=s)for(var F=P-C,ee=O;ee<k;ee+=c){var te=ee-D,ne=h.get(g,M,P,ee,_);ne>=A&&(A=ne,j=N*u*d+F*u+te)}n.set(j,g,v,S,E,_)}}}return n.toTensor()},t.prototype.maxPool3dBackprop=function(e,t,n,r){X([t,n],`maxPool3dBackprop`);for(var i=this.maxPool3dPositions(t,r),a=r.strideDepth,o=r.strideHeight,s=r.strideWidth,c=r.dilationDepth,l=r.dilationHeight,u=r.dilationWidth,d=r.effectiveFilterDepth,f=r.effectiveFilterHeight,p=r.effectiveFilterWidth,m=d-1-r.padInfo.front,h=p-1-r.padInfo.left,g=f-1-r.padInfo.top,_=J(t.shape,`float32`),v=this.bufferSync(i),y=this.bufferSync(e),b=0;b<r.batchSize;++b)for(var x=0;x<r.inChannels;++x)for(var S=0;S<r.inDepth;++S)for(var C=0;C<r.inHeight;++C)for(var w=0;w<r.inWidth;++w){for(var T=S-m,E=C-g,D=w-h,O=0,k=0;k<d;k+=c){var A=(T+k)/a;if(!(A<0||A>=r.outDepth||Math.floor(A)!==A))for(var j=0;j<f;j+=l){var M=(E+j)/o;if(!(M<0||M>=r.outHeight||Math.floor(M)!==M))for(var N=0;N<p;N+=u){var P=(D+N)/s;if(!(P<0||P>=r.outWidth||Math.floor(P)!==P)){var F=d*f*p-1-v.get(b,A,M,P,x)===k*f*p+j*p+N?1:0;F!==0&&(O+=y.get(b,A,M,P,x)*F)}}}}_.set(O,b,S,C,w,x)}return _.toTensor()},t.prototype.cast=function(e,t){return Ni(e,t,this)},t.prototype.reshape=function(e,t){return Pi(e,t)},t.prototype.avgPool=function(e,t){return X(e,`avgPool`),this.pool(e,t,`avg`).toFloat()},t.prototype.resizeBilinear=function(e,t,n,r){X(e,`resizeBilinear`);for(var i=e.shape,a=i[0],o=i[1],s=i[2],c=i[3],l=this.readSync(e.dataId),u=new Float32Array(R([a,t,n,c])),d=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0,m=d[0]/f[0],h=d[1]/f[1],g=0;g<a;g++)for(var _=0;_<t;_++)for(var v=m*_,y=Math.floor(v),b=v-y,x=Math.min(o-1,Math.ceil(v)),S=g*e.strides[0]+y*e.strides[1],C=g*e.strides[0]+x*e.strides[1],w=0;w<n;w++)for(var T=h*w,E=Math.floor(T),D=T-E,O=Math.min(s-1,Math.ceil(T)),k=S+E*e.strides[2],A=C+E*e.strides[2],j=S+O*e.strides[2],M=C+O*e.strides[2],N=0;N<c;N++){var P=l[k+N],F=l[A+N],ee=P+(l[j+N]-P)*D,te=ee+(F+(l[M+N]-F)*D-ee)*b;u[p++]=te}return Bn(u,[a,t,n,c])},t.prototype.resizeBilinearBackprop=function(e,t,n){X([e,t],`resizeBilinearBackprop`);for(var r=t.shape,i=r[0],a=r[1],o=r[2],s=r[3],c=e.shape,l=c[1],u=c[2],d=new Float32Array(i*a*o*s),f=[n&&l>1?a-1:a,n&&u>1?o-1:o],p=[n&&l>1?l-1:l,n&&u>1?u-1:u],m=f[0]/p[0],h=f[1]/p[1],g=this.readSync(e.dataId),_=0,v=0;v<i;v++)for(var y=v*t.strides[0],b=0;b<l;b++)for(var x=b*m,S=Math.floor(x),C=Math.min(Math.ceil(x),a-1),w=y+S*t.strides[1],T=y+C*t.strides[1],E=x-S,D=1-E,O=0;O<u;O++)for(var k=O*h,A=Math.floor(k),j=Math.min(Math.ceil(k),o-1),M=k-A,N=1-M,P=w+A*t.strides[2],F=w+j*t.strides[2],ee=T+A*t.strides[2],te=T+j*t.strides[2],ne=D*N,re=D*M,ie=E*N,ae=E*M,I=0;I<s;I++){var L=g[_++];d[P+I]+=L*ne,d[F+I]+=L*re,d[ee+I]+=L*ie,d[te+I]+=L*ae}return Gn(d,[i,o,a,s],t.dtype)},t.prototype.resizeNearestNeighbor=function(e,t,n,r){X(e,`resizeNearestNeighbor`);for(var i=e.shape,a=i[0],o=i[1],s=i[2],c=i[3],l=this.readSync(e.dataId),u=new Float32Array(a*t*n*c),d=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=d[0]/f[0],m=d[1]/f[1],h=0,g=0;g<a;g++)for(var _=g*e.strides[0],v=0;v<t;v++)for(var y=p*v,b=_+Math.min(o-1,r?Math.round(y):Math.floor(y))*e.strides[1],x=0;x<n;x++)for(var S=m*x,C=b+Math.min(s-1,r?Math.round(S):Math.floor(S))*e.strides[2],w=0;w<c;w++){var T=l[C+w];u[h++]=T}return Bn(u,[a,t,n,c],e.dtype)},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){X([e,t],`resizeNearestNeighborBackprop`);for(var r=t.shape,i=r[0],a=r[1],o=r[2],s=r[3],c=e.shape,l=c[1],u=c[2],d=new Float32Array(i*a*o*s),f=this.readSync(e.dataId),p=[n&&l>1?a-1:a,n&&u>1?o-1:o],m=[n&&l>1?l-1:l,n&&u>1?u-1:u],h=p[0]/m[0],g=p[1]/m[1],_=1/h,v=1/g,y=2*Math.ceil(_)+2,b=2*Math.ceil(v)+2,x=0;x<i;x++)for(var S=x*t.strides[0],C=0;C<a;C++)for(var w=S+C*t.strides[1],T=Math.floor(C*_),E=Math.floor(T-y/2),D=0;D<o;D++)for(var O=w+D*t.strides[2],k=Math.floor(D*v),A=Math.floor(k-b/2),j=0;j<s;j++){for(var M=0,N=0;N<y;N++){var P=N+E;if(!(P<0||P>=l)){var F=S+P*e.strides[1],ee=P*h;if(C===Math.min(a-1,n?Math.round(ee):Math.floor(ee)))for(var te=0;te<b;te++){var ne=te+A;if(!(ne<0||ne>=u)){var re=F+ne*e.strides[2],ie=ne*g;D===Math.min(o-1,n?Math.round(ie):Math.floor(ie))&&(M+=f[re+j])}}}}d[O+j]=M}return Gn(d,t.shape,t.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,a){X([e,t,n,i,a],`batchNorm`);for(var o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=this.readSync(n.dataId),l=i?this.readSync(i.dataId):new Float32Array([1]),u=a?this.readSync(a.dataId):new Float32Array([0]),d=new Float32Array(o.length),f=u.length,p=l.length,m=c.length,h=s.length,g=0,_=0,v=0,y=0,b=0;b<o.length;++b)d[b]=u[g++]+(o[b]-s[_++])*l[v++]/Math.sqrt(c[y++]+r),g>=f&&(g=0),_>=h&&(_=0),v>=p&&(v=0),y>=m&&(y=0);return Gn(d,e.shape)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){X(e,`localResponseNormalization4D`);var a=e.shape[3],o=a-1,s=this.readSync(e.dataId),c=e.size,l=new Float32Array(c);function u(e){for(var n=e%a,r=e-n+Math.max(0,n-t),i=e-n+Math.min(n+t,o),c=0;r<=i;r++){var l=s[r];c+=l*l}return c}for(var d=0;d<c;d++){var f=u(d);l[d]=s[d]*(n+r*f)**+-i}return Gn(l,e.shape)},t.prototype.LRNGrad=function(e,t,n,r,i,a,o){X(e,`LRNGrad`);for(var s=e.shape[3],c=this.readSync(e.dataId),l=this.readSync(t.dataId),u=this.readSync(n.dataId),d=new Float32Array(e.size),f=e.size,p=0;p<f;p++){for(var m=p%s,h=p-m+Math.max(0,m-r),g=p-m+Math.min(s,m+r+1),_=0,v=h;v<g;v++)_+=l[v]**2;for(_=a*_+i,v=h;v<g;v++){var y=-2*a*o*l[v]*u[p]/_;p===v&&(y+=_**+-o),y*=c[p],d[v]+=y}}return Gn(d,e.shape)},t.prototype.multinomial=function(e,t,n,r){X(e,`multinomial`);for(var i=t?e:mi(e),a=i.shape[0],o=i.shape[1],s=Xn([a,n],`int32`),c=this.readSync(s.dataId),l=this.readSync(i.dataId),u=0;u<a;++u){var d=u*o,f=new Float32Array(o-1);f[0]=l[d];for(var p=1;p<f.length;++p)f[p]=f[p-1]+l[d+p];for(var m=gr(r.toString()),h=u*n,g=0;g<n;++g){var _=m();c[h+g]=f.length;for(var v=0;v<f.length;v++)if(_<f[v]){c[h+g]=v;break}}}return s},t.prototype.oneHot=function(e,t,n,r){X(e,`oneHot`);var i=new Float32Array(e.size*t);i.fill(r);for(var a=this.readSync(e.dataId),o=0;o<e.size;++o)a[o]>=0&&a[o]<t&&(i[o*t+a[o]]=n);return Un(i,[e.size,t],`int32`)},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return X(e,`nonMaxSuppression`),Hi(this.readSync(e.dataId),this.readSync(t.dataId),n,r,i)},t.prototype.fft=function(e){return this.fftBatch(e,!1)},t.prototype.ifft=function(e){return this.fftBatch(e,!0)},t.prototype.fftBatch=function(e,t){for(var n=e.shape[0],r=e.shape[1],i=J(e.shape,`float32`),a=J(e.shape,`float32`),o=Rn(e).as2D(n,r),s=zn(e).as2D(n,r),c=0;c<n;c++)for(var l=o.slice([c,0],[1,r]),u=s.slice([c,0],[1,r]),d=Ln(l,u),f=this.readSync(this.fftImpl(d,t).dataId),p=0;p<r;p++){var m=Li(f,p);i.values[c*r+p]=m.real,a.values[c*r+p]=m.imag}return Ln(i.toTensor(),a.toTensor()).as2D(n,r)},t.prototype.fftImpl=function(e,t){var n=e.as1D(),r=n.size;if(this.isExponentOf2(r)){var i=this.fftRadix2(n,r,t).as2D(e.shape[0],e.shape[1]);return t&&(i=Ln(Rn(i).div(q(r)),zn(i).div(q(r)))),i}var a=this.readSync(e.dataId),o=function(e){for(var t=new Float32Array(e.length/2),n=new Float32Array(e.length/2),r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}(this.fourierTransformByMatmul(a,r,t));return Ln(o.real,o.imag).as2D(e.shape[0],e.shape[1])},t.prototype.isExponentOf2=function(e){return(e&e-1)==0},t.prototype.fftRadix2=function(e,t,n){if(t===1)return e;var r=this.readSync(e.dataId),i=t/2,a=function(e){for(var t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=0;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),o=Ln(a.real,a.imag).as1D(),s=function(e){for(var t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=2;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),c=Ln(s.real,s.imag).as1D();o=this.fftRadix2(o,i,n),c=this.fftRadix2(c,i,n);var l=function(e,t){for(var n=new Float32Array(e/2),r=new Float32Array(e/2),i=0;i<Math.ceil(e/2);i++){var a=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(a),r[i]=Math.sin(a)}return{real:n,imag:r}}(t,n),u=Ln(l.real,l.imag).mul(c),d=o.add(u),f=o.sub(u);return Ln(Rn(d).concat(Rn(f)),zn(d).concat(zn(f))).as1D()},t.prototype.fourierTransformByMatmul=function(e,t,n){for(var r=new Float32Array(2*t),i=0;i<t;i++){for(var a=0,o=0,s=0;s<t;s++){var c=zi(i*s,t,n),l=Li(e,s);a+=l.real*c.real-l.imag*c.imag,o+=l.real*c.imag+l.imag*c.real}n&&(a/=t,o/=t),Ri(r,a,o,i)}return r},t.prototype.depthToSpace=function(e,t,n){I(n===`NHWC`,(function(){return`Only NHWC dataFormat supported on CPU for depthToSpace. Got `+n})),I(t>1,(function(){return`blockSize should be > 1 for depthToSpace, but was: `+t}));for(var r=e.shape[0],i=e.shape[1],a=e.shape[2],o=e.shape[3],s=i*t,c=a*t,l=o/(t*t),u=this.readSync(e.dataId),d=new Float32Array(r*s*c*l),f=0,p=0;p<r;++p)for(var m=0;m<s;++m)for(var h=Math.floor(m/t),g=m%t,_=0;_<c;++_)for(var v=Math.floor(_/t),y=(g*t+_%t)*l,b=0;b<l;++b){var x=b+y+o*(v+a*(h+i*p));d[f++]=u[x]}return Gn(d,[r,s,c,l])},t.prototype.broadcastedBinaryOp=function(e,t,n,r){var i=bi(e.shape,t.shape),a=J(i,n),o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=vi(e.shape,i),l=vi(t.shape,i),u=a.values;if(c.length+l.length===0)for(var d=0;d<u.length;++d)u[d]=r(o[d%o.length],s[d%s.length]);else{var f=this.bufferSync(e),p=this.bufferSync(t),m=function(n){var i=a.indexToLoc(n),d=i.slice(-e.rank);c.forEach((function(e){return d[e]=0}));var m=f.locToIndex(d),h=i.slice(-t.rank);l.forEach((function(e){return h[e]=0}));var g=p.locToIndex(h);u[n]=r(o[m],s[g])};for(d=0;d<u.length;++d)m(d)}return a.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(e,t,n){var r=bi(e.shape,t.shape),i=J(r,`float32`),a=J(r,`float32`),o=this.readSync(e.dataId),s=this.readSync(t.dataId),c=vi(e.shape,r),l=vi(t.shape,r),u=i.values,d=a.values;if(c.length+l.length===0)for(var f=0;f<u.length;f++){var p=f%o.length,m=f%s.length,h=n(o[2*p],o[2*p+1],s[2*m],s[2*m+1]);u[f]=h.real,d[f]=h.imag}else{var g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),_=this.bufferSync(this.data.get(t.dataId).complexTensors.real),v=function(r){var a=i.indexToLoc(r),f=a.slice(-e.rank);c.forEach((function(e){return f[e]=0}));var p=g.locToIndex(f),m=a.slice(-t.rank);l.forEach((function(e){return m[e]=0}));var h=_.locToIndex(m),v=n(o[2*p],o[2*p+1],s[2*h],s[2*h+1]);u[r]=v.real,d[r]=v.imag};for(f=0;f<u.length;f++)v(f)}return this.complex(i.toTensor(),a.toTensor())},t.prototype.split=function(e,t,n){return Ji(e,t,n)},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32},t.prototype.epsilon=function(){return 1e-7},t.prototype.cropAndResize=function(e,t,n,r,i,a){for(var o=e.shape,s=o[0],c=o[1],l=o[2],u=o[3],d=t.shape[0],f=r[0],p=r[1],m=J([d,f,p,u],`float32`),h=this.readSync(t.dataId),g=this.readSync(n.dataId),_=this.readSync(e.dataId),v=e.strides,y=m.strides,b=0;b<d;b++){var x=4*b,S=h[x],C=h[x+1],w=h[x+2],T=h[x+3],E=g[b];if(!(E>=s))for(var D=f>1?(w-S)*(c-1)/(f-1):0,O=p>1?(T-C)*(l-1)/(p-1):0,k=0;k<f;k++){var A=f>1?S*(c-1)+k*D:.5*(S+w)*(c-1);if(A<0||A>c-1)for(var j=0;j<p;j++)for(var M=0;M<u;M++){var N=M+j*y[2]+k*y[1]+b*y[0];m.values[N]=a}else if(i===`bilinear`){var P=Math.floor(A),F=Math.ceil(A),ee=A-P;for(j=0;j<p;j++)if((se=p>1?C*(l-1)+j*O:.5*(C+T)*(l-1))<0||se>l-1)for(M=0;M<u;M++)N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=a;else{var te=Math.floor(se),ne=Math.ceil(se),re=se-te;for(M=0;M<u;M++){var ie=_[N=M+te*v[2]+P*v[1]+E*v[0]],ae=_[N=M+ne*v[2]+P*v[1]+E*v[0]],I=_[N=M+te*v[2]+F*v[1]+E*v[0]],L=ie+(ae-ie)*re,oe=I+(_[N=M+ne*v[2]+F*v[1]+E*v[0]]-I)*re;N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=L+(oe-L)*ee}}}else for(j=0;j<p;++j){var se;if((se=p>1?C*(l-1)+j*O:.5*(C+T)*(l-1))<0||se>l-1)for(M=0;M<u;M++)N=M+j*y[2]+k*y[1]+b*y[0],m.values[N]=a;else{var R=Math.round(se),z=Math.round(A);for(M=0;M<u;M++){var ce=M+R*v[2]+z*v[1]+E*v[0],le=M+j*y[2]+k*y[1]+b*y[0];m.values[le]=_[ce]}}}}}return m.toTensor()},t.prototype.sparseToDense=function(e,t,n,r){var i=ii(0,e,n),a=i.sliceRank,o=i.numUpdates,s=i.sliceSize,c=i.strides,l=i.outputSize;return this.scatter(e,t,n,l,s,o,a,c,r,!1)},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=$r(e,t),a=i[0],o=i[1],s=i[2],c=i[3];if(o===0)return Bn([],a,e.dtype);for(var l=new Xe([o,s],e.dtype),u=this.readSync(t.dataId),d=this.readSync(e.dataId),f=0;f<o;f++){for(var p=[],m=0,h=0;h<r;h++){var g=u[f*r+h];m+=g*c[h],p.push(g)}if(m<0||m>=e.size/s)throw Error(`Invalid indices: `+p+` does not index into `+e.shape);for(var _=0;_<s;_++)l.values[f*s+_]=d[m*s+_]}return l.toTensor().reshape(a)},t.prototype.scatterND=function(e,t,n){var r=ii(0,e,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,c=r.outputSize,l=q(0);return this.scatter(e,t,n,c,o,a,i,s,l,!0)},t.prototype.fill=function(e,t,n){var r=_e(n||=De(t),R(e));return r.fill(t),V.makeTensor(r,e,n,this)},t.prototype.onesLike=function(e){if(e.dtype===`string`)throw Error(`onesLike is not supported for string tensors`);return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){var t=_e(e.dtype,R(e.shape));return this.makeOutput(t,e.shape,e.dtype)},t.prototype.linspace=function(e,t,n){return Fi(e,t,n)},t.prototype.scatter=function(e,t,n,r,i,a,o,s,c,l){var u=[r/i,i],d=this.readSync(e.dataId),f=this.readSync(t.dataId);if(r===0)return Bn([],n,t.dtype);var p=new Xe(u,t.dtype);p.values.fill(this.readSync(c.dataId)[0]);for(var m=0;m<a;m++){for(var h=[],g=0,_=0;_<o;_++){var v=d[m*o+_];h.push(v),g+=v*s[_]}if(g<0||g>=r/i)throw Error(`Invalid indices: `+h+` does not index into `+n);for(var y=0;y<i;y++)l?p.values[g*i+y]+=f[m*i+y]:p.values[g*i+y]=t.rank===0?f[0]:f[m*i+y]}return p.toTensor().reshape(n)},t}(_i);V.registerBackend(`cpu`,(function(){return new Vd}),1);for(var Hd=0,Ud=[{kernelName:`NonMaxSuppressionV5`,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t,a=i.boxes,o=i.scores,s=r,c=s.maxOutputSize,l=s.iouThreshold,u=s.scoreThreshold,d=s.softNmsSigma,f=n;X(a,`NonMaxSuppressionWithScore`);var p=Ui(f.data.get(a.dataId).values,f.data.get(o.dataId).values,c,l,u,d);return[p.selectedIndices,p.selectedScores]}},{kernelName:`Square`,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n;X(r,`square`);for(var a=i.data.get(r.dataId).values,o=new Float32Array(a.length),s=0;s<a.length;++s){var c=a[s];o[s]=c*c}return{dataId:i.write(o,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:Zs,backendName:`cpu`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,a=r.b,o=n;X([i,a],Zs);var s=o.data.get(i.dataId).values,c=o.data.get(a.dataId).values,l=function(e,t,n,r,i,a){var o=bi(e,t),s=o.length,c=Ae(o),l=ge(i,R(o)),u=e.length,d=t.length,f=Ae(e),p=Ae(t),m=vi(e,o),h=vi(t,o);if(m.length+h.length===0)for(var g=0;g<l.length;++g)l[g]=a(n[g%n.length],r[g%r.length]);else{var _=function(e){var t=Be(e,s,c),i=t.slice(-u);m.forEach((function(e){return i[e]=0}));var o=ze(i,u,f),g=t.slice(-d);h.forEach((function(e){return g[e]=0}));var _=ze(g,d,p);l[e]=a(n[o],r[_])};for(g=0;g<l.length;++g)_(g)}return[l,o]}(i.shape,a.shape,s,c,i.dtype,(function(e,t){var n=e-t;return n*n})),u=l[0],d=l[1];return{dataId:o.write(u,d,i.dtype),shape:d,dtype:i.dtype}}}];Hd<Ud.length;Hd++)F(Ud[Hd]);for(var Wd,Gd=function(e){this.variableNames=[`A`];var t=ra(),n=e[0],r=e[1];this.outputShape=e,this.userCode=`
|
|
3744
3744
|
void main() {
|
|
3745
3745
|
ivec3 coords = getOutputCoords();
|
|
3746
3746
|
int texR = coords[0];
|
|
@@ -3762,7 +3762,7 @@ Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed thi
|
|
|
3762
3762
|
|
|
3763
3763
|
setOutput(floor(value * 255.0 + 0.5));
|
|
3764
3764
|
}
|
|
3765
|
-
`},
|
|
3765
|
+
`},Kd=function(e){this.variableNames=[`A`],this.packedInputs=!1,this.packedOutput=!0;var t=ra(),n=e[0],r=e[1];this.outputShape=e,this.userCode=`
|
|
3766
3766
|
void main() {
|
|
3767
3767
|
ivec3 coords = getOutputCoords();
|
|
3768
3768
|
int texR = coords[0];
|
|
@@ -3796,9 +3796,57 @@ Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed thi
|
|
|
3796
3796
|
|
|
3797
3797
|
`+t.output+` = result;
|
|
3798
3798
|
}
|
|
3799
|
-
`},Nd=0,Pd=[{kernelName:`FromPixels`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t.pixels,a=r.numChannels,o=typeof HTMLVideoElement<`u`&&i instanceof HTMLVideoElement,s=typeof HTMLImageElement<`u`&&i instanceof HTMLImageElement,c=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],l=c[0],u=c[1],d=[u,l],f=[u,l,a];(s||o)&&(Ad??=document.createElement(`canvas`).getContext(`2d`),Ad.canvas.width=l,Ad.canvas.height=u,Ad.drawImage(i,0,0,l,u),i=Ad.canvas);var p=n.makeTensorInfo(d,`int32`);n.texData.get(p.dataId).usage=ot.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),i);var h=m().getBool(`WEBGL_PACK`)?new Md(f):new jd(f),g=n.runWebGLProgram(h,[p],`int32`);return n.disposeData(p.dataId),g}},{kernelName:`NonMaxSuppressionV5`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs;dn(`tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead`);var i=t,a=i.boxes,o=i.scores,s=r,c=s.maxOutputSize,l=s.iouThreshold,u=s.scoreThreshold,d=s.softNmsSigma,f=n,p=Ai(f.readSync(a.dataId),f.readSync(o.dataId),c,l,u,d);return[p.selectedIndices,p.selectedScores]}},{kernelName:`Square`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n,a=new Y(r.shape,`return x * x;`);return i.runWebGLProgram(a,[r],r.dtype)}},{kernelName:Ls,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,a=r.b,o=n,s=m().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new ba(`return (a - b) * (a - b);`,i.shape,a.shape):new va(`return (a - b) * (a - b);`,i.shape,a.shape);return o.compileAndRun(s,[i,a])}}];Nd<Pd.length;Nd++)x(Pd[Nd]);for(var Fd=0,Id=[{kernelName:`Square`,gradFunc:function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().mul(2))}}}},{kernelName:Ls,gradFunc:function(e,t){var n=t[0],r=t[1],i=G(2);return{a:function(){return $c(e,$c(i,il(n,r)))},b:function(){return $c(e,$c(i,il(r,n)))}}}}];Fd<Id.length;Fd++)S(Id[Fd]);var Ld=function(){function e(){}return e.prototype.fetch=function(e,t){return fetch(e,t)},e.prototype.now=function(){return performance.now()},e.prototype.encode=function(e,t){if(t!==`utf-8`&&t!==`utf8`)throw Error(`Browser's encoder only supports utf-8, but got `+t);return this.textEncoder??=new TextEncoder,this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return new TextDecoder(t).decode(e)},e}();m().get(`IS_BROWSER`)&&m().setPlatform(`browser`,new Ld);var Rd,zd=function(){return s()},Bd=function(){function e(){this.util=s(),this.textEncoder=new this.util.TextEncoder}return e.prototype.fetch=function(e,t){return m().global.fetch==null?(Rd??=zd(),Rd(e,t)):m().global.fetch(e,t)},e.prototype.now=function(){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6},e.prototype.encode=function(e,t){if(t!==`utf-8`&&t!==`utf8`)throw Error(`Node built-in encoder only supports utf-8, but got `+t);return this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return e.length===0?``:new this.util.TextDecoder(t).decode(e)},e}();m().get(`IS_NODE`)&&m().setPlatform(`node`,new Bd);var Vd={float32:4,int32:4,uint16:2,uint8:1,bool:1},Hd=4;function Ud(e,t){for(var n={},r=0,i=function(t){var i=t.name,a=t.dtype,o=t.shape,s=M(o),c=void 0;if(`quantization`in t){var l=t.quantization;if(l.dtype!==`uint8`&&l.dtype!==`uint16`)throw Error(`Weight `+t.name+` has unknown quantization dtype `+l.dtype+`. Supported quantization dtypes are: 'uint8' and 'uint16'.`);var u=Vd[l.dtype],d=e.slice(r,r+s*u),f=l.dtype===`uint8`?new Uint8Array(d):new Uint16Array(d);if(a===`float32`)c=Float32Array.from(f,(function(e){return e*l.scale+l.min}));else{if(a!==`int32`)throw Error(`Unsupported dtype in weight '`+i+`': `+a);c=Int32Array.from(f,(function(e){return Math.round(e*l.scale+l.min)}))}r+=s*u}else if(a===`string`){var p=M(t.shape);c=[];for(var m=0;m<p;m++){var h=new Uint32Array(e.slice(r,r+Hd))[0];r+=Hd;var g=new Uint8Array(e.slice(r,r+h));c.push(g),r+=h}}else{var _=Vd[a];if(d=e.slice(r,r+s*_),a===`float32`)c=new Float32Array(d);else if(a===`int32`)c=new Int32Array(d);else{if(a!==`bool`)throw Error(`Unsupported dtype in weight '`+i+`': `+a);c=new Uint8Array(d)}r+=s*_}n[i]=On(c,o,a)},a=0,o=t;a<o.length;a++)i(o[a]);return n}function Wd(e){if(e===null)throw Error(`Invalid input value: `+JSON.stringify(e));var t=0,n=[];e.forEach((function(e){if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw Error(`Unsupported TypedArray subtype: `+e.constructor.name)}));var r=new Uint8Array(t),i=0;return n.forEach((function(e){r.set(new Uint8Array(e.buffer),i),i+=e.byteLength})),r.buffer}var Gd=typeof Buffer<`u`&&(typeof Blob>`u`||typeof atob>`u`||typeof btoa>`u`);function Kd(e){return Gd?Buffer.byteLength(e):new Blob([e]).size}function qd(e){var t=0;e.forEach((function(e){t+=e.byteLength}));var n=new Uint8Array(t),r=0;return e.forEach((function(e){n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function Jd(e){for(e=e.trim();e.endsWith(`/`);)e=e.slice(0,e.length-1);var t=e.split(`/`);return t[t.length-1]}function Yd(e){if(e.modelTopology instanceof ArrayBuffer)throw Error(`Expected JSON model topology, received ArrayBuffer.`);return{dateSaved:new Date,modelTopologyType:`JSON`,modelTopologyBytes:e.modelTopology==null?0:Kd(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Kd(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}var Xd=function(){function e(){this.saveRouters=[],this.loadRouters=[]}return e.getInstance=function(){return e.instance??=new e,e.instance},e.registerSaveRouter=function(t){e.getInstance().saveRouters.push(t)},e.registerLoadRouter=function(t){e.getInstance().loadRouters.push(t)},e.getSaveHandlers=function(t){return e.getHandlers(t,`save`)},e.getLoadHandlers=function(t,n){return e.getHandlers(t,`load`,n)},e.getHandlers=function(t,n,r){var i=[];return(n===`load`?e.getInstance().loadRouters:e.getInstance().saveRouters).forEach((function(e){var n=e(t,r);n!==null&&i.push(n)})),i},e}(),Zd=`://`,Qd=function(){function e(){this.managers={}}return e.getInstance=function(){return e.instance??=new e,e.instance},e.registerManager=function(t,n){O(t!=null,(function(){return`scheme must not be undefined or null.`})),t.endsWith(Zd)&&(t=t.slice(0,t.indexOf(Zd))),O(t.length>0,(function(){return`scheme must not be an empty string.`}));var r=e.getInstance();O(r.managers[t]==null,(function(){return`A model store manager is already registered for scheme '`+t+`'.`})),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(t==null)throw Error(`Cannot find model manager for scheme '`+e+`'`);return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function $d(e){if(e.indexOf(Zd)===-1)throw Error(`The url string provided does not contain a scheme. Supported schemes are: `+Qd.getSchemes().join(`,`));return{scheme:e.split(Zd)[0],path:e.split(Zd)[1]}}function ef(e,t,n){return n===void 0&&(n=!1),u(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,f;return d(this,(function(d){switch(d.label){case 0:return O(e!==t,(function(){return`Old path and new path are the same: '`+e+`'`})),O((r=Xd.getLoadHandlers(e)).length>0,(function(){return`Copying failed because no load handler is found for source URL `+e+`.`})),O(r.length<2,(function(){return`Copying failed because more than one (`+r.length+`) load handlers for source URL `+e+`.`})),i=r[0],O((a=Xd.getSaveHandlers(t)).length>0,(function(){return`Copying failed because no save handler is found for destination URL `+t+`.`})),O(a.length<2,(function(){return`Copying failed because more than one (`+r.length+`) save handlers for destination URL `+t+`.`})),o=a[0],s=$d(e).scheme,c=$d(e).path,l=s===$d(e).scheme,[4,i.load()];case 1:return u=d.sent(),n&&l?[4,Qd.getManager(s).removeModel(c)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,o.save(u)];case 4:return f=d.sent(),!n||l?[3,6]:[4,Qd.getManager(s).removeModel(c)];case 5:d.sent(),d.label=6;case 6:return[2,f.modelArtifactsInfo]}}))}))}var tf=`models_store`,nf=`model_info_store`;function rf(){if(!m().getBool(`IS_BROWSER`))throw Error(`Failed to obtain IndexedDB factory because the current environmentis not a web browser.`);var e=window||self,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw Error(`The current browser does not appear to support IndexedDB.`);return t}function af(e){var t=e.result;t.createObjectStore(tf,{keyPath:`modelPath`}),t.createObjectStore(nf,{keyPath:`modelPath`})}var of=function(){function e(e){if(this.indexedDB=rf(),e==null||!e)throw Error(`For IndexedDB, modelPath must not be null, undefined or empty.`);this.modelPath=e}return e.prototype.save=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserLocalStorage.save() does not support saving model topology in binary formats yet.`);return[2,this.databaseAction(this.modelPath,e)]}))}))},e.prototype.load=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){return[2,this.databaseAction(this.modelPath)]}))}))},e.prototype.databaseAction=function(e,t){var n=this;return new Promise((function(e,r){var i=n.indexedDB.open(`tensorflowjs`,1);i.onupgradeneeded=function(){return af(i)},i.onsuccess=function(){var a=i.result;if(t==null){var o=a.transaction(tf,`readonly`),s=o.objectStore(tf).get(n.modelPath);s.onsuccess=function(){if(s.result==null)return a.close(),r(Error(`Cannot find model with path '`+n.modelPath+`' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=function(e){return a.close(),r(s.error)},o.oncomplete=function(){return a.close()}}else{var c,l=Yd(t),u=a.transaction(nf,`readwrite`),d=u.objectStore(nf),f=d.put({modelPath:n.modelPath,modelArtifactsInfo:l});f.onsuccess=function(){var i=(c=a.transaction(tf,`readwrite`)).objectStore(tf).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});i.onsuccess=function(){return e({modelArtifactsInfo:l})},i.onerror=function(e){var t=(d=u.objectStore(nf)).delete(n.modelPath);t.onsuccess=function(){return a.close(),r(i.error)},t.onerror=function(e){return a.close(),r(i.error)}}},f.onerror=function(e){return a.close(),r(f.error)},u.oncomplete=function(){c==null?a.close():c.oncomplete=function(){return a.close()}}}},i.onerror=function(e){return r(i.error)}}))},e.URL_SCHEME=`indexeddb://`,e}(),sf=function(e){return m().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(of.URL_SCHEME)?(t=e.slice(of.URL_SCHEME.length),new of(t)):null;var t};Xd.registerSaveRouter(sf),Xd.registerLoadRouter(sf);var cf=function(){function e(){this.indexedDB=rf()}return e.prototype.listModels=function(){return u(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,n){var r=e.indexedDB.open(`tensorflowjs`,1);r.onupgradeneeded=function(){return af(r)},r.onsuccess=function(){var e=r.result,i=e.transaction(nf,`readonly`),a=i.objectStore(nf).getAll();a.onsuccess=function(){for(var e={},n=0,r=a.result;n<r.length;n++){var i=r[n];e[i.modelPath]=i.modelArtifactsInfo}t(e)},a.onerror=function(t){return e.close(),n(a.error)},i.oncomplete=function(){return e.close()}},r.onerror=function(e){return n(r.error)}}))]}))}))},e.prototype.removeModel=function(e){return u(this,void 0,void 0,(function(){var t=this;return d(this,(function(n){var r;return e=(r=e).startsWith(of.URL_SCHEME)?r.slice(of.URL_SCHEME.length):r,[2,new Promise((function(n,r){var i=t.indexedDB.open(`tensorflowjs`,1);i.onupgradeneeded=function(){return af(i)},i.onsuccess=function(){var t,a=i.result,o=a.transaction(nf,`readwrite`),s=o.objectStore(nf),c=s.get(e);c.onsuccess=function(){if(c.result==null)return a.close(),r(Error(`Cannot find model with path '`+e+`' in IndexedDB.`));var i=s.delete(e),o=function(){var i=(t=a.transaction(tf,`readwrite`)).objectStore(tf).delete(e);i.onsuccess=function(){return n(c.result.modelArtifactsInfo)},i.onerror=function(e){return r(c.error)}};i.onsuccess=o,i.onerror=function(e){return o(),a.close(),r(c.error)}},c.onerror=function(e){return a.close(),r(c.error)},o.oncomplete=function(){t==null?a.close():t.oncomplete=function(){return a.close()}}},i.onerror=function(e){return r(i.error)}}))]}))}))},e}();if(m().getBool(`IS_BROWSER`))try{Qd.registerManager(of.URL_SCHEME,new cf)}catch{}var lf=`/`,uf=`tensorflowjs_models`,df=`info`,ff=`model_topology`,pf=`weight_specs`,mf=`weight_data`,hf=`model_metadata`;function gf(e){return{info:[uf,e,df].join(lf),topology:[uf,e,ff].join(lf),weightSpecs:[uf,e,pf].join(lf),weightData:[uf,e,mf].join(lf),modelMetadata:[uf,e,hf].join(lf)}}function _f(e){var t=e.split(lf);if(t.length<3)throw Error(`Invalid key format: `+e);return t.slice(1,t.length-1).join(lf)}var vf=function(){function e(e){if(!m().getBool(`IS_BROWSER`)||typeof window>`u`||window.localStorage===void 0)throw Error(`The current environment does not support local storage.`);if(this.LS=window.localStorage,e==null||!e)throw Error(`For local storage, modelPath must not be null, undefined or empty.`);this.modelPath=e,this.keys=gf(this.modelPath)}return e.prototype.save=function(e){return u(this,void 0,void 0,(function(){var t,n,r;return d(this,(function(i){if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserLocalStorage.save() does not support saving model topology in binary formats yet.`);t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=Yd(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Gd)return Buffer.from(e).toString(`base64`);for(var t=new Uint8Array(e),n=``,r=0,i=t.length;r<i;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(e.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata})),[2,{modelArtifactsInfo:r}]}catch{throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),Error(`Failed to save model '`+this.modelPath+`' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=`+r.modelTopologyBytes+`, weightSpecsBytes=`+r.weightSpecsBytes+`, weightDataBytes=`+r.weightDataBytes+`.`)}return[2]}))}))},e.prototype.load=function(){return u(this,void 0,void 0,(function(){var e,t,n,r,i,a,o;return d(this,(function(s){if((e=JSON.parse(this.LS.getItem(this.keys.info)))==null)throw Error(`In local storage, there is no model with name '`+this.modelPath+`'`);if(e.modelTopologyType!==`JSON`)throw Error(`BrowserLocalStorage does not support loading non-JSON model topology yet.`);if(t={},(n=JSON.parse(this.LS.getItem(this.keys.topology)))==null)throw Error(`In local storage, the topology of model '`+this.modelPath+`' is missing.`);if(t.modelTopology=n,(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs)))==null)throw Error(`In local storage, the weight specs of model '`+this.modelPath+`' are missing.`);if(t.weightSpecs=r,(i=this.LS.getItem(this.keys.modelMetadata))!=null&&(a=JSON.parse(i),t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,t.userDefinedMetadata=a.userDefinedMetadata),(o=this.LS.getItem(this.keys.weightData))==null)throw Error(`In local storage, the binary weight values of model '`+this.modelPath+`' are missing.`);return t.weightData=function(e){if(Gd){var t=Buffer.from(e,`base64`);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}for(var n=atob(e),r=new Uint8Array(n.length),i=0;i<n.length;++i)r.set([n.charCodeAt(i)],i);return r.buffer}(o),[2,t]}))}))},e.URL_SCHEME=`localstorage://`,e}(),yf=function(e){return m().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(vf.URL_SCHEME)?(t=e.slice(vf.URL_SCHEME.length),new vf(t)):null;var t};Xd.registerSaveRouter(yf),Xd.registerLoadRouter(yf);var bf=function(){function e(){O(m().getBool(`IS_BROWSER`),(function(){return`Current environment is not a web browser`})),O(typeof window>`u`||window.localStorage!==void 0,(function(){return`Current browser does not appear to support localStorage`})),this.LS=window.localStorage}return e.prototype.listModels=function(){return u(this,void 0,void 0,(function(){var e,t,n,r,i,a;return d(this,(function(o){for(e={},t=uf+lf,n=lf+df,r=0;r<this.LS.length;++r)(i=this.LS.key(r)).startsWith(t)&&i.endsWith(n)&&(a=_f(i),e[a]=JSON.parse(this.LS.getItem(i)));return[2,e]}))}))},e.prototype.removeModel=function(e){return u(this,void 0,void 0,(function(){var t,n;return d(this,(function(r){var i;if(e=(i=e).startsWith(vf.URL_SCHEME)?i.slice(vf.URL_SCHEME.length):i,t=gf(e),this.LS.getItem(t.info)==null)throw Error(`Cannot find model at path '`+e+`'`);return n=JSON.parse(this.LS.getItem(t.info)),this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),[2,n]}))}))},e}();if(m().getBool(`IS_BROWSER`))try{Qd.registerManager(vf.URL_SCHEME,new bf)}catch{}var xf=`model`,Sf=`.json`,Cf=`.weights.bin`;function wf(e){return new Promise((function(e){return setTimeout(e)})).then(e)}var Tf=function(){function e(t){if(!m().getBool(`IS_BROWSER`))throw Error(`browserDownloads() cannot proceed because the current environment is not a browser.`);t.startsWith(e.URL_SCHEME)&&(t=t.slice(e.URL_SCHEME.length)),t!=null&&t.length!==0||(t=xf),this.modelTopologyFileName=t+Sf,this.weightDataFileName=t+Cf}return e.prototype.save=function(e){return u(this,void 0,void 0,(function(){var t,n,r,i,a,o;return d(this,(function(s){switch(s.label){case 0:if(typeof document>`u`)throw Error("Browser downloads are not supported in this environment since `document` is not present");if(t=window.URL.createObjectURL(new Blob([e.weightData],{type:`application/octet-stream`})),!(e.modelTopology instanceof ArrayBuffer))return[3,1];throw Error(`BrowserDownloads.save() does not support saving model topology in binary formats yet.`);case 1:return n=[{paths:[`./`+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:`application/json`})),(a=this.jsonAnchor==null?document.createElement(`a`):this.jsonAnchor).download=this.modelTopologyFileName,a.href=i,[4,wf((function(){return a.dispatchEvent(new MouseEvent(`click`))}))];case 2:return s.sent(),e.weightData==null?[3,4]:((o=this.weightDataAnchor==null?document.createElement(`a`):this.weightDataAnchor).download=this.weightDataFileName,o.href=t,[4,wf((function(){return o.dispatchEvent(new MouseEvent(`click`))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:Yd(e)}]}}))}))},e.URL_SCHEME=`downloads://`,e}(),Ef=function(){function e(e){if(e==null||e.length<1)throw Error(`When calling browserFiles, at least 1 file is required, but received `+e);this.files=e}return e.prototype.load=function(){return u(this,void 0,void 0,(function(){var e,t,n=this;return d(this,(function(r){return e=this.files[0],t=this.files.slice(1),[2,new Promise((function(r,i){var a=new FileReader;a.onload=function(a){var o=JSON.parse(a.target.result),s=o.modelTopology;if(s!=null){t.length===0&&r({modelTopology:s});var c=o.weightsManifest;if(c!=null){var l;try{l=n.checkManifestAndWeightFiles(c,t)}catch(e){i(e);return}var u=[],d=[],f=[];c.forEach((function(e){e.paths.forEach((function(e){d.push(e),f.push(null)})),u.push.apply(u,e.weights)})),c.forEach((function(e){e.paths.forEach((function(e){var t=new FileReader;t.onload=function(t){var n=t.target.result,i=d.indexOf(e);f[i]=n,f.indexOf(null)===-1&&r({modelTopology:s,weightSpecs:u,weightData:qd(f),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},t.onerror=function(t){return i(`Failed to weights data from file of path '`+e+`'.`)},t.readAsArrayBuffer(l[e])}))}))}else i(Error(`weightManifest field is missing from file `+e.name))}else i(Error(`modelTopology field is missing from file `+e.name))},a.onerror=function(t){return i(`Failed to read model topology and weights manifest JSON from file '`+e.name+`'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`)},a.readAsText(e)}))]}))}))},e.prototype.checkManifestAndWeightFiles=function(e,t){for(var n=[],r=t.map((function(e){return Jd(e.name)})),i={},a=0,o=e;a<o.length;a++)o[a].paths.forEach((function(e){var a=Jd(e);if(n.indexOf(a)!==-1)throw Error(`Duplicate file basename found in weights manifest: '`+a+`'`);if(n.push(a),r.indexOf(a)===-1)throw Error(`Weight file with basename '`+a+`' is not provided.`);i[e]=t[r.indexOf(a)]}));if(n.length!==t.length)throw Error(`Mismatch in the number of files in weights manifest (`+n.length+`) and the number of weight files provided (`+t.length+`).`);return i},e}();function Df(e,t,n,r){(function(e){O(e!=null&&Array.isArray(e)&&e.length>0,(function(){return`promises must be a none empty array`}))})(e),function(e,t){O(e>=0&&e<=1,(function(){return`Progress fraction must be in range [0, 1], but got startFraction `+e})),O(t>=0&&t<=1,(function(){return`Progress fraction must be in range [0, 1], but got endFraction `+t})),O(t>=e,(function(){return`startFraction must be no more than endFraction, but got startFraction `+e+` and endFraction `+t}))}(n??=0,r??=1);var i=0;return Promise.all(e.map((function(a){return a.then((function(a){return t(n+ ++i/e.length*(r-n)),a})),a})))}function Of(e,t){return u(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u;return d(this,(function(d){switch(d.label){case 0:return t??={},n=t.fetchFunc==null?m().platform.fetch:t.fetchFunc,r=e.map((function(e){return n(e,t.requestInit,{isBinary:!0})})),i=0,a=.5,t.onProgress==null?[4,Promise.all(r)]:[3,2];case 1:return o=d.sent(),[3,4];case 2:return[4,Df(r,t.onProgress,i,a)];case 3:o=d.sent(),d.label=4;case 4:return s=o.map((function(e){return e.arrayBuffer()})),c=.5,l=1,t.onProgress==null?[4,Promise.all(s)]:[3,6];case 5:return u=d.sent(),[3,8];case 6:return[4,Df(s,t.onProgress,c,l)];case 7:u=d.sent(),d.label=8;case 8:return[2,u]}}))}))}function kf(e){var t=this;return function(n,r,i){return r===void 0&&(r=``),u(t,void 0,void 0,(function(){var t,a,o,s,c,l,u,f,p,m;return d(this,(function(d){switch(d.label){case 0:if(t=n.map((function(){return!1})),a={},o=i==null?[]:i.map((function(){return!1})),s=[],n.forEach((function(e,n){var r=0;e.weights.forEach((function(e){var c=Vd[`quantization`in e?e.quantization.dtype:e.dtype]*M(e.shape),l=function(){t[n]=!0,a[n]??(a[n]=[]),a[n].push({manifestEntry:e,groupOffset:r,sizeBytes:c})};i==null?l():i.forEach((function(t,n){t===e.name&&(l(),o[n]=!0)})),s.push(e.name),r+=c}))})),!o.every((function(e){return e})))throw c=i.filter((function(e,t){return!o[t]})),Error(`Could not find weights in manifest with names: `+c.join(`, `)+`.
|
|
3800
|
-
Manifest JSON has weights with names: `+s.join(`, `)+`.`);return l=t.reduce((function(e,t,n){return t&&e.push(n),e}),[]),u=[],l.forEach((function(e){n[e].paths.forEach((function(e){var t=r+(r.endsWith(`/`)?``:`/`)+e;u.push(t)}))})),[4,e(u)];case 1:return f=d.sent(),p={},m=0,l.forEach((function(e){for(var t=n[e].paths.length,r=0,i=0;i<t;i++)r+=f[m+i].byteLength;for(var o=new ArrayBuffer(r),s=new Uint8Array(o),c=0,l=0;l<t;l++){var u=new Uint8Array(f[m+l]);s.set(u,c),c+=u.byteLength}a[e].forEach((function(e){var t=Ud(o.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(var n in t)p[n]=t[n]})),m+=t})),[2,p]}}))}))}}Xd.registerSaveRouter((function(e){return m().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(Tf.URL_SCHEME)?function(e){return e===void 0&&(e=`model`),new Tf(e)}(e.slice(Tf.URL_SCHEME.length)):null}));var Af=function(){function e(e,t){if(this.DEFAULT_METHOD=`POST`,t??={},this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc==null?this.fetch=m().platform.fetch:(O(typeof t.fetchFunc==`function`,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=t.fetchFunc),O(e!=null&&e.length>0,(function(){return`URL path for http must not be null, undefined or empty.`})),Array.isArray(e)&&O(e.length===2,(function(){return`URL paths for http must have a length of 2, (actual length is `+e.length+`).`})),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw Error(`requestInit is expected to have no pre-existing body, but has one.`);this.requestInit=t.requestInit||{}}return e.prototype.save=function(e){return u(this,void 0,void 0,(function(){var t,n,r,i;return d(this,(function(a){switch(a.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.`);return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:[`./model.weights.bin`],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n},t.body.append(`model.json`,new Blob([JSON.stringify(r)],{type:`application/json`}),`model.json`),e.weightData!=null&&t.body.append(`model.weights.bin`,new Blob([e.weightData],{type:`application/octet-stream`}),`model.weights.bin`),[4,this.fetch(this.path,t)];case 1:if((i=a.sent()).ok)return[2,{modelArtifactsInfo:Yd(e),responses:[i]}];throw Error(`BrowserHTTPRequest.save() failed due to HTTP response status `+i.status+`.`)}}))}))},e.prototype.load=function(){return u(this,void 0,void 0,(function(){var e,t,n,r,i,a,o,s,c,l,u,f;return d(this,(function(d){switch(d.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(e=d.sent()).ok)throw Error(`Request to `+this.path+` failed with status code `+e.status+`. Please verify this URL points to the model JSON of the model to load.`);d.label=2;case 2:return d.trys.push([2,4,,5]),[4,e.json()];case 3:return t=d.sent(),[3,5];case 4:throw d.sent(),n=`Failed to parse model JSON of response from `+this.path+`.`,this.path.endsWith(`.pb`)?n+=` Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.`:n+=` Please make sure the server is serving valid JSON for this request.`,Error(n);case 5:if(r=t.modelTopology,i=t.weightsManifest,a=t.generatedBy,o=t.convertedBy,s=t.format,c=t.userDefinedMetadata,r==null&&i==null)throw Error(`The JSON from HTTP path `+this.path+` contains neither model topology or manifest for weights.`);return i==null?[3,7]:[4,this.loadWeights(i)];case 6:f=d.sent(),l=f[0],u=f[1],d.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:u,userDefinedMetadata:c,generatedBy:a,convertedBy:o,format:s}]}}))}))},e.prototype.loadWeights=function(e){return u(this,void 0,void 0,(function(){var t,n,r,i,a,o,s,c,l,u,f;return d(this,(function(d){switch(d.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=function(e){var t=e.lastIndexOf(`/`),n=e.lastIndexOf(`?`),r=e.substring(0,t),i=n>t?e.substring(n):``;return[r+`/`,i]}(t),r=n[0],i=n[1],a=this.weightPathPrefix||r,o=[],s=0,c=e;s<c.length;s++)l=c[s],o.push.apply(o,l.weights);return u=[],e.forEach((function(e){e.paths.forEach((function(e){u.push(a+e+i)}))})),[4,Of(u,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=d.sent(),[2,[o,qd(f)]]}}))}))},e.URL_SCHEME_REGEX=/^https?:\/\//,e}();function jf(e){return e.match(Af.URL_SCHEME_REGEX)!=null}var Mf=function(e,t){return typeof fetch>`u`?null:(Array.isArray(e)?e.every((function(e){return jf(e)})):jf(e))?Nf(e,{onProgress:t}):null};function Nf(e,t){return new Af(e,t)}Xd.registerSaveRouter(Mf),Xd.registerLoadRouter(Mf);var Pf=function(){function e(e){this.modelArtifacts=e}return e.prototype.load=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){return[2,this.modelArtifacts]}))}))},e}(),Ff=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){return[2,this.saveHandler(e)]}))}))},e}(),If=Object.freeze({browserFiles:function(e){return new Ef(e)},browserHTTPRequest:function(e,t){return Nf(e,t)},concatenateArrayBuffers:qd,decodeWeights:Ud,encodeWeights:function(e,t){return u(this,void 0,void 0,(function(){var n,r,i,a,o,s=this;return d(this,(function(c){switch(c.label){case 0:for(n=[],r=[],i=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e),a=function(a){var o=i[a],c=Array.isArray(e)?e[a].tensor:e[o];if(c.dtype!==`float32`&&c.dtype!==`int32`&&c.dtype!==`bool`&&c.dtype!==`string`)throw Error(`Unsupported dtype in weight '`+o+`': `+c.dtype);var l={name:o,shape:c.shape,dtype:c.dtype};if(c.dtype===`string`){var f=new Promise((function(e){return u(s,void 0,void 0,(function(){var t,n,r,i,a,o,s;return d(this,(function(l){switch(l.label){case 0:return[4,c.bytes()];case 1:for(t=l.sent(),n=t.reduce((function(e,t){return e+t.length}),0)+Hd*t.length,r=new Uint8Array(n),i=0,a=0;a<t.length;a++)o=t[a],s=new Uint8Array(new Uint32Array([o.length]).buffer),r.set(s,i),i+=Hd,r.set(o,i),i+=o.length;return e(r),[2]}}))}))}));r.push(f)}else r.push(c.data());t!=null&&(l.group=t),n.push(l)},o=0;o<i.length;++o)a(o);return[4,Promise.all(r)];case 1:return[2,{data:Wd(c.sent()),specs:n}]}}))}))},fromMemory:function(e,t,n,r){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Pf(e):(console.warn(`Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release.`),new Pf({modelTopology:e})):(console.warn(`Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release.`),new Pf({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))},getLoadHandlers:function(e,t){return Xd.getLoadHandlers(e,t)},getModelArtifactsInfoForJSON:Yd,getSaveHandlers:function(e){return Xd.getSaveHandlers(e)},http:Nf,isHTTPScheme:jf,loadWeights:function(e,t,n,r){return t===void 0&&(t=``),u(this,void 0,void 0,(function(){return d(this,(function(i){return[2,kf((function(e){return Of(e,{requestInit:r})}))(e,t,n)]}))}))},registerLoadRouter:function(e){return Xd.registerLoadRouter(e)},registerSaveRouter:function(e){return Xd.registerSaveRouter(e)},weightsLoaderFactory:kf,withSaveHandler:function(e){return new Ff(e)},copyModel:function(e,t){return u(this,void 0,void 0,(function(){return d(this,(function(n){return[2,ef(e,t,!1)]}))}))},listModels:function(){return u(this,void 0,void 0,(function(){var e,t,n,r,i,a,o;return d(this,(function(s){switch(s.label){case 0:e=Qd.getSchemes(),t={},n=0,r=e,s.label=1;case 1:return n<r.length?(i=r[n],[4,Qd.getManager(i).listModels()]):[3,4];case 2:for(o in a=s.sent())t[i+Zd+o]=a[o];s.label=3;case 3:return n++,[3,1];case 4:return[2,t]}}))}))},moveModel:function(e,t){return u(this,void 0,void 0,(function(){return d(this,(function(n){return[2,ef(e,t,!0)]}))}))},removeModel:function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){return t=$d(e),[2,Qd.getManager(t.scheme).removeModel(t.path)]}))}))}}),Lf,Rf=W({confusionMatrix_:function(e,t,n){var r=U(e,`labels`,`confusionMatrix`),i=U(t,`predictions`,`confusionMatrix`);O(n==null||n>0&&Number.isInteger(n),(function(){return`If provided, numClasses must be a positive integer, but got `+n})),O(r.rank===1,(function(){return`Expected the rank of labels to be 1, but got `+r.rank})),O(i.rank===1,(function(){return`Expected the rank of predictions to be 1, but got `+i.rank})),O(r.shape[0]===i.shape[0],(function(){return`Mismatch in the number of examples: `+r.shape[0]+` vs. `+i.shape[0]+`. Labels and predictions should have the same number of elements.`})),O(n>0&&Number.isInteger(n),(function(){return`numClasses is required to be a positive integer, but got `+n}));var a=vr(r.asType(`int32`),n),o=vr(i.asType(`int32`),n);return a.transpose().matMul(o).asType(`int32`)}});Object.freeze({confusionMatrix:Rf});var zf=W({fromPixels_:function(e,t){if(t===void 0&&(t=3),t>4)throw Error(`Cannot construct Tensor with more than 4 channels from pixels.`);if(e==null)throw Error(`pixels passed to tf.browser.fromPixels() can not be null`);var n=!1,r=!1,i=!1,a=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData<`u`&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement<`u`&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement)a=!0;else{if(e.getContext==null)throw Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was `+e.constructor.name);o=!0}if(i&&i&&e.readyState<2)throw Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(v(`FromPixels`,z.backendName)!=null)return z.runKernel(`FromPixels`,{pixels:e},{numChannels:t});var s,c,l=i?[e.videoWidth,e.videoHeight]:[e.width,e.height],u=l[0],d=l[1];if(o?s=e.getContext(`2d`).getImageData(0,0,u,d).data:r||n?s=e.data:(a||i)&&(Lf??=document.createElement(`canvas`).getContext(`2d`),Lf.canvas.width=u,Lf.canvas.height=d,Lf.drawImage(e,0,0,u,d),s=Lf.getImageData(0,0,u,d).data),t===4)c=new Int32Array(s);else{var f=u*d;c=new Int32Array(f*t);for(var p=0;p<f;p++)for(var m=0;m<t;++m)c[p*t+m]=s[4*p+m]}return Mn(c,[d,u,t],`int32`)}}),Bf=Object.freeze({toPixels:function(e,t){return u(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u,f,p,m,h,g,_,v,y,b,x,S,C,w,T;return d(this,(function(d){switch(d.label){case 0:if(n=U(e,`img`,`toPixels`),e instanceof Ve||(n=n.toInt()),n.rank!==2&&n.rank!==3)throw Error(`toPixels only supports rank 2 or 3 tensors, got rank `+n.rank+`.`);if(r=n.shape.slice(0,2),i=r[0],a=r[1],(o=n.rank===2?1:n.shape[2])>4||o===2)throw Error(`toPixels only supports depth of size 1, 3 or 4 but got `+o);return[4,n.data()];case 1:return s=d.sent(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(u=d.sent(),f=u[0],p=u[1],m=f[0],h=p[0],c.dispose(),l.dispose(),n.dtype===`float32`){if(m<0||h>1)throw Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [`+m+` - `+h+`].`)}else{if(n.dtype!==`int32`)throw Error(`Unsupported type for toPixels: `+n.dtype+`. Please use float32 or int32 tensors.`);if(m<0||h>255)throw Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [`+m+` - `+h+`].`)}for(g=n.dtype===`float32`?255:1,_=new Uint8ClampedArray(a*i*4),v=0;v<i*a;++v)y=void 0,b=void 0,x=void 0,S=void 0,o===1?(y=s[v]*g,b=s[v]*g,x=s[v]*g,S=255):o===3?(y=s[3*v]*g,b=s[3*v+1]*g,x=s[3*v+2]*g,S=255):o===4&&(y=s[4*v]*g,b=s[4*v+1]*g,x=s[4*v+2]*g,S=s[4*v+3]*g),_[(C=4*v)+0]=Math.round(y),_[C+1]=Math.round(b),_[C+2]=Math.round(x),_[C+3]=Math.round(S);return t!=null&&(t.width=a,t.height=i,w=t.getContext(`2d`),T=new ImageData(_,a,i),w.putImageData(T,0,0)),n!==e&&n.dispose(),[2,_]}}))}))},fromPixels:zf}),Vf=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(e,t){return new e(t)},e}(),Hf=function(){function e(){this.classNameMap={}}return e.getMap=function(){return e.instance??=new e,e.instance},e.register=function(t){e.getMap().classNameMap[t.className]=[t,t.fromConfig]},e}();function Uf(e){O(e.className!=null,(function(){return`Class being registered does not have the static className property defined.`})),O(typeof e.className==`string`,(function(){return`className is required to be a string, but got type `+typeof e.className})),O(e.className.length>0,(function(){return`Class being registered has an empty-string as its className, which is disallowed.`})),Hf.register(e)}Object.freeze({Serializable:Vf,SerializationMap:Hf,registerClass:Uf});var Wf=.001,Gf=.1;function Kf(){return z.backend.floatPrecision()===32?Wf:Gf}function qf(e,t,n){var r=!0;if((le(e)||le(t))&&(r=!1),le(e)&&le(t)&&(r=!0),r){var i=e.constructor.name,a=t.constructor.name;if(i!==a)throw Error(`Arrays are of different type. Actual: `+i+`. Expected: `+a)}if(Array.isArray(e)&&Array.isArray(t)){var o=fn(e),s=fn(t);if(!N(o,s))throw Error(`Arrays have different shapes. Actual: [`+o+`]. Expected: [`+s+`]`)}var c=le(e)?e:j(e),l=le(t)?t:j(t);if(c.length!==l.length)throw Error(`Arrays have different lengths actual: `+c.length+` vs expected: `+l.length+`.
|
|
3799
|
+
`},qd=0,Jd=[{kernelName:`FromPixels`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t.pixels,a=r.numChannels,o=typeof HTMLVideoElement<`u`&&i instanceof HTMLVideoElement,s=typeof HTMLImageElement<`u`&&i instanceof HTMLImageElement,c=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],l=c[0],u=c[1],d=[u,l],f=[u,l,a];(s||o)&&(Wd??=document.createElement(`canvas`).getContext(`2d`),Wd.canvas.width=l,Wd.canvas.height=u,Wd.drawImage(i,0,0,l,u),i=Wd.canvas);var p=n.makeTensorInfo(d,`int32`);n.texData.get(p.dataId).usage=vt.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),i);var m=O().getBool(`WEBGL_PACK`)?new Kd(f):new Gd(f),h=n.runWebGLProgram(m,[p],`int32`);return n.disposeData(p.dataId),h}},{kernelName:`NonMaxSuppressionV5`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs;Cn(`tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead`);var i=t,a=i.boxes,o=i.scores,s=r,c=s.maxOutputSize,l=s.iouThreshold,u=s.scoreThreshold,d=s.softNmsSigma,f=n,p=Ui(f.readSync(a.dataId),f.readSync(o.dataId),c,l,u,d);return[p.selectedIndices,p.selectedScores]}},{kernelName:`Square`,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n,a=new vs(r.shape,`return x * x;`);return i.runWebGLProgram(a,[r],r.dtype)}},{kernelName:Zs,backendName:`webgl`,kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,a=r.b,o=n,s=O().getBool(`WEBGL_PACK_BINARY_OPERATIONS`)?new Na(`return (a - b) * (a - b);`,i.shape,a.shape):new ja(`return (a - b) * (a - b);`,i.shape,a.shape);return o.compileAndRun(s,[i,a])}}];qd<Jd.length;qd++)F(Jd[qd]);for(var Yd=0,Xd=[{kernelName:`Square`,gradFunc:function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().mul(2))}}}},{kernelName:Zs,gradFunc:function(e,t){var n=t[0],r=t[1],i=q(2);return{a:function(){return pl(e,pl(i,vl(n,r)))},b:function(){return pl(e,pl(i,vl(r,n)))}}}}];Yd<Xd.length;Yd++)ee(Xd[Yd]);var Zd=function(){function e(){}return e.prototype.fetch=function(e,t){return fetch(e,t)},e.prototype.now=function(){return performance.now()},e.prototype.encode=function(e,t){if(t!==`utf-8`&&t!==`utf8`)throw Error(`Browser's encoder only supports utf-8, but got `+t);return this.textEncoder??=new TextEncoder,this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return new TextDecoder(t).decode(e)},e}();O().get(`IS_BROWSER`)&&O().setPlatform(`browser`,new Zd);var Qd,$d=function(){return x()},ef=function(){function e(){this.util=x(),this.textEncoder=new this.util.TextEncoder}return e.prototype.fetch=function(e,t){return O().global.fetch==null?(Qd??=$d(),Qd(e,t)):O().global.fetch(e,t)},e.prototype.now=function(){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6},e.prototype.encode=function(e,t){if(t!==`utf-8`&&t!==`utf8`)throw Error(`Node built-in encoder only supports utf-8, but got `+t);return this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return e.length===0?``:new this.util.TextDecoder(t).decode(e)},e}();O().get(`IS_NODE`)&&O().setPlatform(`node`,new ef);var tf={float32:4,int32:4,uint16:2,uint8:1,bool:1},nf=4;function rf(e,t){for(var n={},r=0,i=function(t){var i=t.name,a=t.dtype,o=t.shape,s=R(o),c=void 0;if(`quantization`in t){var l=t.quantization;if(l.dtype!==`uint8`&&l.dtype!==`uint16`)throw Error(`Weight `+t.name+` has unknown quantization dtype `+l.dtype+`. Supported quantization dtypes are: 'uint8' and 'uint16'.`);var u=tf[l.dtype],d=e.slice(r,r+s*u),f=l.dtype===`uint8`?new Uint8Array(d):new Uint16Array(d);if(a===`float32`)c=Float32Array.from(f,(function(e){return e*l.scale+l.min}));else{if(a!==`int32`)throw Error(`Unsupported dtype in weight '`+i+`': `+a);c=Int32Array.from(f,(function(e){return Math.round(e*l.scale+l.min)}))}r+=s*u}else if(a===`string`){var p=R(t.shape);c=[];for(var m=0;m<p;m++){var h=new Uint32Array(e.slice(r,r+nf))[0];r+=nf;var g=new Uint8Array(e.slice(r,r+h));c.push(g),r+=h}}else{var _=tf[a];if(d=e.slice(r,r+s*_),a===`float32`)c=new Float32Array(d);else if(a===`int32`)c=new Int32Array(d);else{if(a!==`bool`)throw Error(`Unsupported dtype in weight '`+i+`': `+a);c=new Uint8Array(d)}r+=s*_}n[i]=Bn(c,o,a)},a=0,o=t;a<o.length;a++)i(o[a]);return n}function af(e){if(e===null)throw Error(`Invalid input value: `+JSON.stringify(e));var t=0,n=[];e.forEach((function(e){if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw Error(`Unsupported TypedArray subtype: `+e.constructor.name)}));var r=new Uint8Array(t),i=0;return n.forEach((function(e){r.set(new Uint8Array(e.buffer),i),i+=e.byteLength})),r.buffer}var of=typeof Buffer<`u`&&(typeof Blob>`u`||typeof atob>`u`||typeof btoa>`u`);function sf(e){return of?Buffer.byteLength(e):new Blob([e]).size}function cf(e){var t=0;e.forEach((function(e){t+=e.byteLength}));var n=new Uint8Array(t),r=0;return e.forEach((function(e){n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function lf(e){for(e=e.trim();e.endsWith(`/`);)e=e.slice(0,e.length-1);var t=e.split(`/`);return t[t.length-1]}function uf(e){if(e.modelTopology instanceof ArrayBuffer)throw Error(`Expected JSON model topology, received ArrayBuffer.`);return{dateSaved:new Date,modelTopologyType:`JSON`,modelTopologyBytes:e.modelTopology==null?0:sf(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:sf(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}var df=function(){function e(){this.saveRouters=[],this.loadRouters=[]}return e.getInstance=function(){return e.instance??=new e,e.instance},e.registerSaveRouter=function(t){e.getInstance().saveRouters.push(t)},e.registerLoadRouter=function(t){e.getInstance().loadRouters.push(t)},e.getSaveHandlers=function(t){return e.getHandlers(t,`save`)},e.getLoadHandlers=function(t,n){return e.getHandlers(t,`load`,n)},e.getHandlers=function(t,n,r){var i=[];return(n===`load`?e.getInstance().loadRouters:e.getInstance().saveRouters).forEach((function(e){var n=e(t,r);n!==null&&i.push(n)})),i},e}(),ff=`://`,pf=function(){function e(){this.managers={}}return e.getInstance=function(){return e.instance??=new e,e.instance},e.registerManager=function(t,n){I(t!=null,(function(){return`scheme must not be undefined or null.`})),t.endsWith(ff)&&(t=t.slice(0,t.indexOf(ff))),I(t.length>0,(function(){return`scheme must not be an empty string.`}));var r=e.getInstance();I(r.managers[t]==null,(function(){return`A model store manager is already registered for scheme '`+t+`'.`})),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(t==null)throw Error(`Cannot find model manager for scheme '`+e+`'`);return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function mf(e){if(e.indexOf(ff)===-1)throw Error(`The url string provided does not contain a scheme. Supported schemes are: `+pf.getSchemes().join(`,`));return{scheme:e.split(ff)[0],path:e.split(ff)[1]}}function hf(e,t,n){return n===void 0&&(n=!1),w(this,void 0,void 0,(function(){var r,i,a,o,s,c,l,u,d;return T(this,(function(f){switch(f.label){case 0:return I(e!==t,(function(){return`Old path and new path are the same: '`+e+`'`})),I((r=df.getLoadHandlers(e)).length>0,(function(){return`Copying failed because no load handler is found for source URL `+e+`.`})),I(r.length<2,(function(){return`Copying failed because more than one (`+r.length+`) load handlers for source URL `+e+`.`})),i=r[0],I((a=df.getSaveHandlers(t)).length>0,(function(){return`Copying failed because no save handler is found for destination URL `+t+`.`})),I(a.length<2,(function(){return`Copying failed because more than one (`+r.length+`) save handlers for destination URL `+t+`.`})),o=a[0],s=mf(e).scheme,c=mf(e).path,l=s===mf(e).scheme,[4,i.load()];case 1:return u=f.sent(),n&&l?[4,pf.getManager(s).removeModel(c)]:[3,3];case 2:f.sent(),f.label=3;case 3:return[4,o.save(u)];case 4:return d=f.sent(),!n||l?[3,6]:[4,pf.getManager(s).removeModel(c)];case 5:f.sent(),f.label=6;case 6:return[2,d.modelArtifactsInfo]}}))}))}var gf=`models_store`,_f=`model_info_store`;function vf(){if(!O().getBool(`IS_BROWSER`))throw Error(`Failed to obtain IndexedDB factory because the current environmentis not a web browser.`);var e=window||self,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw Error(`The current browser does not appear to support IndexedDB.`);return t}function yf(e){var t=e.result;t.createObjectStore(gf,{keyPath:`modelPath`}),t.createObjectStore(_f,{keyPath:`modelPath`})}var bf=function(){function e(e){if(this.indexedDB=vf(),e==null||!e)throw Error(`For IndexedDB, modelPath must not be null, undefined or empty.`);this.modelPath=e}return e.prototype.save=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserLocalStorage.save() does not support saving model topology in binary formats yet.`);return[2,this.databaseAction(this.modelPath,e)]}))}))},e.prototype.load=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){return[2,this.databaseAction(this.modelPath)]}))}))},e.prototype.databaseAction=function(e,t){var n=this;return new Promise((function(e,r){var i=n.indexedDB.open(`tensorflowjs`,1);i.onupgradeneeded=function(){return yf(i)},i.onsuccess=function(){var a=i.result;if(t==null){var o=a.transaction(gf,`readonly`),s=o.objectStore(gf).get(n.modelPath);s.onsuccess=function(){if(s.result==null)return a.close(),r(Error(`Cannot find model with path '`+n.modelPath+`' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=function(e){return a.close(),r(s.error)},o.oncomplete=function(){return a.close()}}else{var c,l=uf(t),u=a.transaction(_f,`readwrite`),d=u.objectStore(_f),f=d.put({modelPath:n.modelPath,modelArtifactsInfo:l});f.onsuccess=function(){var i=(c=a.transaction(gf,`readwrite`)).objectStore(gf).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});i.onsuccess=function(){return e({modelArtifactsInfo:l})},i.onerror=function(e){var t=(d=u.objectStore(_f)).delete(n.modelPath);t.onsuccess=function(){return a.close(),r(i.error)},t.onerror=function(e){return a.close(),r(i.error)}}},f.onerror=function(e){return a.close(),r(f.error)},u.oncomplete=function(){c==null?a.close():c.oncomplete=function(){return a.close()}}}},i.onerror=function(e){return r(i.error)}}))},e.URL_SCHEME=`indexeddb://`,e}(),xf=function(e){return O().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(bf.URL_SCHEME)?(t=e.slice(bf.URL_SCHEME.length),new bf(t)):null;var t};df.registerSaveRouter(xf),df.registerLoadRouter(xf);var Sf=function(){function e(){this.indexedDB=vf()}return e.prototype.listModels=function(){return w(this,void 0,void 0,(function(){var e=this;return T(this,(function(t){return[2,new Promise((function(t,n){var r=e.indexedDB.open(`tensorflowjs`,1);r.onupgradeneeded=function(){return yf(r)},r.onsuccess=function(){var e=r.result,i=e.transaction(_f,`readonly`),a=i.objectStore(_f).getAll();a.onsuccess=function(){for(var e={},n=0,r=a.result;n<r.length;n++){var i=r[n];e[i.modelPath]=i.modelArtifactsInfo}t(e)},a.onerror=function(t){return e.close(),n(a.error)},i.oncomplete=function(){return e.close()}},r.onerror=function(e){return n(r.error)}}))]}))}))},e.prototype.removeModel=function(e){return w(this,void 0,void 0,(function(){var t=this;return T(this,(function(n){var r;return e=(r=e).startsWith(bf.URL_SCHEME)?r.slice(bf.URL_SCHEME.length):r,[2,new Promise((function(n,r){var i=t.indexedDB.open(`tensorflowjs`,1);i.onupgradeneeded=function(){return yf(i)},i.onsuccess=function(){var t,a=i.result,o=a.transaction(_f,`readwrite`),s=o.objectStore(_f),c=s.get(e);c.onsuccess=function(){if(c.result==null)return a.close(),r(Error(`Cannot find model with path '`+e+`' in IndexedDB.`));var i=s.delete(e),o=function(){var i=(t=a.transaction(gf,`readwrite`)).objectStore(gf).delete(e);i.onsuccess=function(){return n(c.result.modelArtifactsInfo)},i.onerror=function(e){return r(c.error)}};i.onsuccess=o,i.onerror=function(e){return o(),a.close(),r(c.error)}},c.onerror=function(e){return a.close(),r(c.error)},o.oncomplete=function(){t==null?a.close():t.oncomplete=function(){return a.close()}}},i.onerror=function(e){return r(i.error)}}))]}))}))},e}();if(O().getBool(`IS_BROWSER`))try{pf.registerManager(bf.URL_SCHEME,new Sf)}catch{}var Cf=`/`,wf=`tensorflowjs_models`,Tf=`info`,Ef=`model_topology`,Df=`weight_specs`,Of=`weight_data`,kf=`model_metadata`;function Af(e){return{info:[wf,e,Tf].join(Cf),topology:[wf,e,Ef].join(Cf),weightSpecs:[wf,e,Df].join(Cf),weightData:[wf,e,Of].join(Cf),modelMetadata:[wf,e,kf].join(Cf)}}function jf(e){var t=e.split(Cf);if(t.length<3)throw Error(`Invalid key format: `+e);return t.slice(1,t.length-1).join(Cf)}var Mf=function(){function e(e){if(!O().getBool(`IS_BROWSER`)||typeof window>`u`||window.localStorage===void 0)throw Error(`The current environment does not support local storage.`);if(this.LS=window.localStorage,e==null||!e)throw Error(`For local storage, modelPath must not be null, undefined or empty.`);this.modelPath=e,this.keys=Af(this.modelPath)}return e.prototype.save=function(e){return w(this,void 0,void 0,(function(){var t,n,r;return T(this,(function(i){if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserLocalStorage.save() does not support saving model topology in binary formats yet.`);t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=uf(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(of)return Buffer.from(e).toString(`base64`);for(var t=new Uint8Array(e),n=``,r=0,i=t.length;r<i;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(e.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata})),[2,{modelArtifactsInfo:r}]}catch{throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),Error(`Failed to save model '`+this.modelPath+`' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=`+r.modelTopologyBytes+`, weightSpecsBytes=`+r.weightSpecsBytes+`, weightDataBytes=`+r.weightDataBytes+`.`)}return[2]}))}))},e.prototype.load=function(){return w(this,void 0,void 0,(function(){var e,t,n,r,i,a,o;return T(this,(function(s){if((e=JSON.parse(this.LS.getItem(this.keys.info)))==null)throw Error(`In local storage, there is no model with name '`+this.modelPath+`'`);if(e.modelTopologyType!==`JSON`)throw Error(`BrowserLocalStorage does not support loading non-JSON model topology yet.`);if(t={},(n=JSON.parse(this.LS.getItem(this.keys.topology)))==null)throw Error(`In local storage, the topology of model '`+this.modelPath+`' is missing.`);if(t.modelTopology=n,(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs)))==null)throw Error(`In local storage, the weight specs of model '`+this.modelPath+`' are missing.`);if(t.weightSpecs=r,(i=this.LS.getItem(this.keys.modelMetadata))!=null&&(a=JSON.parse(i),t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,t.userDefinedMetadata=a.userDefinedMetadata),(o=this.LS.getItem(this.keys.weightData))==null)throw Error(`In local storage, the binary weight values of model '`+this.modelPath+`' are missing.`);return t.weightData=function(e){if(of){var t=Buffer.from(e,`base64`);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}for(var n=atob(e),r=new Uint8Array(n.length),i=0;i<n.length;++i)r.set([n.charCodeAt(i)],i);return r.buffer}(o),[2,t]}))}))},e.URL_SCHEME=`localstorage://`,e}(),Nf=function(e){return O().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(Mf.URL_SCHEME)?(t=e.slice(Mf.URL_SCHEME.length),new Mf(t)):null;var t};df.registerSaveRouter(Nf),df.registerLoadRouter(Nf);var Pf=function(){function e(){I(O().getBool(`IS_BROWSER`),(function(){return`Current environment is not a web browser`})),I(typeof window>`u`||window.localStorage!==void 0,(function(){return`Current browser does not appear to support localStorage`})),this.LS=window.localStorage}return e.prototype.listModels=function(){return w(this,void 0,void 0,(function(){var e,t,n,r,i,a;return T(this,(function(o){for(e={},t=wf+Cf,n=Cf+Tf,r=0;r<this.LS.length;++r)(i=this.LS.key(r)).startsWith(t)&&i.endsWith(n)&&(a=jf(i),e[a]=JSON.parse(this.LS.getItem(i)));return[2,e]}))}))},e.prototype.removeModel=function(e){return w(this,void 0,void 0,(function(){var t,n;return T(this,(function(r){var i;if(e=(i=e).startsWith(Mf.URL_SCHEME)?i.slice(Mf.URL_SCHEME.length):i,t=Af(e),this.LS.getItem(t.info)==null)throw Error(`Cannot find model at path '`+e+`'`);return n=JSON.parse(this.LS.getItem(t.info)),this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),[2,n]}))}))},e}();if(O().getBool(`IS_BROWSER`))try{pf.registerManager(Mf.URL_SCHEME,new Pf)}catch{}var Ff=`model`,If=`.json`,Lf=`.weights.bin`;function Rf(e){return new Promise((function(e){return setTimeout(e)})).then(e)}var zf=function(){function e(t){if(!O().getBool(`IS_BROWSER`))throw Error(`browserDownloads() cannot proceed because the current environment is not a browser.`);t.startsWith(e.URL_SCHEME)&&(t=t.slice(e.URL_SCHEME.length)),t!=null&&t.length!==0||(t=Ff),this.modelTopologyFileName=t+If,this.weightDataFileName=t+Lf}return e.prototype.save=function(e){return w(this,void 0,void 0,(function(){var t,n,r,i,a,o;return T(this,(function(s){switch(s.label){case 0:if(typeof document>`u`)throw Error("Browser downloads are not supported in this environment since `document` is not present");if(t=window.URL.createObjectURL(new Blob([e.weightData],{type:`application/octet-stream`})),!(e.modelTopology instanceof ArrayBuffer))return[3,1];throw Error(`BrowserDownloads.save() does not support saving model topology in binary formats yet.`);case 1:return n=[{paths:[`./`+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:`application/json`})),(a=this.jsonAnchor==null?document.createElement(`a`):this.jsonAnchor).download=this.modelTopologyFileName,a.href=i,[4,Rf((function(){return a.dispatchEvent(new MouseEvent(`click`))}))];case 2:return s.sent(),e.weightData==null?[3,4]:((o=this.weightDataAnchor==null?document.createElement(`a`):this.weightDataAnchor).download=this.weightDataFileName,o.href=t,[4,Rf((function(){return o.dispatchEvent(new MouseEvent(`click`))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:uf(e)}]}}))}))},e.URL_SCHEME=`downloads://`,e}(),Bf=function(){function e(e){if(e==null||e.length<1)throw Error(`When calling browserFiles, at least 1 file is required, but received `+e);this.files=e}return e.prototype.load=function(){return w(this,void 0,void 0,(function(){var e,t,n=this;return T(this,(function(r){return e=this.files[0],t=this.files.slice(1),[2,new Promise((function(r,i){var a=new FileReader;a.onload=function(a){var o=JSON.parse(a.target.result),s=o.modelTopology;if(s!=null){t.length===0&&r({modelTopology:s});var c=o.weightsManifest;if(c!=null){var l;try{l=n.checkManifestAndWeightFiles(c,t)}catch(e){i(e);return}var u=[],d=[],f=[];c.forEach((function(e){e.paths.forEach((function(e){d.push(e),f.push(null)})),u.push.apply(u,e.weights)})),c.forEach((function(e){e.paths.forEach((function(e){var t=new FileReader;t.onload=function(t){var n=t.target.result,i=d.indexOf(e);f[i]=n,f.indexOf(null)===-1&&r({modelTopology:s,weightSpecs:u,weightData:cf(f),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},t.onerror=function(t){return i(`Failed to weights data from file of path '`+e+`'.`)},t.readAsArrayBuffer(l[e])}))}))}else i(Error(`weightManifest field is missing from file `+e.name))}else i(Error(`modelTopology field is missing from file `+e.name))},a.onerror=function(t){return i(`Failed to read model topology and weights manifest JSON from file '`+e.name+`'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`)},a.readAsText(e)}))]}))}))},e.prototype.checkManifestAndWeightFiles=function(e,t){for(var n=[],r=t.map((function(e){return lf(e.name)})),i={},a=0,o=e;a<o.length;a++)o[a].paths.forEach((function(e){var a=lf(e);if(n.indexOf(a)!==-1)throw Error(`Duplicate file basename found in weights manifest: '`+a+`'`);if(n.push(a),r.indexOf(a)===-1)throw Error(`Weight file with basename '`+a+`' is not provided.`);i[e]=t[r.indexOf(a)]}));if(n.length!==t.length)throw Error(`Mismatch in the number of files in weights manifest (`+n.length+`) and the number of weight files provided (`+t.length+`).`);return i},e}();function Vf(e,t,n,r){(function(e){I(e!=null&&Array.isArray(e)&&e.length>0,(function(){return`promises must be a none empty array`}))})(e),function(e,t){I(e>=0&&e<=1,(function(){return`Progress fraction must be in range [0, 1], but got startFraction `+e})),I(t>=0&&t<=1,(function(){return`Progress fraction must be in range [0, 1], but got endFraction `+t})),I(t>=e,(function(){return`startFraction must be no more than endFraction, but got startFraction `+e+` and endFraction `+t}))}(n??=0,r??=1);var i=0;return Promise.all(e.map((function(a){return a.then((function(a){return t(n+ ++i/e.length*(r-n)),a})),a})))}function Hf(e,t){return w(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u;return T(this,(function(d){switch(d.label){case 0:return t??={},n=t.fetchFunc==null?O().platform.fetch:t.fetchFunc,r=e.map((function(e){return n(e,t.requestInit,{isBinary:!0})})),i=0,a=.5,t.onProgress==null?[4,Promise.all(r)]:[3,2];case 1:return o=d.sent(),[3,4];case 2:return[4,Vf(r,t.onProgress,i,a)];case 3:o=d.sent(),d.label=4;case 4:return s=o.map((function(e){return e.arrayBuffer()})),c=.5,l=1,t.onProgress==null?[4,Promise.all(s)]:[3,6];case 5:return u=d.sent(),[3,8];case 6:return[4,Vf(s,t.onProgress,c,l)];case 7:u=d.sent(),d.label=8;case 8:return[2,u]}}))}))}function Uf(e){var t=this;return function(n,r,i){return r===void 0&&(r=``),w(t,void 0,void 0,(function(){var t,a,o,s,c,l,u,d,f,p;return T(this,(function(m){switch(m.label){case 0:if(t=n.map((function(){return!1})),a={},o=i==null?[]:i.map((function(){return!1})),s=[],n.forEach((function(e,n){var r=0;e.weights.forEach((function(e){var c=tf[`quantization`in e?e.quantization.dtype:e.dtype]*R(e.shape),l=function(){t[n]=!0,a[n]??(a[n]=[]),a[n].push({manifestEntry:e,groupOffset:r,sizeBytes:c})};i==null?l():i.forEach((function(t,n){t===e.name&&(l(),o[n]=!0)})),s.push(e.name),r+=c}))})),!o.every((function(e){return e})))throw c=i.filter((function(e,t){return!o[t]})),Error(`Could not find weights in manifest with names: `+c.join(`, `)+`.
|
|
3800
|
+
Manifest JSON has weights with names: `+s.join(`, `)+`.`);return l=t.reduce((function(e,t,n){return t&&e.push(n),e}),[]),u=[],l.forEach((function(e){n[e].paths.forEach((function(e){var t=r+(r.endsWith(`/`)?``:`/`)+e;u.push(t)}))})),[4,e(u)];case 1:return d=m.sent(),f={},p=0,l.forEach((function(e){for(var t=n[e].paths.length,r=0,i=0;i<t;i++)r+=d[p+i].byteLength;for(var o=new ArrayBuffer(r),s=new Uint8Array(o),c=0,l=0;l<t;l++){var u=new Uint8Array(d[p+l]);s.set(u,c),c+=u.byteLength}a[e].forEach((function(e){var t=rf(o.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(var n in t)f[n]=t[n]})),p+=t})),[2,f]}}))}))}}df.registerSaveRouter((function(e){return O().getBool(`IS_BROWSER`)&&!Array.isArray(e)&&e.startsWith(zf.URL_SCHEME)?function(e){return e===void 0&&(e=`model`),new zf(e)}(e.slice(zf.URL_SCHEME.length)):null}));var Wf=function(){function e(e,t){if(this.DEFAULT_METHOD=`POST`,t??={},this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc==null?this.fetch=O().platform.fetch:(I(typeof t.fetchFunc==`function`,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=t.fetchFunc),I(e!=null&&e.length>0,(function(){return`URL path for http must not be null, undefined or empty.`})),Array.isArray(e)&&I(e.length===2,(function(){return`URL paths for http must have a length of 2, (actual length is `+e.length+`).`})),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw Error(`requestInit is expected to have no pre-existing body, but has one.`);this.requestInit=t.requestInit||{}}return e.prototype.save=function(e){return w(this,void 0,void 0,(function(){var t,n,r,i;return T(this,(function(a){switch(a.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw Error(`BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.`);return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:[`./model.weights.bin`],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n},t.body.append(`model.json`,new Blob([JSON.stringify(r)],{type:`application/json`}),`model.json`),e.weightData!=null&&t.body.append(`model.weights.bin`,new Blob([e.weightData],{type:`application/octet-stream`}),`model.weights.bin`),[4,this.fetch(this.path,t)];case 1:if((i=a.sent()).ok)return[2,{modelArtifactsInfo:uf(e),responses:[i]}];throw Error(`BrowserHTTPRequest.save() failed due to HTTP response status `+i.status+`.`)}}))}))},e.prototype.load=function(){return w(this,void 0,void 0,(function(){var e,t,n,r,i,a,o,s,c,l,u,d;return T(this,(function(f){switch(f.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(e=f.sent()).ok)throw Error(`Request to `+this.path+` failed with status code `+e.status+`. Please verify this URL points to the model JSON of the model to load.`);f.label=2;case 2:return f.trys.push([2,4,,5]),[4,e.json()];case 3:return t=f.sent(),[3,5];case 4:throw f.sent(),n=`Failed to parse model JSON of response from `+this.path+`.`,this.path.endsWith(`.pb`)?n+=` Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.`:n+=` Please make sure the server is serving valid JSON for this request.`,Error(n);case 5:if(r=t.modelTopology,i=t.weightsManifest,a=t.generatedBy,o=t.convertedBy,s=t.format,c=t.userDefinedMetadata,r==null&&i==null)throw Error(`The JSON from HTTP path `+this.path+` contains neither model topology or manifest for weights.`);return i==null?[3,7]:[4,this.loadWeights(i)];case 6:d=f.sent(),l=d[0],u=d[1],f.label=7;case 7:return[2,{modelTopology:r,weightSpecs:l,weightData:u,userDefinedMetadata:c,generatedBy:a,convertedBy:o,format:s}]}}))}))},e.prototype.loadWeights=function(e){return w(this,void 0,void 0,(function(){var t,n,r,i,a,o,s,c,l,u,d;return T(this,(function(f){switch(f.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=function(e){var t=e.lastIndexOf(`/`),n=e.lastIndexOf(`?`),r=e.substring(0,t),i=n>t?e.substring(n):``;return[r+`/`,i]}(t),r=n[0],i=n[1],a=this.weightPathPrefix||r,o=[],s=0,c=e;s<c.length;s++)l=c[s],o.push.apply(o,l.weights);return u=[],e.forEach((function(e){e.paths.forEach((function(e){u.push(a+e+i)}))})),[4,Hf(u,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return d=f.sent(),[2,[o,cf(d)]]}}))}))},e.URL_SCHEME_REGEX=/^https?:\/\//,e}();function Gf(e){return e.match(Wf.URL_SCHEME_REGEX)!=null}var Kf=function(e,t){return typeof fetch>`u`?null:(Array.isArray(e)?e.every((function(e){return Gf(e)})):Gf(e))?qf(e,{onProgress:t}):null};function qf(e,t){return new Wf(e,t)}df.registerSaveRouter(Kf),df.registerLoadRouter(Kf);var Jf=function(){function e(e){this.modelArtifacts=e}return e.prototype.load=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){return[2,this.modelArtifacts]}))}))},e}(),Yf=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){return[2,this.saveHandler(e)]}))}))},e}(),Xf=Object.freeze({browserFiles:function(e){return new Bf(e)},browserHTTPRequest:function(e,t){return qf(e,t)},concatenateArrayBuffers:cf,decodeWeights:rf,encodeWeights:function(e,t){return w(this,void 0,void 0,(function(){var n,r,i,a,o,s=this;return T(this,(function(c){switch(c.label){case 0:for(n=[],r=[],i=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e),a=function(a){var o=i[a],c=Array.isArray(e)?e[a].tensor:e[o];if(c.dtype!==`float32`&&c.dtype!==`int32`&&c.dtype!==`bool`&&c.dtype!==`string`)throw Error(`Unsupported dtype in weight '`+o+`': `+c.dtype);var l={name:o,shape:c.shape,dtype:c.dtype};if(c.dtype===`string`){var u=new Promise((function(e){return w(s,void 0,void 0,(function(){var t,n,r,i,a,o,s;return T(this,(function(l){switch(l.label){case 0:return[4,c.bytes()];case 1:for(t=l.sent(),n=t.reduce((function(e,t){return e+t.length}),0)+nf*t.length,r=new Uint8Array(n),i=0,a=0;a<t.length;a++)o=t[a],s=new Uint8Array(new Uint32Array([o.length]).buffer),r.set(s,i),i+=nf,r.set(o,i),i+=o.length;return e(r),[2]}}))}))}));r.push(u)}else r.push(c.data());t!=null&&(l.group=t),n.push(l)},o=0;o<i.length;++o)a(o);return[4,Promise.all(r)];case 1:return[2,{data:af(c.sent()),specs:n}]}}))}))},fromMemory:function(e,t,n,r){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Jf(e):(console.warn(`Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release.`),new Jf({modelTopology:e})):(console.warn(`Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release.`),new Jf({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))},getLoadHandlers:function(e,t){return df.getLoadHandlers(e,t)},getModelArtifactsInfoForJSON:uf,getSaveHandlers:function(e){return df.getSaveHandlers(e)},http:qf,isHTTPScheme:Gf,loadWeights:function(e,t,n,r){return t===void 0&&(t=``),w(this,void 0,void 0,(function(){return T(this,(function(i){return[2,Uf((function(e){return Hf(e,{requestInit:r})}))(e,t,n)]}))}))},registerLoadRouter:function(e){return df.registerLoadRouter(e)},registerSaveRouter:function(e){return df.registerSaveRouter(e)},weightsLoaderFactory:Uf,withSaveHandler:function(e){return new Yf(e)},copyModel:function(e,t){return w(this,void 0,void 0,(function(){return T(this,(function(n){return[2,hf(e,t,!1)]}))}))},listModels:function(){return w(this,void 0,void 0,(function(){var e,t,n,r,i,a,o;return T(this,(function(s){switch(s.label){case 0:e=pf.getSchemes(),t={},n=0,r=e,s.label=1;case 1:return n<r.length?(i=r[n],[4,pf.getManager(i).listModels()]):[3,4];case 2:for(o in a=s.sent())t[i+ff+o]=a[o];s.label=3;case 3:return n++,[3,1];case 4:return[2,t]}}))}))},moveModel:function(e,t){return w(this,void 0,void 0,(function(){return T(this,(function(n){return[2,hf(e,t,!0)]}))}))},removeModel:function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){return t=mf(e),[2,pf.getManager(t.scheme).removeModel(t.path)]}))}))}}),Zf,Qf=K({confusionMatrix_:function(e,t,n){var r=G(e,`labels`,`confusionMatrix`),i=G(t,`predictions`,`confusionMatrix`);I(n==null||n>0&&Number.isInteger(n),(function(){return`If provided, numClasses must be a positive integer, but got `+n})),I(r.rank===1,(function(){return`Expected the rank of labels to be 1, but got `+r.rank})),I(i.rank===1,(function(){return`Expected the rank of predictions to be 1, but got `+i.rank})),I(r.shape[0]===i.shape[0],(function(){return`Mismatch in the number of examples: `+r.shape[0]+` vs. `+i.shape[0]+`. Labels and predictions should have the same number of elements.`})),I(n>0&&Number.isInteger(n),(function(){return`numClasses is required to be a positive integer, but got `+n}));var a=Ar(r.asType(`int32`),n),o=Ar(i.asType(`int32`),n);return a.transpose().matMul(o).asType(`int32`)}});Object.freeze({confusionMatrix:Qf});var $f=K({fromPixels_:function(e,t){if(t===void 0&&(t=3),t>4)throw Error(`Cannot construct Tensor with more than 4 channels from pixels.`);if(e==null)throw Error(`pixels passed to tf.browser.fromPixels() can not be null`);var n=!1,r=!1,i=!1,a=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData<`u`&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement<`u`&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement)a=!0;else{if(e.getContext==null)throw Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was `+e.constructor.name);o=!0}if(i&&i&&e.readyState<2)throw Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(M(`FromPixels`,V.backendName)!=null)return V.runKernel(`FromPixels`,{pixels:e},{numChannels:t});var s,c,l=i?[e.videoWidth,e.videoHeight]:[e.width,e.height],u=l[0],d=l[1];if(o?s=e.getContext(`2d`).getImageData(0,0,u,d).data:r||n?s=e.data:(a||i)&&(Zf??=document.createElement(`canvas`).getContext(`2d`),Zf.canvas.width=u,Zf.canvas.height=d,Zf.drawImage(e,0,0,u,d),s=Zf.getImageData(0,0,u,d).data),t===4)c=new Int32Array(s);else{var f=u*d;c=new Int32Array(f*t);for(var p=0;p<f;p++)for(var m=0;m<t;++m)c[p*t+m]=s[4*p+m]}return Wn(c,[d,u,t],`int32`)}}),ep=Object.freeze({toPixels:function(e,t){return w(this,void 0,void 0,(function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w;return T(this,(function(T){switch(T.label){case 0:if(n=G(e,`img`,`toPixels`),e instanceof $e||(n=n.toInt()),n.rank!==2&&n.rank!==3)throw Error(`toPixels only supports rank 2 or 3 tensors, got rank `+n.rank+`.`);if(r=n.shape.slice(0,2),i=r[0],a=r[1],(o=n.rank===2?1:n.shape[2])>4||o===2)throw Error(`toPixels only supports depth of size 1, 3 or 4 but got `+o);return[4,n.data()];case 1:return s=T.sent(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(u=T.sent(),d=u[0],f=u[1],p=d[0],m=f[0],c.dispose(),l.dispose(),n.dtype===`float32`){if(p<0||m>1)throw Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [`+p+` - `+m+`].`)}else{if(n.dtype!==`int32`)throw Error(`Unsupported type for toPixels: `+n.dtype+`. Please use float32 or int32 tensors.`);if(p<0||m>255)throw Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [`+p+` - `+m+`].`)}for(h=n.dtype===`float32`?255:1,g=new Uint8ClampedArray(a*i*4),_=0;_<i*a;++_)v=void 0,y=void 0,b=void 0,x=void 0,o===1?(v=s[_]*h,y=s[_]*h,b=s[_]*h,x=255):o===3?(v=s[3*_]*h,y=s[3*_+1]*h,b=s[3*_+2]*h,x=255):o===4&&(v=s[4*_]*h,y=s[4*_+1]*h,b=s[4*_+2]*h,x=s[4*_+3]*h),g[(S=4*_)+0]=Math.round(v),g[S+1]=Math.round(y),g[S+2]=Math.round(b),g[S+3]=Math.round(x);return t!=null&&(t.width=a,t.height=i,C=t.getContext(`2d`),w=new ImageData(g,a,i),C.putImageData(w,0,0)),n!==e&&n.dispose(),[2,g]}}))}))},fromPixels:$f}),tp=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(e,t){return new e(t)},e}(),np=function(){function e(){this.classNameMap={}}return e.getMap=function(){return e.instance??=new e,e.instance},e.register=function(t){e.getMap().classNameMap[t.className]=[t,t.fromConfig]},e}();function rp(e){I(e.className!=null,(function(){return`Class being registered does not have the static className property defined.`})),I(typeof e.className==`string`,(function(){return`className is required to be a string, but got type `+typeof e.className})),I(e.className.length>0,(function(){return`Class being registered has an empty-string as its className, which is disallowed.`})),np.register(e)}Object.freeze({Serializable:tp,SerializationMap:np,registerClass:rp});var ip=.001,ap=.1;function op(){return V.backend.floatPrecision()===32?ip:ap}function sp(e,t,n){var r=!0;if((xe(e)||xe(t))&&(r=!1),xe(e)&&xe(t)&&(r=!0),r){var i=e.constructor.name,a=t.constructor.name;if(i!==a)throw Error(`Arrays are of different type. Actual: `+i+`. Expected: `+a)}if(Array.isArray(e)&&Array.isArray(t)){var o=wn(e),s=wn(t);if(!z(o,s))throw Error(`Arrays have different shapes. Actual: [`+o+`]. Expected: [`+s+`]`)}var c=xe(e)?e:se(e),l=xe(t)?t:se(t);if(c.length!==l.length)throw Error(`Arrays have different lengths actual: `+c.length+` vs expected: `+l.length+`.
|
|
3801
3801
|
Actual: `+c+`.
|
|
3802
3802
|
Expected: `+l+`.`);for(var u=0;u<l.length;++u){var d=c[u],f=l[u];if(!n(d,f))throw Error(`Arrays differ: actual[`+u+`] = `+d+`, expected[`+u+`] = `+f+`.
|
|
3803
3803
|
Actual: `+c+`.
|
|
3804
|
-
Expected: `+l+`.`)}}function Jf(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}Object.freeze({TEST_EPSILON_FLOAT16:Gf,expectArraysClose:function(e,t,n){return n??=Kf(),qf(e,t,(function(e,t){return Jf(e,t,n)}))},testEpsilon:Kf,expectPromiseToFail:function(e,t){e().then((function(){return t.fail()}),(function(){return t()}))},expectArraysEqual:function(e,t){var n=typeof t==`string`||typeof t==`number`||typeof t==`boolean`?[t]:t;return fe(e)||fe(e[0])||fe(t)||fe(t[0])?qf(e,n,(function(e,t){return e==t})):qf(e,t,(function(e,t){return Jf(e,t,0)}))},expectNumbersClose:function(e,t,n){if(n??=Kf(),!Jf(e,t,n))throw Error(`Numbers differ: actual === `+e+`, expected === `+t)},expectValuesInRange:function(e,t,n){for(var r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw Error(`Value out of range:`+e[r]+` low: `+t+`, high: `+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),Object.freeze({gpgpu_util:vo,webgl_util:sn,forceHalfFloat:function(){m().set(`WEBGL_FORCE_F16_TEXTURES`,!0)},MathBackendWebGL:Fs,setWebGLContext:ut,GPGPUContext:yo});var Yf=function(e){function t(){return e!==null&&e.apply(this,arguments)||this}return l(t,e),t.prototype.minimize=function(e,t,n){t===void 0&&(t=!1);var r=this.computeGradients(e,n),i=r.value,a=r.grads;if(n!=null){var o=n.map((function(e){return{name:e.name,tensor:a[e.name]}}));this.applyGradients(o)}else this.applyGradients(a);return ln(a),t?i:(i.dispose(),null)},Object.defineProperty(t.prototype,`iterations`,{get:function(){return this.iterations_??=0,this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,t){return ei(e,t)},t.prototype.dispose=function(){this.iterations_!=null&&ln(this.iterations_)},t.prototype.saveIterations=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){return this.iterations_??=0,[2,{name:`iter`,tensor:G(this.iterations_,`int32`)}]}))}))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){throw Error(`getWeights() is not implemented for this optimizer yet.`)}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(e){throw Error(`setWeights() is not implemented for this optimizer class `+this.getClassName())}))}))},t.prototype.extractIterations=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return t=this,[4,e[0].tensor.data()];case 1:return t.iterations_=n.sent()[0],[2,e.slice(1)]}}))}))},t}(Vf);Object.defineProperty(Yf,Symbol.hasInstance,{value:function(e){return e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null}});var Xf=function(e){function t(t,n,r){r===void 0&&(r=null);var i=e.call(this)||this;return i.learningRate=t,i.rho=n,i.epsilon=r,i.accumulatedGrads=[],i.accumulatedUpdates=[],r??(i.epsilon=z.backend.epsilon()),i}return l(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=z.registeredVariables[n];t.accumulatedGrads[r]??(t.accumulatedGrads[r]={originalName:n+`/accum_grad`,variable:H((function(){return Un(i).variable(!1)}))}),t.accumulatedUpdates[r]??(t.accumulatedUpdates[r]={originalName:n+`/accum_var`,variable:H((function(){return Un(i).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedGrads[r].variable,s=t.accumulatedUpdates[r].variable;H((function(){var e=o.mul(t.rho).add(a.square().mul(1-t.rho)),n=s.add(t.epsilon).sqrt().div(o.add(t.epsilon).sqrt()).mul(a),r=s.mul(t.rho).add(n.square().mul(1-t.rho));o.assign(e),s.assign(r);var c=n.mul(-t.learningRate).add(i);i.assign(c)}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedUpdates!=null&&(ln(this.accumulatedGrads.map((function(e){return e.variable}))),ln(this.accumulatedUpdates.map((function(e){return e.variable}))))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=e.length/2,this.accumulatedGrads=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedUpdates=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className=`Adadelta`,t}(Yf);Uf(Xf);var Zf=function(e){function t(t,n){n===void 0&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return l(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=z.registeredVariables[n];t.accumulatedGrads[r]??(t.accumulatedGrads[r]={originalName:n+`/accumulator`,variable:H((function(){return zn(i.shape,t.initialAccumulatorValue).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedGrads[r].variable;H((function(){var e=o.add(a.square());o.assign(e);var n=a.div(e.add(z.backend.epsilon()).sqrt()).mul(-t.learningRate).add(i);i.assign(n)}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedGrads!=null&&ln(this.accumulatedGrads.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulatedGrads=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className=`Adagrad`,t}(Yf);Uf(Zf);var Qf=function(e){function t(t,n,r,i){i===void 0&&(i=null);var a=e.call(this)||this;return a.learningRate=t,a.beta1=n,a.beta2=r,a.epsilon=i,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],H((function(){a.accBeta1=G(n).variable(),a.accBeta2=G(r).variable()})),i??(a.epsilon=z.backend.epsilon()),a}return l(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);H((function(){var r=il(1,t.accBeta1),i=il(1,t.accBeta2);n.forEach((function(n,a){var o=z.registeredVariables[n];t.accumulatedFirstMoment[a]??(t.accumulatedFirstMoment[a]={originalName:n+`/m`,variable:H((function(){return Un(o).variable(!1)}))}),t.accumulatedSecondMoment[a]??(t.accumulatedSecondMoment[a]={originalName:n+`/v`,variable:H((function(){return Un(o).variable(!1)}))});var s=Array.isArray(e)?e[a].tensor:e[n];if(s!=null){var c=t.accumulatedFirstMoment[a].variable,l=t.accumulatedSecondMoment[a].variable,u=c.mul(t.beta1).add(s.mul(1-t.beta1)),d=l.mul(t.beta2).add(s.square().mul(1-t.beta2)),f=u.div(r),p=d.div(i);c.assign(u),l.assign(d);var m=f.div(p.sqrt().add(t.epsilon)).mul(-t.learningRate).add(o);o.assign(m)}})),t.accBeta1.assign(t.accBeta1.mul(t.beta1)),t.accBeta2.assign(t.accBeta2.mul(t.beta2))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&ln(this.accumulatedFirstMoment.map((function(e){return e.variable}))),this.accumulatedSecondMoment!=null&&ln(this.accumulatedSecondMoment.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){var t,n=this;return d(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),H((function(){n.accBeta1.assign(tl(n.beta1,n.iterations_+1)),n.accBeta2.assign(tl(n.beta2,n.iterations_+1))})),t=e.length/2,this.accumulatedFirstMoment=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedSecondMoment=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className=`Adam`,t}(Yf);Uf(Qf);var $f=function(e){function t(t,n,r,i,a){i===void 0&&(i=null),a===void 0&&(a=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=i,o.decay=a,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],H((function(){o.iteration=G(0).variable(),o.accBeta1=G(n).variable()})),i??(o.epsilon=z.backend.epsilon()),o}return l(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);H((function(){var r=il(1,t.accBeta1),i=Uc(-t.learningRate,t.iteration.mul(t.decay).add(1));n.forEach((function(n,a){var o=z.registeredVariables[n];t.accumulatedFirstMoment[a]??(t.accumulatedFirstMoment[a]={originalName:n+`/m`,variable:Un(o).variable(!1)}),t.accumulatedWeightedInfNorm[a]??(t.accumulatedWeightedInfNorm[a]={originalName:n+`/v`,variable:Un(o).variable(!1)});var s=Array.isArray(e)?e[a].tensor:e[n];if(s!=null){var c=t.accumulatedFirstMoment[a].variable,l=t.accumulatedWeightedInfNorm[a].variable,u=c.mul(t.beta1).add(s.mul(1-t.beta1)),d=l.mul(t.beta2),f=s.abs(),p=d.maximum(f);c.assign(u),l.assign(p);var m=i.div(r).mul(u.div(p.add(t.epsilon))).add(o);o.assign(m)}})),t.iteration.assign(t.iteration.add(1)),t.accBeta1.assign(t.accBeta1.mul(t.beta1))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ln(this.accumulatedFirstMoment.map((function(e){return e.variable}))),this.accumulatedWeightedInfNorm!=null&&ln(this.accumulatedWeightedInfNorm.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){throw Error(`getWeights() is not implemented for Adamax yet.`)}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(e){throw Error(`setWeights() is not implemented for Adamax yet.`)}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className=`Adamax`,t}(Yf);Uf($f);var ep=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return l(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=Array.isArray(e)?e[r].tensor:e[n];if(i!=null){var a=z.registeredVariables[n];H((function(){var e=t.c.mul(i).add(a);a.assign(e)}))}})),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=un(G(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:if((e=t.sent()).length!==0)throw Error(`SGD optimizer does not have settable weights.`);return[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className=`SGD`,t}(Yf);Uf(ep);var tp=function(e){function t(t,n,r){r===void 0&&(r=!1);var i=e.call(this,t)||this;return i.learningRate=t,i.momentum=n,i.useNesterov=r,i.accumulations=[],i.m=G(i.momentum),i}return l(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=z.registeredVariables[n];t.accumulations[r]??(t.accumulations[r]={originalName:n+`/momentum`,variable:H((function(){return Un(i).variable(!1)}))});var a=t.accumulations[r].variable,o=Array.isArray(e)?e[r].tensor:e[n];o!=null&&H((function(){var e,n=t.m.mul(a).add(o);e=t.useNesterov?t.c.mul(o.add(n.mul(t.m))).add(i):t.c.mul(n).add(i),a.assign(n),i.assign(e)}))})),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&ln(this.accumulations.map((function(e){return e.variable})))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulations=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className=`Momentum`,t}(ep);Uf(tp);var np=function(e){function t(t,n,r,i,a){n===void 0&&(n=.9),r===void 0&&(r=0),i===void 0&&(i=null),a===void 0&&(a=!1);var o=e.call(this)||this;if(o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=i,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=a,i??(o.epsilon=z.backend.epsilon()),t==null)throw Error(`learningRate for RMSPropOptimizer must be defined.`);return o}return l(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=z.registeredVariables[n];t.accumulatedMeanSquares[r]??(t.accumulatedMeanSquares[r]={originalName:n+`/rms`,variable:H((function(){return Un(i).variable(!1)}))}),t.accumulatedMoments[r]??(t.accumulatedMoments[r]={originalName:n+`/momentum`,variable:H((function(){return Un(i).variable(!1)}))}),t.accumulatedMeanGrads[r]==null&&t.centered&&(t.accumulatedMeanGrads[r]={originalName:n+`/mg`,variable:H((function(){return Un(i).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedMeanSquares[r].variable,s=t.accumulatedMoments[r].variable;H((function(){var e=o.mul(t.decay).add(a.square().mul(1-t.decay));if(t.centered){var n=t.accumulatedMeanGrads[r].variable,c=n.mul(t.decay).add(a.mul(1-t.decay)),l=s.mul(t.momentum).add(a.mul(t.learningRate).div(e.sub(c.square().add(t.epsilon)).sqrt()));o.assign(e),n.assign(c),s.assign(l);var u=i.sub(l);i.assign(u)}else{var d=o.mul(t.decay).add(a.square().mul(1-t.decay));l=s.mul(t.momentum).add(a.mul(t.learningRate).div(d.add(t.epsilon).sqrt())),o.assign(d),s.assign(l),u=i.sub(l),i.assign(u)}}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&ln(this.accumulatedMeanSquares.map((function(e){return e.variable}))),this.accumulatedMeanGrads!=null&&this.centered&&ln(this.accumulatedMeanGrads.map((function(e){return e.variable}))),this.accumulatedMoments!=null&&ln(this.accumulatedMoments.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=this.centered?e.length/3:e.length/2,this.accumulatedMeanSquares=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedMoments=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}))),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className=`RMSProp`,t}(Yf);Uf(np);var rp=function(){function e(){}return e.sgd=function(e){return new ep(e)},e.momentum=function(e,t,n){return n===void 0&&(n=!1),new tp(e,t,n)},e.rmsprop=function(e,t,n,r,i){return t===void 0&&(t=.9),n===void 0&&(n=0),r===void 0&&(r=null),i===void 0&&(i=!1),new np(e,t,n,r,i)},e.adam=function(e,t,n,r){return e===void 0&&(e=.001),t===void 0&&(t=.9),n===void 0&&(n=.999),r===void 0&&(r=null),new Qf(e,t,n,r)},e.adadelta=function(e,t,n){return e===void 0&&(e=.001),t===void 0&&(t=.95),n===void 0&&(n=null),new Xf(e,t,n)},e.adamax=function(e,t,n,r,i){return e===void 0&&(e=.002),t===void 0&&(t=.9),n===void 0&&(n=.999),r===void 0&&(r=null),i===void 0&&(i=0),new $f(e,t,n,r,i)},e.adagrad=function(e,t){return t===void 0&&(t=.1),new Zf(e,t)},e}();rp.sgd,rp.momentum,rp.adadelta,rp.adagrad,rp.rmsprop,rp.adamax,rp.adam,Ve.prototype.squaredDifference=function(e){return Rs(this,e)},R=Td;function ip(e,t,n){if(n===void 0&&(n=!1),e.beginPath(),t.slice(1).forEach(function(n,r){var i=n.x,a=n.y,o=t[r];e.moveTo(o.x,o.y),e.lineTo(i,a)}),n){var r=t[t.length-1],i=t[0];if(!r||!i)return;e.moveTo(r.x,r.y),e.lineTo(i.x,i.y)}e.stroke()}var ap=function(e,t){return ap=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},ap(e,t)};function Z(e,t){ap(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var op=function(){return op=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},op.apply(this,arguments)};function Q(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function $(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}}function sp(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}var cp=function(){function e(e,t){if(!bp(e)||!bp(t))throw Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have `+JSON.stringify({width:e,height:t}));this._width=e,this._height=t}return Object.defineProperty(e.prototype,`width`,{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`height`,{get:function(){return this._height},enumerable:!0,configurable:!0}),e.prototype.reverse=function(){return new e(1/this.width,1/this.height)},e}();function lp(e,t){return e instanceof Ve&&e.shape.length===t}function up(e){return lp(e,2)}function dp(e){return lp(e,3)}function fp(e){return lp(e,4)}function pp(e){return e%1!=0}function mp(e){return e%2==0}function hp(e,t){t===void 0&&(t=2);var n=10**t;return Math.floor(e*n)/n}function gp(e){return e&&e.width&&e.height}function _p(e,t){var n=e.width,r=e.height,i=t/Math.max(r,n);return new cp(Math.round(n*i),Math.round(r*i))}function vp(e){return e.reduce(function(e,t){return e.add(t)},new Sp(0,0)).div(new Sp(e.length,e.length))}function yp(e,t,n){return Array(e).fill(0).map(function(e,r){return t+r*n})}function bp(e){return!!e&&e!==1/0&&e!==-1/0&&!isNaN(e)||e===0}function xp(e){return bp(e)&&0<=e&&e<=1}var Sp=function(){function e(e,t){this._x=e,this._y=t}return Object.defineProperty(e.prototype,`x`,{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`y`,{get:function(){return this._y},enumerable:!0,configurable:!0}),e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.sub=function(t){return new e(this.x-t.x,this.y-t.y)},e.prototype.mul=function(t){return new e(this.x*t.x,this.y*t.y)},e.prototype.div=function(t){return new e(this.x/t.x,this.y/t.y)},e.prototype.abs=function(){return new e(Math.abs(this.x),Math.abs(this.y))},e.prototype.magnitude=function(){return Math.sqrt(this.x**2+this.y**2)},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y))},e}(),Cp=function(){function e(t,n){n===void 0&&(n=!0);var r=t||{},i=[r.left,r.top,r.right,r.bottom].every(bp),a=[r.x,r.y,r.width,r.height].every(bp);if(!a&&!i)throw Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have `+JSON.stringify(r));var o=a?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top],s=o[0],c=o[1],l=o[2],u=o[3];e.assertIsValidBox({x:s,y:c,width:l,height:u},`Box.constructor`,n),this._x=s,this._y=c,this._width=l,this._height=u}return e.isRect=function(e){return!!e&&[e.x,e.y,e.width,e.height].every(bp)},e.assertIsValidBox=function(t,n,r){if(r===void 0&&(r=!1),!e.isRect(t))throw Error(n+` - invalid box: `+JSON.stringify(t)+`, expected object with properties x, y, width, height`);if(!r&&(t.width<0||t.height<0))throw Error(n+` - width (`+t.width+`) and height (`+t.height+`) must be positive numbers`)},Object.defineProperty(e.prototype,`x`,{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`y`,{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`width`,{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`height`,{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`left`,{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`top`,{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`right`,{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottom`,{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`area`,{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`topLeft`,{get:function(){return new Sp(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`topRight`,{get:function(){return new Sp(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottomLeft`,{get:function(){return new Sp(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottomRight`,{get:function(){return new Sp(this.right,this.bottom)},enumerable:!0,configurable:!0}),e.prototype.round=function(){var t=[this.x,this.y,this.width,this.height].map(function(e){return Math.round(e)}),n=t[0],r=t[1],i=t[2],a=t[3];return new e({x:n,y:r,width:i,height:a})},e.prototype.floor=function(){var t=[this.x,this.y,this.width,this.height].map(function(e){return Math.floor(e)}),n=t[0],r=t[1],i=t[2],a=t[3];return new e({x:n,y:r,width:i,height:a})},e.prototype.toSquare=function(){var t=this,n=t.x,r=t.y,i=t.width,a=t.height,o=Math.abs(i-a);return i<a&&(n-=o/2,i+=o),a<i&&(r-=o/2,a+=o),new e({x:n,y:r,width:i,height:a})},e.prototype.rescale=function(t){var n=gp(t)?t.width:t,r=gp(t)?t.height:t;return new e({x:this.x*n,y:this.y*r,width:this.width*n,height:this.height*r})},e.prototype.pad=function(t,n){var r=[this.x-t/2,this.y-n/2,this.width+t,this.height+n],i=r[0],a=r[1],o=r[2],s=r[3];return new e({x:i,y:a,width:o,height:s})},e.prototype.clipAtImageBorders=function(t,n){var r=this,i=r.x,a=r.y,o=r.right,s=r.bottom,c=Math.max(i,0),l=Math.max(a,0),u=o-c,d=s-l;return new e({x:c,y:l,width:Math.min(u,t-c),height:Math.min(d,n-l)}).floor()},e.prototype.shift=function(t,n){var r=this,i=r.width,a=r.height;return new e({x:this.x+t,y:this.y+n,width:i,height:a})},e.prototype.padAtBorders=function(e,t){var n=this.width+1,r=this.height+1,i=1,a=1,o=n,s=r,c=this.left,l=this.top,u=this.right,d=this.bottom;return u>t&&(o=-u+t+n,u=t),d>e&&(s=-d+e+r,d=e),c<1&&(s=2-c,c=1),l<1&&(s=2-l,l=1),{dy:a,edy:s,dx:i,edx:o,y:l,ey:d,x:c,ex:u,w:n,h:r}},e.prototype.calibrate=function(t){return new e({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()},e}(),wp=function(e){Z(t,e);function t(t,n,r,i,a){return a===void 0&&(a=!1),e.call(this,{left:t,top:n,right:r,bottom:i},a)||this}return t}(Cp),Tp=function(){function e(e,t,n,r,i){this._imageDims=new cp(i.width,i.height),this._score=e,this._classScore=t,this._className=n,this._box=new Cp(r).rescale(this._imageDims)}return Object.defineProperty(e.prototype,`score`,{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`classScore`,{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`className`,{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`box`,{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageDims`,{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageWidth`,{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageHeight`,{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`relativeBox`,{get:function(){return new Cp(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),e.prototype.forSize=function(t,n){return new e(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})},e}(),Ep=function(e){Z(t,e);function t(t,n,r){return e.call(this,t,t,``,n,r)||this}return t.prototype.forSize=function(n,r){var i=e.prototype.forSize.call(this,n,r),a=i.score,o=i.relativeBox,s=i.imageDims;return new t(a,o,s)},t}(Tp);function Dp(e,t,n){n===void 0&&(n=!0);var r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top));return n?r/(e.area+t.area-r):r/Math.min(e.area,t.area)}function Op(e){var t=e.map(function(e){return e.x}),n=e.map(function(e){return e.y});return new wp(t.reduce(function(e,t){return t<e?t:e},1/0),n.reduce(function(e,t){return t<e?t:e},1/0),t.reduce(function(e,t){return e<t?t:e},0),n.reduce(function(e,t){return e<t?t:e},0))}function kp(e,t,n,r){r===void 0&&(r=!0);for(var i=t.map(function(e,t){return{score:e,boxIndex:t}}).sort(function(e,t){return e.score-t.score}).map(function(e){return e.boxIndex}),a=[],o=function(){var t=i.pop();a.push(t);for(var o=i,s=[],c=0;c<o.length;c++){var l=o[c],u=e[t],d=e[l];s.push(Dp(u,d,r))}i=i.filter(function(e,t){return s[t]<=n})};i.length>0;)o();return a}function Ap(e,t){return H(function(){var n=t[0],r=t[1],i=t[2];return il(e,Wn([zn(sp(e.shape.slice(0,3),[1]),n),zn(sp(e.shape.slice(0,3),[1]),r),zn(sp(e.shape.slice(0,3),[1]),i)],3))})}function jp(e,t){return t===void 0&&(t=!1),H(function(){var n=e.shape.slice(1),r=n[0],i=n[1];if(r===i)return e;var a=Math.abs(r-i),o=Math.round(a*(t?.5:1)),s=r>i?2:1,c=function(t){var n=e.shape.slice();return n[s]=t,zn(n,0)},l=c(o),u=a-l.shape[s];return Wn([t&&u?c(u):null,e,l].filter(function(e){return!!e}).map(function(e){return e.toFloat()}),s)})}function Mp(e){return 1/(1+Math.exp(-e))}var Np=function(e){Z(t,e);function t(t,n,r,i,a){return a===void 0&&(a=!1),e.call(this,{x:t,y:n,width:r,height:i},a)||this}return t}(Cp),Pp=.5,Fp=.43,Ip=.45,Lp=function(){function e(e,t,n){n===void 0&&(n=new Sp(0,0));var r=t.width,i=t.height;this._imgDims=new cp(r,i),this._shift=n,this._positions=e.map(function(e){return e.mul(new Sp(r,i)).add(n)})}return Object.defineProperty(e.prototype,`shift`,{get:function(){return new Sp(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageWidth`,{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageHeight`,{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`positions`,{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`relativePositions`,{get:function(){var e=this;return this._positions.map(function(t){return t.sub(e._shift).div(new Sp(e.imageWidth,e.imageHeight))})},enumerable:!0,configurable:!0}),e.prototype.forSize=function(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})},e.prototype.shiftBy=function(e,t){return new this.constructor(this.relativePositions,this._imgDims,new Sp(e,t))},e.prototype.shiftByPoint=function(e){return this.shiftBy(e.x,e.y)},e.prototype.align=function(e,t){if(t===void 0&&(t={}),e){var n=e instanceof Ep?e.box.floor():new Cp(e);return this.shiftBy(n.x,n.y).align(null,t)}var r=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t),i=r.useDlibAlignment,a=r.minBoxPadding;return i?this.alignDlib():this.alignMinBbox(a)},e.prototype.alignDlib=function(){var e=this.getRefPointsForAlignment(),t=e[0],n=e[1],r=e[2],i=function(e){return r.sub(e).magnitude()},a=(i(t)+i(n))/2,o=Math.floor(a/Ip),s=vp(e),c=Math.floor(Math.max(0,s.x-Pp*o)),l=Math.floor(Math.max(0,s.y-Fp*o));return new Np(c,l,Math.min(o,this.imageWidth+c),Math.min(o,this.imageHeight+l))},e.prototype.alignMinBbox=function(e){var t=Op(this.positions);return t.pad(t.width*e,t.height*e)},e.prototype.getRefPointsForAlignment=function(){throw Error(`getRefPointsForAlignment not implemented by base class`)},e}(),Rp=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getRefPointsForAlignment=function(){var e=this.positions;return[e[0],e[1],vp([e[3],e[4]])]},t}(Lp),zp=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getJawOutline=function(){return this.positions.slice(0,17)},t.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},t.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},t.prototype.getNose=function(){return this.positions.slice(27,36)},t.prototype.getLeftEye=function(){return this.positions.slice(36,42)},t.prototype.getRightEye=function(){return this.positions.slice(42,48)},t.prototype.getMouth=function(){return this.positions.slice(48,68)},t.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(vp)},t}(Lp),Bp=function(){function e(e,t){this._label=e,this._distance=t}return Object.defineProperty(e.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`distance`,{get:function(){return this._distance},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){return e===void 0&&(e=!0),``+this.label+(e?` (`+hp(this.distance)+`)`:``)},e}(),Vp=function(e){Z(t,e);function t(t,n){var r=e.call(this,t)||this;return r._label=n,r}return t.assertIsValidLabeledBox=function(e,t){if(Cp.assertIsValidBox(e,t),!bp(e.label))throw Error(t+` - expected property label (`+e.label+`) to be a number`)},Object.defineProperty(t.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),t}(Cp),Hp=function(){function e(e,t){if(typeof e!=`string`)throw Error(`LabeledFaceDescriptors - constructor expected label to be a string`);if(!Array.isArray(t)||t.some(function(e){return!(e instanceof Float32Array)}))throw Error(`LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array`);this._label=e,this._descriptors=t}return Object.defineProperty(e.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`descriptors`,{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),e.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map(function(e){return Array.from(e)})}},e.fromJSON=function(t){var n=t.descriptors.map(function(e){return new Float32Array(e)});return new e(t.label,n)},e}();(function(e){Z(t,e);function t(t,n,r,i){var a=e.call(this,t,n)||this;return a._score=r,a._classScore=i,a}return t.assertIsValidPredictedBox=function(e,t){if(Vp.assertIsValidLabeledBox(e,t),!xp(e.score)||!xp(e.classScore))throw Error(t+` - expected properties score (`+e.score+`) and (`+e.classScore+`) to be a number between [0, 1]`)},Object.defineProperty(t.prototype,`score`,{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`classScore`,{get:function(){return this._classScore},enumerable:!0,configurable:!0}),t})(Vp);function Up(e){return e.detection instanceof Ep}function Wp(e,t){return Object.assign({},e,{detection:t})}function Gp(){var e=window.fetch||function(){throw Error(`fetch - missing fetch implementation for browser environment`)};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement(`canvas`)},createImageElement:function(){return document.createElement(`img`)},fetch:e,readFile:function(){throw Error(`readFile - filesystem not available for browser environment`)}}}function Kp(e){var t=``;if(!e)try{e=s()}catch(e){t=e.toString()}return{readFile:e?function(t){return new Promise(function(n,r){e.readFile(t,function(e,t){return e?r(e):n(t)})})}:function(){throw Error(`readFile - failed to require fs in nodejs environment with error: `+t)}}}function qp(){var e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=function(){if(e)return new e;throw Error(`createCanvasElement - missing Canvas implementation for nodejs environment`)},r=function(){if(t)return new t;throw Error(`createImageElement - missing Image implementation for nodejs environment`)},i=global.fetch||function(){throw Error(`fetch - missing fetch implementation for nodejs environment`)},a=Kp();return op({Canvas:e||function(){function e(){}return e}(),CanvasRenderingContext2D:global.CanvasRenderingContext2D||function(){function e(){}return e}(),Image:t||function(){function e(){}return e}(),ImageData:global.ImageData||function(){function e(){}return e}(),Video:global.HTMLVideoElement||function(){function e(){}return e}(),createCanvasElement:n,createImageElement:r,fetch:i},a)}function Jp(){return typeof window==`object`&&typeof document<`u`&&typeof HTMLImageElement<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLVideoElement<`u`&&typeof ImageData<`u`&&typeof CanvasRenderingContext2D<`u`}function Yp(){return typeof global==`object`&&typeof require==`function`&&typeof module<`u`&&typeof process<`u`&&!!process.version}var Xp;function Zp(){if(!Xp)throw Error(`getEnv - environment is not defined, check isNodejs() and isBrowser()`);return Xp}function Qp(e){Xp=e}function $p(){Jp()&&Qp(Gp()),Yp()&&Qp(qp())}function em(e){if(Xp||$p(),!Xp)throw Error(`monkeyPatch - environment is not defined, check isNodejs() and isBrowser()`);var t=e.Canvas,n=t===void 0?Xp.Canvas:t,r=e.Image,i=r===void 0?Xp.Image:r;Xp.Canvas=n,Xp.Image=i,Xp.createCanvasElement=e.createCanvasElement||(function(){return new n}),Xp.createImageElement=e.createImageElement||(function(){return new i}),Xp.ImageData=e.ImageData||Xp.ImageData,Xp.Video=e.Video||Xp.Video,Xp.fetch=e.fetch||Xp.fetch,Xp.readFile=e.readFile||Xp.readFile}var tm={getEnv:Zp,setEnv:Qp,initialize:$p,createBrowserEnv:Gp,createFileSystem:Kp,createNodejsEnv:qp,monkeyPatch:em,isBrowser:Jp,isNodejs:Yp};$p();function nm(e){return!tm.isNodejs()&&typeof e==`string`?document.getElementById(e):e}function rm(e){var t=tm.getEnv(),n=t.Canvas;if(e instanceof t.CanvasRenderingContext2D)return e;var r=nm(e);if(!(r instanceof n))throw Error(`resolveContext2d - expected canvas to be of instance of Canvas`);var i=r.getContext(`2d`);if(!i)throw Error(`resolveContext2d - canvas 2d context is null`);return i}var im;(function(e){e.TOP_LEFT=`TOP_LEFT`,e.TOP_RIGHT=`TOP_RIGHT`,e.BOTTOM_LEFT=`BOTTOM_LEFT`,e.BOTTOM_RIGHT=`BOTTOM_RIGHT`})(im||={});var am=function(){function e(e){e===void 0&&(e={});var t=e.anchorPosition,n=e.backgroundColor,r=e.fontColor,i=e.fontSize,a=e.fontStyle,o=e.padding;this.anchorPosition=t||im.TOP_LEFT,this.backgroundColor=n||`rgba(0, 0, 0, 0.5)`,this.fontColor=r||`rgba(255, 255, 255, 1)`,this.fontSize=i||14,this.fontStyle=a||`Georgia`,this.padding=o||4}return e}(),om=function(){function e(t,n,r){r===void 0&&(r={}),this.text=typeof t==`string`?[t]:t instanceof e?t.text:t,this.anchor=n,this.options=new am(r)}return e.prototype.measureWidth=function(e){var t=this.options.padding;return this.text.map(function(t){return e.measureText(t).width}).reduce(function(e,t){return e<t?t:e},0)+2*t},e.prototype.measureHeight=function(){var e=this.options,t=e.fontSize,n=e.padding;return this.text.length*t+2*n},e.prototype.getUpperLeft=function(e,t){var n=this.options.anchorPosition,r=n===im.BOTTOM_RIGHT||n===im.TOP_RIGHT,i=n===im.BOTTOM_LEFT||n===im.BOTTOM_RIGHT,a=this.measureWidth(e),o=this.measureHeight(),s=r?this.anchor.x-a:this.anchor.x,c=i?this.anchor.y-o:this.anchor.y;if(t){var l=t.width,u=t.height;return{x:Math.max(Math.min(s,l-a),0),y:Math.max(Math.min(c,u-o),0)}}return{x:s,y:c}},e.prototype.draw=function(e){var t=nm(e),n=rm(t),r=this.options,i=r.backgroundColor,a=r.fontColor,o=r.fontSize,s=r.fontStyle,c=r.padding;n.font=o+`px `+s;var l=this.measureWidth(n),u=this.measureHeight();n.fillStyle=i;var d=this.getUpperLeft(n,t);n.fillRect(d.x,d.y,l,u),n.fillStyle=a,this.text.forEach(function(e,t){var r=c+d.x,i=c+d.y+(t+1)*o;n.fillText(e,r,i)})},e}(),sm=function(){function e(e){e===void 0&&(e={});var t=e.boxColor,n=e.lineWidth,r=e.label,i=e.drawLabelOptions;this.boxColor=t||`rgba(0, 0, 255, 1)`,this.lineWidth=n||2,this.label=r;var a={anchorPosition:im.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new am(Object.assign({},a,i))}return e}();(function(){function e(e,t){t===void 0&&(t={}),this.box=new Cp(e),this.options=new sm(t)}return e.prototype.draw=function(e){var t=rm(e),n=this.options,r=n.boxColor,i=n.lineWidth,a=this.box,o=a.x,s=a.y,c=a.width,l=a.height;t.strokeStyle=r,t.lineWidth=i,t.strokeRect(o,s,c,l);var u=this.options.label;u&&new om([u],{x:o-i/2,y:s},this.options.drawLabelOptions).draw(e)},e})();function cm(e){var t=tm.getEnv(),n=t.Image,r=t.Video;return e instanceof n&&e.complete||e instanceof r&&e.readyState>=3}function lm(e){return new Promise(function(t,n){if(e instanceof tm.getEnv().Canvas||cm(e))return t();function r(e){e.currentTarget&&(e.currentTarget.removeEventListener(`load`,r),e.currentTarget.removeEventListener(`error`,i),t(e))}function i(e){e.currentTarget&&(e.currentTarget.removeEventListener(`load`,r),e.currentTarget.removeEventListener(`error`,i),n(e))}e.addEventListener(`load`,r),e.addEventListener(`error`,i)})}function um(e){var t=tm.getEnv(),n=t.Image,r=t.Video;return e instanceof n?new cp(e.naturalWidth,e.naturalHeight):e instanceof r?new cp(e.videoWidth,e.videoHeight):new cp(e.width,e.height)}function dm(e){var t=e.width,n=e.height,r=tm.getEnv().createCanvasElement,i=r();return i.width=t,i.height=n,i}function fm(e,t){var n=tm.getEnv().ImageData;if(!(e instanceof n)&&!cm(e))throw Error(`createCanvasFromMedia - media has not finished loading yet`);var r=t||um(e),i=r.width,a=r.height,o=dm({width:i,height:a});return e instanceof n?rm(o).putImageData(e,0,0):rm(o).drawImage(e,0,0,i,a),o}function pm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a,o,s;return $(this,function(c){switch(c.label){case 0:return n=t||tm.getEnv().createCanvasElement(),r=e.shape.slice(fp(e)?1:0),i=r[0],a=r[1],o=r[2],s=H(function(){return e.as3D(i,a,o).toInt()}),[4,Bf.toPixels(s,n)];case 1:return c.sent(),s.dispose(),[2,n]}})})}function mm(e){var t=tm.getEnv(),n=t.Image,r=t.Canvas,i=t.Video;return e instanceof n||e instanceof r||e instanceof i}function hm(e,t,n){n===void 0&&(n=!1);var r=tm.getEnv(),i=r.Image,a=r.Canvas;if(!(e instanceof i||e instanceof a))throw Error(`imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement`);var o=um(e),s=t/Math.max(o.height,o.width),c=s*o.width,l=s*o.height,u=dm({width:t,height:t}),d=e instanceof a?e:fm(e),f=Math.abs(c-l)/2,p=n&&c<l?f:0,m=n&&l<c?f:0;return rm(u).drawImage(d,p,m,c,l),u}var gm=function(){function e(e,t){var n=this;if(t===void 0&&(t=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have `+e);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach(function(e,t){if(dp(e)){n._imageTensors[t]=e,n._inputDimensions[t]=e.shape;return}if(fp(e)){var r=e.shape[0];if(r!==1)throw Error(`NetInput - tf.Tensor4D with batchSize `+r+` passed, but not supported in input array`);n._imageTensors[t]=e,n._inputDimensions[t]=e.shape.slice(1);return}var i=e instanceof tm.getEnv().Canvas?e:fm(e);n._canvases[t]=i,n._inputDimensions[t]=[i.height,i.width,3]})}return Object.defineProperty(e.prototype,`imageTensors`,{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`canvases`,{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`isBatchInput`,{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`batchSize`,{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`inputDimensions`,{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`inputSize`,{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`reshapedInputDimensions`,{get:function(){var e=this;return yp(this.batchSize,0,1).map(function(t,n){return e.getReshapedInputDimensions(n)})},enumerable:!0,configurable:!0}),e.prototype.getInput=function(e){return this.canvases[e]||this.imageTensors[e]},e.prototype.getInputDimensions=function(e){return this._inputDimensions[e]},e.prototype.getInputHeight=function(e){return this._inputDimensions[e][0]},e.prototype.getInputWidth=function(e){return this._inputDimensions[e][1]},e.prototype.getReshapedInputDimensions=function(e){if(typeof this.inputSize!=`number`)throw Error(`getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet`);return _p({width:this.getInputWidth(e),height:this.getInputHeight(e)},this.inputSize)},e.prototype.toBatchTensor=function(e,t){var n=this;return t===void 0&&(t=!0),this._inputSize=e,H(function(){return jr(yp(n.batchSize,0,1).map(function(r){var i=n.getInput(r);if(i instanceof Ve){var a=fp(i)?i:i.expandDims();return a=jp(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=gd.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof tm.getEnv().Canvas)return Bf.fromPixels(hm(i,e,t));throw Error(`toBatchTensor - at batchIdx `+r+`, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have `+i)}).map(function(e){return e.toFloat()})).as4D(n.batchSize,e,e,3)})},e}();function _m(e){return Q(this,void 0,void 0,function(){var t,n,r;return $(this,function(i){switch(i.label){case 0:if(e instanceof gm)return[2,e];if(t=Array.isArray(e)?e:[e],!t.length)throw Error(`toNetInput - empty array passed as input`);return n=function(t){return Array.isArray(e)?` at input index `+t+`:`:``},r=t.map(nm),r.forEach(function(e,r){if(!mm(e)&&!dp(e)&&!fp(e))throw typeof t[r]==`string`?Error(`toNetInput -`+n(r)+` string passed, but could not resolve HTMLElement for element id `+t[r]):Error(`toNetInput -`+n(r)+` expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(fp(e)){var i=e.shape[0];if(i!==1)throw Error(`toNetInput -`+n(r)+` tf.Tensor4D with batchSize `+i+` passed, but not supported in input array`)}}),[4,Promise.all(r.map(function(e){return mm(e)&&lm(e)}))];case 1:return i.sent(),[2,new gm(r,Array.isArray(e))]}})})}function vm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c;return $(this,function(l){switch(l.label){case 0:return n=tm.getEnv().Canvas,r=e,e instanceof n?[3,5]:[4,_m(e)];case 1:if(i=l.sent(),i.batchSize>1)throw Error(`extractFaces - batchSize > 1 not supported`);return a=i.getInput(0),a instanceof n?(o=a,[3,4]):[3,2];case 2:return[4,pm(a)];case 3:o=l.sent(),l.label=4;case 4:r=o,l.label=5;case 5:return s=rm(r),c=t.map(function(e){return e instanceof Ep?e.forSize(r.width,r.height).box.floor():e}).map(function(e){return e.clipAtImageBorders(r.width,r.height)}),[2,c.map(function(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=dm({width:r,height:i});return rm(a).putImageData(s.getImageData(t,n,r,i),0,0),a})]}})})}function ym(e,t){return Q(this,void 0,void 0,function(){return $(this,function(n){if(!dp(e)&&!fp(e))throw Error(`extractFaceTensors - expected image tensor to be 3D or 4D`);if(fp(e)&&e.shape[0]>1)throw Error(`extractFaceTensors - batchSize > 1 not supported`);return[2,H(function(){var n=e.shape.slice(fp(e)?1:0),r=n[0],i=n[1],a=n[2];return t.map(function(e){return e instanceof Ep?e.forSize(i,r).box:e}).map(function(e){return e.clipAtImageBorders(i,r)}).map(function(t){var n=t.x,o=t.y,s=t.width,c=t.height;return tu(e.as3D(r,i,a),[o,n,0],[c,s,a])})})]})})}function bm(e,t){return Q(this,void 0,void 0,function(){var n,r;return $(this,function(i){switch(i.label){case 0:return n=tm.getEnv().fetch,[4,n(e,t)];case 1:if(r=i.sent(),!(r.status<400))throw Error(`failed to fetch: (`+r.status+`) `+r.statusText+`, from url: `+r.url);return[2,r]}})})}function xm(e){return Q(this,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,bm(e)];case 1:return[2,t.sent().json()]}})})}function Sm(e,t){var n=t+`-weights_manifest.json`;if(!e)return{modelBaseUri:``,manifestUri:n};if(e===`/`)return{modelBaseUri:`/`,manifestUri:`/`+n};var r=e.startsWith(`http://`)?`http://`:e.startsWith(`https://`)?`https://`:``;e=e.replace(r,``);var i=e.split(`/`).filter(function(e){return e}),a=e.endsWith(`.json`)?i[i.length-1]:n,o=r+(e.endsWith(`.json`)?i.slice(0,i.length-1):i).join(`/`);return o=e.startsWith(`/`)?`/`+o:o,{modelBaseUri:o,manifestUri:o===`/`?`/`+a:o+`/`+a}}function Cm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a;return $(this,function(o){switch(o.label){case 0:return n=Sm(e,t),r=n.manifestUri,i=n.modelBaseUri,[4,xm(r)];case 1:return a=o.sent(),[2,If.loadWeights(a,i)]}})})}var wm=function(){function e(e){this._name=e,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(e.prototype,`params`,{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`paramMappings`,{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`isLoaded`,{get:function(){return!!this.params},enumerable:!0,configurable:!0}),e.prototype.getParamFromPath=function(e){var t=this.traversePropertyPath(e);return t.obj[t.objProp]},e.prototype.reassignParamFromPath=function(e,t){var n=this.traversePropertyPath(e),r=n.obj,i=n.objProp;r[i].dispose(),r[i]=t},e.prototype.getParamList=function(){var e=this;return this._paramMappings.map(function(t){var n=t.paramPath;return{path:n,tensor:e.getParamFromPath(n)}})},e.prototype.getTrainableParams=function(){return this.getParamList().filter(function(e){return e.tensor instanceof qe})},e.prototype.getFrozenParams=function(){return this.getParamList().filter(function(e){return!(e.tensor instanceof qe)})},e.prototype.variable=function(){var e=this;this.getFrozenParams().forEach(function(t){var n=t.path,r=t.tensor;e.reassignParamFromPath(n,r.variable())})},e.prototype.freeze=function(){var e=this;this.getTrainableParams().forEach(function(t){var n=t.path,r=t.tensor,i=On(r.dataSync());r.dispose(),e.reassignParamFromPath(n,i)})},e.prototype.dispose=function(e){e===void 0&&(e=!0),this.getParamList().forEach(function(t){if(e&&t.tensor.isDisposed)throw Error(`param tensor has already been disposed for path `+t.path);t.tensor.dispose()}),this._params=void 0},e.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map(function(e){var t=e.tensor;return Array.from(t.dataSync())}).reduce(function(e,t){return e.concat(t)}))},e.prototype.load=function(e){return Q(this,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return e instanceof Float32Array?(this.extractWeights(e),[2]):[4,this.loadFromUri(e)];case 1:return t.sent(),[2]}})})},e.prototype.loadFromUri=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:if(e&&typeof e!=`string`)throw Error(this._name+`.loadFromUri - expected model uri`);return[4,Cm(e,this.getDefaultModelName())];case 1:return t=n.sent(),this.loadFromWeightMap(t),[2]}})})},e.prototype.loadFromDisk=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a,o,s,c,l,u;return $(this,function(d){switch(d.label){case 0:if(e&&typeof e!=`string`)throw Error(this._name+`.loadFromDisk - expected model file path`);return t=tm.getEnv().readFile,n=Sm(e,this.getDefaultModelName()),r=n.manifestUri,i=n.modelBaseUri,a=function(e){return Promise.all(e.map(function(e){return t(e).then(function(e){return e.buffer})}))},o=If.weightsLoaderFactory(a),l=(c=JSON).parse,[4,t(r)];case 1:return s=l.apply(c,[d.sent().toString()]),[4,o(s,i)];case 2:return u=d.sent(),this.loadFromWeightMap(u),[2]}})})},e.prototype.loadFromWeightMap=function(e){var t=this.extractParamsFromWeigthMap(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.extractWeights=function(e){var t=this.extractParams(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.traversePropertyPath=function(e){if(!this.params)throw Error(`traversePropertyPath - model has no loaded params`);var t=e.split(`/`).reduce(function(t,n){if(!t.nextObj.hasOwnProperty(n))throw Error(`traversePropertyPath - object does not have property `+n+`, for path `+e);return{obj:t.nextObj,objProp:n,nextObj:t.nextObj[n]}},{nextObj:this.params}),n=t.obj,r=t.objProp;if(!n||!r||!(n[r]instanceof Ve))throw Error(`traversePropertyPath - parameter is not a tensor, for path `+e);return{obj:n,objProp:r}},e}();function Tm(e,t,n){return H(function(){var r=Pl(e,t.depthwise_filter,t.pointwise_filter,n,`same`);return r=zc(r,t.bias),r})}function Em(e,t,n){return n===void 0&&(n=!1),H(function(){var r=vu(n?zc(Dl(e,t.conv0.filters,[2,2],`same`),t.conv0.bias):Tm(e,t.conv0,[2,2])),i=Tm(r,t.conv1,[1,1]);return vu(zc(r,zc(i,Tm(vu(zc(r,i)),t.conv2,[1,1]))))})}function Dm(e,t,n,r){return n===void 0&&(n=!1),r===void 0&&(r=!0),H(function(){var i=vu(n?zc(Dl(e,t.conv0.filters,r?[2,2]:[1,1],`same`),t.conv0.bias):Tm(e,t.conv0,r?[2,2]:[1,1])),a=Tm(i,t.conv1,[1,1]),o=Tm(vu(zc(i,a)),t.conv2,[1,1]);return vu(zc(i,zc(a,zc(o,Tm(vu(zc(i,zc(a,o))),t.conv3,[1,1])))))})}function Om(e,t,n,r){return n===void 0&&(n=`same`),r===void 0&&(r=!1),H(function(){var i=zc(Dl(e,t.filters,[1,1],n),t.bias);return r?vu(i):i})}function km(e,t){Object.keys(e).forEach(function(n){t.some(function(e){return e.originalPath===n})||e[n].dispose()})}function Am(e,t){return function(n,r,i,a){var o=Nn(e(n*r*i*i),[i,i,n,r]),s=An(e(r));return t.push({paramPath:a+`/filters`},{paramPath:a+`/bias`}),{filters:o,bias:s}}}function jm(e,t){return function(n,r,i){var a=jn(e(n*r),[n,r]),o=An(e(r));return t.push({paramPath:i+`/weights`},{paramPath:i+`/bias`}),{weights:a,bias:o}}}var Mm=function(){function e(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}return e}();function Nm(e,t){return function(n,r,i){var a=Nn(e(9*n),[3,3,n,1]),o=Nn(e(n*r),[1,1,n,r]),s=An(e(r));return t.push({paramPath:i+`/depthwise_filter`},{paramPath:i+`/pointwise_filter`},{paramPath:i+`/bias`}),new Mm(a,o,s)}}function Pm(e){return function(t){return new Mm(e(t+`/depthwise_filter`,4),e(t+`/pointwise_filter`,4),e(t+`/bias`,1))}}function Fm(e,t){return function(n,r,i){var a=e[n];if(!lp(a,r))throw Error(`expected weightMap[`+n+`] to be a Tensor`+r+`D, instead have `+a);return t.push({originalPath:n,paramPath:i||n}),a}}function Im(e){var t=e;function n(e){var n=t.slice(0,e);return t=t.slice(e),n}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}function Lm(e,t){var n=Am(e,t),r=Nm(e,t);function i(e,t,i,a){return a===void 0&&(a=!1),{conv0:a?n(e,t,3,i+`/conv0`):r(e,t,i+`/conv0`),conv1:r(t,t,i+`/conv1`),conv2:r(t,t,i+`/conv2`)}}function a(e,t,n,a){a===void 0&&(a=!1);var o=i(e,t,n,a);return{conv0:o.conv0,conv1:o.conv1,conv2:o.conv2,conv3:r(t,t,n+`/conv3`)}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function Rm(e){var t=[],n=Im(e),r=n.extractWeights,i=n.getRemainingWeights,a=Lm(r,t).extractDenseBlock4Params,o=a(3,32,`dense0`,!0),s=a(32,64,`dense1`),c=a(64,128,`dense2`),l=a(128,256,`dense3`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{dense0:o,dense1:s,dense2:c,dense3:l}}}function zm(e){return function(t){return{filters:e(t+`/filters`,4),bias:e(t+`/bias`,1)}}}function Bm(e,t){var n=Fm(e,t),r=zm(n),i=Pm(n);function a(e,t){return t===void 0&&(t=!1),{conv0:t?r(e+`/conv0`):i(e+`/conv0`),conv1:i(e+`/conv1`),conv2:i(e+`/conv2`)}}function o(e,t){return t===void 0&&(t=!1),{conv0:t?r(e+`/conv0`):i(e+`/conv0`),conv1:i(e+`/conv1`),conv2:i(e+`/conv2`),conv3:i(e+`/conv3`)}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:o}}function Vm(e){var t=[],n=Bm(e,t).extractDenseBlock4Params,r={dense0:n(`dense0`,!0),dense1:n(`dense1`),dense2:n(`dense2`),dense3:n(`dense3`)};return km(e,t),{params:r,paramMappings:t}}var Hm=function(e){Z(t,e);function t(){return e.call(this,`FaceFeatureExtractor`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`FaceFeatureExtractor - load model before inference`);return H(function(){var n=Dm(Ap(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(G(255)),t.dense0,!0);return n=Dm(n,t.dense1),n=Dm(n,t.dense2),n=Dm(n,t.dense3),n=Jl(n,[7,7],[2,2],`valid`),n})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`face_feature_extractor_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Vm(e)},t.prototype.extractParams=function(e){return Rm(e)},t}(wm);function Um(e,t){return H(function(){return zc(Ll(e,t.weights),t.bias)})}function Wm(e,t,n){var r=[],i=Im(e),a=i.extractWeights,o=i.getRemainingWeights,s=jm(a,r)(t,n,`fc`);if(o().length!==0)throw Error(`weights remaing after extract: `+o().length);return{paramMappings:r,params:{fc:s}}}function Gm(e){var t=[],n=Fm(e,t);function r(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}var i={fc:r(`fc`)};return km(e,t),{params:i,paramMappings:t}}function Km(e){var t={},n={};return Object.keys(e).forEach(function(r){var i=r.startsWith(`fc`)?n:t;i[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}var qm=function(e){Z(t,e);function t(t,n){var r=e.call(this,t)||this;return r._faceFeatureExtractor=n,r}return Object.defineProperty(t.prototype,`faceFeatureExtractor`,{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw Error(this._name+` - load model before inference`);return H(function(){var r=e instanceof gm?t.faceFeatureExtractor.forwardInput(e):e;return Um(r.as2D(r.shape[0],-1),n.fc)})},t.prototype.dispose=function(t){t===void 0&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return Wm(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},t.prototype.extractParamsFromWeigthMap=function(e){var t=Km(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),Gm(r)},t.prototype.extractParams=function(e){var t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,i=e.slice(0,e.length-r),a=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(a)},t}(wm),Jm=[`neutral`,`happy`,`sad`,`angry`,`fearful`,`disgusted`,`surprised`],Ym=function(){function e(e){var t=this;if(e.length!==7)throw Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: `+e.length);Jm.forEach(function(n,r){t[n]=e[r]})}return e.prototype.asSortedArray=function(){var e=this;return Jm.map(function(t){return{expression:t,probability:e[t]}}).sort(function(e,t){return t.probability-e.probability})},e}(),Xm=function(e){Z(t,e);function t(t){return t===void 0&&(t=new Hm),e.call(this,`FaceExpressionNet`,t)||this}return t.prototype.forwardInput=function(e){var t=this;return H(function(){return ni(t.runNet(e))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.predictExpressions=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a=this;return $(this,function(o){switch(o.label){case 0:return[4,_m(e)];case 1:return t=o.sent(),[4,this.forwardInput(t)];case 2:return n=o.sent(),[4,Promise.all(Pr(n).map(function(e){return Q(a,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return[4,e.data()];case 1:return t=n.sent(),e.dispose(),[2,t]}})})}))];case 3:return r=o.sent(),n.dispose(),i=r.map(function(e){return new Ym(e)}),[2,t.isBatchInput?i:i[0]]}})})},t.prototype.getDefaultModelName=function(){return`face_expression_model`},t.prototype.getClassifierChannelsIn=function(){return 256},t.prototype.getClassifierChannelsOut=function(){return 7},t}(qm);function Zm(e,t){return Object.assign({},e,{expressions:t})}function Qm(e){return Up(e)&&e.landmarks instanceof Lp&&e.unshiftedLandmarks instanceof Lp&&e.alignedRect instanceof Ep}function $m(e,t){var n=e.detection.box,r=t.shiftBy(n.x,n.y),i=r.align(),a=e.detection.imageDims,o={landmarks:r,unshiftedLandmarks:t,alignedRect:new Ep(e.detection.score,i.rescale(a.reverse()),a)};return Object.assign({},e,o)}var eh=function(){function e(e){e===void 0&&(e={});var t=e.drawLines,n=t===void 0?!0:t,r=e.drawPoints,i=r===void 0?!0:r,a=e.lineWidth,o=e.lineColor,s=e.pointSize,c=e.pointColor;this.drawLines=n,this.drawPoints=i,this.lineWidth=a||1,this.pointSize=s||2,this.lineColor=o||`rgba(0, 255, 255, 1)`,this.pointColor=c||`rgba(255, 0, 255, 1)`}return e}();(function(){function e(e,t){t===void 0&&(t={}),this.faceLandmarks=e,this.options=new eh(t)}return e.prototype.draw=function(e){var t=rm(e),n=this.options,r=n.drawLines,i=n.drawPoints,a=n.lineWidth,o=n.lineColor,s=n.pointSize,c=n.pointColor;r&&this.faceLandmarks instanceof zp&&(t.strokeStyle=o,t.lineWidth=a,ip(t,this.faceLandmarks.getJawOutline()),ip(t,this.faceLandmarks.getLeftEyeBrow()),ip(t,this.faceLandmarks.getRightEyeBrow()),ip(t,this.faceLandmarks.getNose()),ip(t,this.faceLandmarks.getLeftEye(),!0),ip(t,this.faceLandmarks.getRightEye(),!0),ip(t,this.faceLandmarks.getMouth(),!0)),i&&(t.strokeStyle=c,t.fillStyle=c,this.faceLandmarks.positions.forEach(function(e){t.beginPath(),t.arc(e.x,e.y,s,0,2*Math.PI),t.fill()}))},e})();function th(e,t){var n=Am(e,t),r=Nm(e,t);function i(e,t,i){return{separable_conv0:r(e,t,i+`/separable_conv0`),separable_conv1:r(t,t,i+`/separable_conv1`),expansion_conv:n(e,t,1,i+`/expansion_conv`)}}function a(e,t){return{separable_conv0:r(e,e,t+`/separable_conv0`),separable_conv1:r(e,e,t+`/separable_conv1`),separable_conv2:r(e,e,t+`/separable_conv2`)}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:i,extractMainBlockParams:a}}function nh(e,t){var n=[],r=Im(e),i=r.extractWeights,a=r.getRemainingWeights,o=th(i,n),s=o.extractConvParams,c=o.extractSeparableConvParams,l=o.extractReductionBlockParams,u=o.extractMainBlockParams,d={conv_in:s(3,32,3,`entry_flow/conv_in`),reduction_block_0:l(32,64,`entry_flow/reduction_block_0`),reduction_block_1:l(64,128,`entry_flow/reduction_block_1`)},f={};yp(t,0,1).forEach(function(e){f[`main_block_`+e]=u(128,`middle_flow/main_block_`+e)});var p={reduction_block:l(128,256,`exit_flow/reduction_block`),separable_conv:c(256,512,`exit_flow/separable_conv`)};if(a().length!==0)throw Error(`weights remaing after extract: `+a().length);return{paramMappings:n,params:{entry_flow:d,middle_flow:f,exit_flow:p}}}function rh(e,t){var n=Fm(e,t),r=zm(n),i=Pm(n);function a(e){return{separable_conv0:i(e+`/separable_conv0`),separable_conv1:i(e+`/separable_conv1`),expansion_conv:r(e+`/expansion_conv`)}}function o(e){return{separable_conv0:i(e+`/separable_conv0`),separable_conv1:i(e+`/separable_conv1`),separable_conv2:i(e+`/separable_conv2`)}}return{extractConvParams:r,extractSeparableConvParams:i,extractReductionBlockParams:a,extractMainBlockParams:o}}function ih(e,t){var n=[],r=rh(e,n),i=r.extractConvParams,a=r.extractSeparableConvParams,o=r.extractReductionBlockParams,s=r.extractMainBlockParams,c={conv_in:i(`entry_flow/conv_in`),reduction_block_0:o(`entry_flow/reduction_block_0`),reduction_block_1:o(`entry_flow/reduction_block_1`)},l={};yp(t,0,1).forEach(function(e){l[`main_block_`+e]=s(`middle_flow/main_block_`+e)});var u={reduction_block:o(`exit_flow/reduction_block`),separable_conv:a(`exit_flow/separable_conv`)};return km(e,n),{params:{entry_flow:c,middle_flow:l,exit_flow:u},paramMappings:n}}function ah(e,t,n){return zc(Dl(e,t.filters,n,`same`),t.bias)}function oh(e,t,n){n===void 0&&(n=!0);var r=n?vu(e):e;return r=Tm(r,t.separable_conv0,[1,1]),r=Tm(vu(r),t.separable_conv1,[1,1]),r=ql(r,[3,3],[2,2],`same`),r=zc(r,ah(e,t.expansion_conv,[2,2])),r}function sh(e,t){var n=Tm(vu(e),t.separable_conv0,[1,1]);return n=Tm(vu(n),t.separable_conv1,[1,1]),n=Tm(vu(n),t.separable_conv2,[1,1]),n=zc(n,e),n}var ch=function(e){Z(t,e);function t(t){var n=e.call(this,`TinyXception`)||this;return n._numMainBlocks=t,n}return t.prototype.forwardInput=function(e){var t=this,n=this.params;if(!n)throw Error(`TinyXception - load model before inference`);return H(function(){var r=vu(ah(Ap(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(G(256)),n.entry_flow.conv_in,[2,2]));return r=oh(r,n.entry_flow.reduction_block_0,!1),r=oh(r,n.entry_flow.reduction_block_1),yp(t._numMainBlocks,0,1).forEach(function(e){r=sh(r,n.middle_flow[`main_block_`+e])}),r=oh(r,n.exit_flow.reduction_block),r=vu(Tm(r,n.exit_flow.separable_conv,[1,1])),r})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`tiny_xception_model`},t.prototype.extractParamsFromWeigthMap=function(e){return ih(e,this._numMainBlocks)},t.prototype.extractParams=function(e){return nh(e,this._numMainBlocks)},t}(wm);function lh(e){var t=[],n=Im(e),r=n.extractWeights,i=n.getRemainingWeights,a=jm(r,t),o=a(512,1,`fc/age`),s=a(512,2,`fc/gender`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{fc:{age:o,gender:s}}}}function uh(e){var t=[],n=Fm(e,t);function r(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}var i={fc:{age:r(`fc/age`),gender:r(`fc/gender`)}};return km(e,t),{params:i,paramMappings:t}}var dh;(function(e){e.FEMALE=`female`,e.MALE=`male`})(dh||={});var fh=function(e){Z(t,e);function t(t){t===void 0&&(t=new ch(2));var n=e.call(this,`AgeGenderNet`)||this;return n._faceFeatureExtractor=t,n}return Object.defineProperty(t.prototype,`faceFeatureExtractor`,{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw Error(this._name+` - load model before inference`);return H(function(){var r=e instanceof gm?t.faceFeatureExtractor.forwardInput(e):e,i=Jl(r,[7,7],[2,2],`valid`).as2D(r.shape[0],-1);return{age:Um(i,n.fc.age).as1D(),gender:Um(i,n.fc.gender)}})},t.prototype.forwardInput=function(e){var t=this;return H(function(){var n=t.runNet(e),r=n.age,i=n.gender;return{age:r,gender:ni(i)}})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.predictAgeAndGender=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a,o,s=this;return $(this,function(c){switch(c.label){case 0:return[4,_m(e)];case 1:return t=c.sent(),[4,this.forwardInput(t)];case 2:return n=c.sent(),r=Pr(n.age),i=Pr(n.gender),a=r.map(function(e,t){return{ageTensor:e,genderTensor:i[t]}}),[4,Promise.all(a.map(function(e){var t=e.ageTensor,n=e.genderTensor;return Q(s,void 0,void 0,function(){var e,r,i,a,o;return $(this,function(s){switch(s.label){case 0:return[4,t.data()];case 1:return e=s.sent()[0],[4,n.data()];case 2:return r=s.sent()[0],i=r>.5,a=i?dh.MALE:dh.FEMALE,o=i?r:1-r,t.dispose(),n.dispose(),[2,{age:e,gender:a,genderProbability:o}]}})})}))];case 3:return o=c.sent(),n.age.dispose(),n.gender.dispose(),[2,t.isBatchInput?o:o[0]]}})})},t.prototype.getDefaultModelName=function(){return`age_gender_model`},t.prototype.dispose=function(t){t===void 0&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return lh(e)},t.prototype.extractParamsFromWeigthMap=function(e){var t=Km(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),uh(r)},t.prototype.extractParams=function(e){var t=1539,n=e.slice(0,e.length-t),r=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(r)},t}(wm),ph=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.postProcess=function(e,t,n){var r=n.map(function(e){var n=e.width,r=e.height,i=t/Math.max(r,n);return{width:n*i,height:r*i}}),i=r.length;return H(function(){var n=function(e,t){return jr([zn([68],e),zn([68],t)],1).as2D(1,136).as1D()},a=function(e,t){var n=r[e],i=n.width,a=n.height;return t(i,a)?Math.abs(i-a)/2:0},o=function(e){return a(e,function(e,t){return e<t})},s=function(e){return a(e,function(e,t){return t<e})};return e.mul(zn([i,136],t)).sub(jr(Array.from(Array(i),function(e,t){return n(o(t),s(t))}))).div(jr(Array.from(Array(i),function(e,t){return n(r[t].width,r[t].height)})))})},t.prototype.forwardInput=function(e){var t=this;return H(function(){var n=t.runNet(e);return t.postProcess(n,e.inputSize,e.inputDimensions.map(function(e){return{height:e[0],width:e[1]}}))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.detectLandmarks=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i=this;return $(this,function(a){switch(a.label){case 0:return[4,_m(e)];case 1:return t=a.sent(),n=H(function(){return Pr(i.forwardInput(t))}),[4,Promise.all(n.map(function(e,n){return Q(i,void 0,void 0,function(){var r,i,a,o,s;return $(this,function(c){switch(c.label){case 0:return a=(i=Array).from,[4,e.data()];case 1:return r=a.apply(i,[c.sent()]),o=r.filter(function(e,t){return mp(t)}),s=r.filter(function(e,t){return!mp(t)}),[2,new zp(Array(68).fill(0).map(function(e,t){return new Sp(o[t],s[t])}),{height:t.getInputHeight(n),width:t.getInputWidth(n)})]}})})}))];case 2:return r=a.sent(),n.forEach(function(e){return e.dispose()}),[2,t.isBatchInput?r:r[0]]}})})},t.prototype.getClassifierChannelsOut=function(){return 136},t}(qm),mh=function(e){Z(t,e);function t(t){return t===void 0&&(t=new Hm),e.call(this,`FaceLandmark68Net`,t)||this}return t.prototype.getDefaultModelName=function(){return`face_landmark_68_model`},t.prototype.getClassifierChannelsIn=function(){return 256},t}(ph);function hh(e){var t=[],n=Bm(e,t).extractDenseBlock3Params,r={dense0:n(`dense0`,!0),dense1:n(`dense1`),dense2:n(`dense2`)};return km(e,t),{params:r,paramMappings:t}}function gh(e){var t=[],n=Im(e),r=n.extractWeights,i=n.getRemainingWeights,a=Lm(r,t).extractDenseBlock3Params,o=a(3,32,`dense0`,!0),s=a(32,64,`dense1`),c=a(64,128,`dense2`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{dense0:o,dense1:s,dense2:c}}}var _h=function(e){Z(t,e);function t(){return e.call(this,`TinyFaceFeatureExtractor`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`TinyFaceFeatureExtractor - load model before inference`);return H(function(){var n=Em(Ap(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(G(255)),t.dense0,!0);return n=Em(n,t.dense1),n=Em(n,t.dense2),n=Jl(n,[14,14],[2,2],`valid`),n})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`face_feature_extractor_tiny_model`},t.prototype.extractParamsFromWeigthMap=function(e){return hh(e)},t.prototype.extractParams=function(e){return gh(e)},t}(wm),vh=function(e){Z(t,e);function t(t){return t===void 0&&(t=new _h),e.call(this,`FaceLandmark68TinyNet`,t)||this}return t.prototype.getDefaultModelName=function(){return`face_landmark_68_tiny_model`},t.prototype.getClassifierChannelsIn=function(){return 128},t}(ph);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(mh);function yh(e,t){return zc($c(e,t.weights),t.biases)}function bh(e,t,n,r,i){i===void 0&&(i=`same`);var a=t.conv,o=a.filters,s=a.bias,c=Dl(e,o,n,i);return c=zc(c,s),c=yh(c,t.scale),r?vu(c):c}function xh(e,t){return bh(e,t,[1,1],!0)}function Sh(e,t){return bh(e,t,[1,1],!1)}function Ch(e,t){return bh(e,t,[2,2],!0,`valid`)}function wh(e,t){function n(t,n,r){var i=e(t),a=i.length/(n*r*r);if(pp(a))throw Error(`depth has to be an integer: `+a+`, weights.length: `+i.length+`, numFilters: `+n+`, filterSize: `+r);return H(function(){return xu(Nn(i,[n,a,r,r]),[2,3,1,0])})}function r(r,i,a,o){var s=n(r,i,a),c=An(e(i));return t.push({paramPath:o+`/filters`},{paramPath:o+`/bias`}),{filters:s,bias:c}}function i(n,r){var i=An(e(n)),a=An(e(n));return t.push({paramPath:r+`/weights`},{paramPath:r+`/biases`}),{weights:i,biases:a}}function a(e,t,n,a){return{conv:r(e,t,n,a+`/conv`),scale:i(t,a+`/scale`)}}function o(e,t,n,r,i){return i===void 0&&(i=!1),{conv1:a((i?.5:1)*e,t,n,r+`/conv1`),conv2:a(e,t,n,r+`/conv2`)}}return{extractConvLayerParams:a,extractResidualLayerParams:o}}function Th(e){var t=Im(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],a=wh(n,i),o=a.extractConvLayerParams,s=a.extractResidualLayerParams,c=o(4704,32,7,`conv32_down`),l=s(9216,32,3,`conv32_1`),u=s(9216,32,3,`conv32_2`),d=s(9216,32,3,`conv32_3`),f=s(36864,64,3,`conv64_down`,!0),p=s(36864,64,3,`conv64_1`),m=s(36864,64,3,`conv64_2`),h=s(36864,64,3,`conv64_3`),g=s(147456,128,3,`conv128_down`,!0),_=s(147456,128,3,`conv128_1`),v=s(147456,128,3,`conv128_2`),y=s(589824,256,3,`conv256_down`,!0),b=s(589824,256,3,`conv256_1`),x=s(589824,256,3,`conv256_2`),S=s(589824,256,3,`conv256_down_out`),C=H(function(){return xu(jn(n(256*128),[128,256]),[1,0])});if(i.push({paramPath:`fc`}),r().length!==0)throw Error(`weights remaing after extract: `+r().length);return{params:{conv32_down:c,conv32_1:l,conv32_2:u,conv32_3:d,conv64_down:f,conv64_1:p,conv64_2:m,conv64_3:h,conv128_down:g,conv128_1:_,conv128_2:v,conv256_down:y,conv256_1:b,conv256_2:x,conv256_down_out:S,fc:C},paramMappings:i}}function Eh(e,t){var n=Fm(e,t);function r(e){return{weights:n(e+`/scale/weights`,1),biases:n(e+`/scale/biases`,1)}}function i(e){var t=n(e+`/conv/filters`,4),i=n(e+`/conv/bias`,1),a=r(e);return{conv:{filters:t,bias:i},scale:a}}function a(e){return{conv1:i(e+`/conv1`),conv2:i(e+`/conv2`)}}return{extractConvLayerParams:i,extractResidualLayerParams:a}}function Dh(e){var t=[],n=Eh(e,t),r=n.extractConvLayerParams,i=n.extractResidualLayerParams,a=r(`conv32_down`),o=i(`conv32_1`),s=i(`conv32_2`),c=i(`conv32_3`),l=i(`conv64_down`),u=i(`conv64_1`),d=i(`conv64_2`),f=i(`conv64_3`),p=i(`conv128_down`),m=i(`conv128_1`),h=i(`conv128_2`),g=i(`conv256_down`),_=i(`conv256_1`),v=i(`conv256_2`),y=i(`conv256_down_out`),b=e.fc;if(t.push({originalPath:`fc`,paramPath:`fc`}),!up(b))throw Error(`expected weightMap[fc] to be a Tensor2D, instead have `+b);var x={conv32_down:a,conv32_1:o,conv32_2:s,conv32_3:c,conv64_down:l,conv64_1:u,conv64_2:d,conv64_3:f,conv128_down:p,conv128_1:m,conv128_2:h,conv256_down:g,conv256_1:_,conv256_2:v,conv256_down_out:y,fc:b};return km(e,t),{params:x,paramMappings:t}}function Oh(e,t){var n=xh(e,t.conv1);return n=Sh(n,t.conv2),n=zc(n,e),n=vu(n),n}function kh(e,t){var n=Ch(e,t.conv1);n=Sh(n,t.conv2);var r=Jl(e,2,2,`valid`),i=Rn(r.shape),a=r.shape[3]!==n.shape[3];if(r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2]){var o=sp(n.shape);o[1]=1;var s=Rn(o);n=Wn([n,s],1);var c=sp(n.shape);c[2]=1;var l=Rn(c);n=Wn([n,l],2)}return r=a?Wn([r,i],3):r,n=zc(r,n),n=vu(n),n}var Ah=function(e){Z(t,e);function t(){return e.call(this,`FaceRecognitionNet`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`FaceRecognitionNet - load model before inference`);return H(function(){var n=Ch(Ap(e.toBatchTensor(150,!0).toFloat(),[122.782,117.001,104.298]).div(G(256)),t.conv32_down);return n=ql(n,3,2,`valid`),n=Oh(n,t.conv32_1),n=Oh(n,t.conv32_2),n=Oh(n,t.conv32_3),n=kh(n,t.conv64_down),n=Oh(n,t.conv64_1),n=Oh(n,t.conv64_2),n=Oh(n,t.conv64_3),n=kh(n,t.conv128_down),n=Oh(n,t.conv128_1),n=Oh(n,t.conv128_2),n=kh(n,t.conv256_down),n=Oh(n,t.conv256_1),n=Oh(n,t.conv256_2),n=kh(n,t.conv256_down_out),Ll(n.mean([1,2]),t.fc)})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.computeFaceDescriptor=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i=this;return $(this,function(a){switch(a.label){case 0:return[4,_m(e)];case 1:return t=a.sent(),n=H(function(){return Pr(i.forwardInput(t))}),[4,Promise.all(n.map(function(e){return e.data()}))];case 2:return r=a.sent(),n.forEach(function(e){return e.dispose()}),[2,t.isBatchInput?r:r[0]]}})})},t.prototype.getDefaultModelName=function(){return`face_recognition_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Dh(e)},t.prototype.extractParams=function(e){return Th(e)},t}(wm);function jh(e,t){return Object.assign({},e,{descriptor:t})}function Mh(e,t){return Object.assign({},e,{age:t})}function Nh(e,t,n){return Object.assign({},e,{gender:t,genderProbability:n})}var Ph=function(){function e(e){var t=e===void 0?{}:e,n=t.minFaceSize,r=t.scaleFactor,i=t.maxNumScales,a=t.scoreThresholds,o=t.scaleSteps;if(this._name=`MtcnnOptions`,this._minFaceSize=n||20,this._scaleFactor=r||.709,this._maxNumScales=i||10,this._scoreThresholds=a||[.6,.7,.7],this._scaleSteps=o,typeof this._minFaceSize!=`number`||this._minFaceSize<0)throw Error(this._name+` - expected minFaceSize to be a number > 0`);if(typeof this._scaleFactor!=`number`||this._scaleFactor<=0||this._scaleFactor>=1)throw Error(this._name+` - expected scaleFactor to be a number between 0 and 1`);if(typeof this._maxNumScales!=`number`||this._maxNumScales<0)throw Error(this._name+` - expected maxNumScales to be a number > 0`);if(!Array.isArray(this._scoreThresholds)||this._scoreThresholds.length!==3||this._scoreThresholds.some(function(e){return typeof e!=`number`}))throw Error(this._name+` - expected scoreThresholds to be an array of numbers of length 3`);if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some(function(e){return typeof e!=`number`})))throw Error(this._name+` - expected scaleSteps to be an array of numbers`)}return Object.defineProperty(e.prototype,`minFaceSize`,{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scaleFactor`,{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`maxNumScales`,{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scoreThresholds`,{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scaleSteps`,{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),e}();function Fh(e,t){function n(n,r){var i=Nn(e(9*n),[3,3,n,1]),a=An(e(n)),o=An(e(n)),s=An(e(n)),c=An(e(n));return t.push({paramPath:r+`/filters`},{paramPath:r+`/batch_norm_scale`},{paramPath:r+`/batch_norm_offset`},{paramPath:r+`/batch_norm_mean`},{paramPath:r+`/batch_norm_variance`}),{filters:i,batch_norm_scale:a,batch_norm_offset:o,batch_norm_mean:s,batch_norm_variance:c}}function r(n,r,i,a,o){var s=Nn(e(n*r*i*i),[i,i,n,r]),c=An(e(r));return t.push({paramPath:a+`/filters`},{paramPath:a+`/`+(o?`batch_norm_offset`:`bias`)}),{filters:s,bias:c}}function i(e,t,n,i){var a=r(e,t,n,i,!0);return{filters:a.filters,batch_norm_offset:a.bias}}function a(e,t,r){return{depthwise_conv:n(e,r+`/depthwise_conv`),pointwise_conv:i(e,t,1,r+`/pointwise_conv`)}}function o(){return{conv_0:i(3,32,3,`mobilenetv1/conv_0`),conv_1:a(32,64,`mobilenetv1/conv_1`),conv_2:a(64,128,`mobilenetv1/conv_2`),conv_3:a(128,128,`mobilenetv1/conv_3`),conv_4:a(128,256,`mobilenetv1/conv_4`),conv_5:a(256,256,`mobilenetv1/conv_5`),conv_6:a(256,512,`mobilenetv1/conv_6`),conv_7:a(512,512,`mobilenetv1/conv_7`),conv_8:a(512,512,`mobilenetv1/conv_8`),conv_9:a(512,512,`mobilenetv1/conv_9`),conv_10:a(512,512,`mobilenetv1/conv_10`),conv_11:a(512,512,`mobilenetv1/conv_11`),conv_12:a(512,1024,`mobilenetv1/conv_12`),conv_13:a(1024,1024,`mobilenetv1/conv_13`)}}function s(){var e=i(1024,256,1,`prediction_layer/conv_0`),t=i(256,512,3,`prediction_layer/conv_1`),n=i(512,128,1,`prediction_layer/conv_2`),a=i(128,256,3,`prediction_layer/conv_3`),o=i(256,128,1,`prediction_layer/conv_4`),s=i(128,256,3,`prediction_layer/conv_5`),c=i(256,64,1,`prediction_layer/conv_6`),l=i(64,128,3,`prediction_layer/conv_7`),u=r(512,12,1,`prediction_layer/box_predictor_0/box_encoding_predictor`),d=r(512,9,1,`prediction_layer/box_predictor_0/class_predictor`),f=r(1024,24,1,`prediction_layer/box_predictor_1/box_encoding_predictor`),p=r(1024,18,1,`prediction_layer/box_predictor_1/class_predictor`),m=r(512,24,1,`prediction_layer/box_predictor_2/box_encoding_predictor`),h=r(512,18,1,`prediction_layer/box_predictor_2/class_predictor`),g=r(256,24,1,`prediction_layer/box_predictor_3/box_encoding_predictor`),_=r(256,18,1,`prediction_layer/box_predictor_3/class_predictor`),v=r(256,24,1,`prediction_layer/box_predictor_4/box_encoding_predictor`),y=r(256,18,1,`prediction_layer/box_predictor_4/class_predictor`),b=r(128,24,1,`prediction_layer/box_predictor_5/box_encoding_predictor`),x=r(128,18,1,`prediction_layer/box_predictor_5/class_predictor`);return{conv_0:e,conv_1:t,conv_2:n,conv_3:a,conv_4:o,conv_5:s,conv_6:c,conv_7:l,box_predictor_0:{box_encoding_predictor:u,class_predictor:d},box_predictor_1:{box_encoding_predictor:f,class_predictor:p},box_predictor_2:{box_encoding_predictor:m,class_predictor:h},box_predictor_3:{box_encoding_predictor:g,class_predictor:_},box_predictor_4:{box_encoding_predictor:v,class_predictor:y},box_predictor_5:{box_encoding_predictor:b,class_predictor:x}}}return{extractMobilenetV1Params:o,extractPredictionLayerParams:s}}function Ih(e){var t=[],n=Im(e),r=n.extractWeights,i=n.getRemainingWeights,a=Fh(r,t),o=a.extractMobilenetV1Params,s=a.extractPredictionLayerParams,c=o(),l=s(),u={extra_dim:Mn(r(5118*4),[1,5118,4])};if(t.push({paramPath:`output_layer/extra_dim`}),i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{params:{mobilenetv1:c,prediction_layer:l,output_layer:u},paramMappings:t}}function Lh(e,t){var n=Fm(e,t);function r(e,t,r){return{filters:n(e+`/Conv2d_`+t+`_pointwise/weights`,4,r+`/filters`),batch_norm_offset:n(e+`/Conv2d_`+t+`_pointwise/convolution_bn_offset`,1,r+`/batch_norm_offset`)}}function i(e){var t=`mobilenetv1/conv_`+e,i=`MobilenetV1/Conv2d_`+e+`_depthwise`,a=t+`/depthwise_conv`,o=t+`/pointwise_conv`;return{depthwise_conv:{filters:n(i+`/depthwise_weights`,4,a+`/filters`),batch_norm_scale:n(i+`/BatchNorm/gamma`,1,a+`/batch_norm_scale`),batch_norm_offset:n(i+`/BatchNorm/beta`,1,a+`/batch_norm_offset`),batch_norm_mean:n(i+`/BatchNorm/moving_mean`,1,a+`/batch_norm_mean`),batch_norm_variance:n(i+`/BatchNorm/moving_variance`,1,a+`/batch_norm_variance`)},pointwise_conv:r(`MobilenetV1`,e,o)}}function a(){return{conv_0:r(`MobilenetV1`,0,`mobilenetv1/conv_0`),conv_1:i(1),conv_2:i(2),conv_3:i(3),conv_4:i(4),conv_5:i(5),conv_6:i(6),conv_7:i(7),conv_8:i(8),conv_9:i(9),conv_10:i(10),conv_11:i(11),conv_12:i(12),conv_13:i(13)}}function o(e,t){return{filters:n(e+`/weights`,4,t+`/filters`),bias:n(e+`/biases`,1,t+`/bias`)}}function s(e){return{box_encoding_predictor:o(`Prediction/BoxPredictor_`+e+`/BoxEncodingPredictor`,`prediction_layer/box_predictor_`+e+`/box_encoding_predictor`),class_predictor:o(`Prediction/BoxPredictor_`+e+`/ClassPredictor`,`prediction_layer/box_predictor_`+e+`/class_predictor`)}}function c(){return{conv_0:r(`Prediction`,0,`prediction_layer/conv_0`),conv_1:r(`Prediction`,1,`prediction_layer/conv_1`),conv_2:r(`Prediction`,2,`prediction_layer/conv_2`),conv_3:r(`Prediction`,3,`prediction_layer/conv_3`),conv_4:r(`Prediction`,4,`prediction_layer/conv_4`),conv_5:r(`Prediction`,5,`prediction_layer/conv_5`),conv_6:r(`Prediction`,6,`prediction_layer/conv_6`),conv_7:r(`Prediction`,7,`prediction_layer/conv_7`),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:c}}function Rh(e){var t=[],n=Lh(e,t),r=n.extractMobilenetV1Params,i=n.extractPredictionLayerParams,a=e[`Output/extra_dim`];if(t.push({originalPath:`Output/extra_dim`,paramPath:`output_layer/extra_dim`}),!dp(a))throw Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have `+a);var o={mobilenetv1:r(),prediction_layer:i(),output_layer:{extra_dim:a}};return km(e,t),{params:o,paramMappings:t}}function zh(e,t,n){return H(function(){var r=Dl(e,t.filters,n,`same`);return r=zc(r,t.batch_norm_offset),qs(r,0,6)})}var Bh=.0010000000474974513;function Vh(e,t,n){return H(function(){var r=jl(e,t.filters,n,`same`);return r=kc(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Bh),qs(r,0,6)})}function Hh(e){return[2,4,6,12].some(function(t){return t===e})?[2,2]:[1,1]}function Uh(e,t){return H(function(){var n=null,r=zh(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach(function(e,t){var i=t+1,a=Hh(i);r=Vh(r,e.depthwise_conv,a),r=zh(r,e.pointwise_conv,[1,1]),i===11&&(n=r)}),n===null)throw Error(`mobileNetV1 - output of conv layer 11 is null`);return{out:r,conv11:n}})}function Wh(e,t,n,r,i){var a=e.shape[0],o=Math.min(n,a),s=t.map(function(e,t){return{score:e,boxIndex:t}}).filter(function(e){return e.score>i}).sort(function(e,t){return t.score-e.score}),c=function(e){return e<=r?1:0},l=[];return s.forEach(function(t){if(!(l.length>=o)){for(var n=t.score,r=l.length-1;r>=0;--r){var a=Gh(e,t.boxIndex,l[r]);if(a!==0&&(t.score*=c(a),t.score<=i))break}n===t.score&&l.push(t.boxIndex)}}),l}function Gh(e,t,n){var r=e.arraySync(),i=Math.min(r[t][0],r[t][2]),a=Math.min(r[t][1],r[t][3]),o=Math.max(r[t][0],r[t][2]),s=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),l=Math.min(r[n][1],r[n][3]),u=Math.max(r[n][0],r[n][2]),d=Math.max(r[n][1],r[n][3]),f=(o-i)*(s-a),p=(u-c)*(d-l);if(f<=0||p<=0)return 0;var m=Math.max(i,c),h=Math.max(a,l),g=Math.min(o,u),_=Math.min(s,d),v=Math.max(g-m,0)*Math.max(_-h,0);return v/(f+p-v)}function Kh(e){var t=Pr(xu(e,[1,0])),n=[il(t[2],t[0]),il(t[3],t[1])];return{sizes:n,centers:[zc(t[0],Uc(n[0],G(2))),zc(t[1],Uc(n[1],G(2)))]}}function qh(e,t){var n=Kh(e),r=n.sizes,i=n.centers,a=Pr(xu(t,[1,0])),o=Uc($c(Zs(Uc(a[2],G(5))),r[0]),G(2)),s=zc($c(Uc(a[0],G(10)),r[0]),i[0]),c=Uc($c(Zs(Uc(a[3],G(5))),r[1]),G(2)),l=zc($c(Uc(a[1],G(10)),r[1]),i[1]);return xu(jr([il(s,o),il(l,c),zc(s,o),zc(l,c)]),[1,0])}function Jh(e,t,n){return H(function(){var r=e.shape[0],i=qh(Or(Mr(n.extra_dim,[r,1,1]),[-1,4]),Or(e,[-1,4]));i=Or(i,[r,i.shape[0]/r,4]);var a=Ql(sc(Ql(t,[0,0,1],[-1,-1,-1])),[0,0,0],[-1,-1,1]);return a=Or(a,[r,a.shape[1]]),{boxes:Pr(i),scores:Pr(a)}})}function Yh(e,t){return H(function(){var n=e.shape[0];return{boxPredictionEncoding:Or(Om(e,t.box_encoding_predictor),[n,-1,1,4]),classPrediction:Or(Om(e,t.class_predictor),[n,-1,3])}})}function Xh(e,t,n){return H(function(){var r=zh(zh(e,n.conv_0,[1,1]),n.conv_1,[2,2]),i=zh(zh(r,n.conv_2,[1,1]),n.conv_3,[2,2]),a=zh(zh(i,n.conv_4,[1,1]),n.conv_5,[2,2]),o=zh(zh(a,n.conv_6,[1,1]),n.conv_7,[2,2]),s=Yh(t,n.box_predictor_0),c=Yh(e,n.box_predictor_1),l=Yh(r,n.box_predictor_2),u=Yh(i,n.box_predictor_3),d=Yh(a,n.box_predictor_4),f=Yh(o,n.box_predictor_5);return{boxPredictions:Wn([s.boxPredictionEncoding,c.boxPredictionEncoding,l.boxPredictionEncoding,u.boxPredictionEncoding,d.boxPredictionEncoding,f.boxPredictionEncoding],1),classPredictions:Wn([s.classPrediction,c.classPrediction,l.classPrediction,u.classPrediction,d.classPrediction,f.classPrediction],1)}})}var Zh=function(){function e(e){var t=e===void 0?{}:e,n=t.minConfidence,r=t.maxResults;if(this._name=`SsdMobilenetv1Options`,this._minConfidence=n||.5,this._maxResults=r||100,typeof this._minConfidence!=`number`||this._minConfidence<=0||this._minConfidence>=1)throw Error(this._name+` - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!=`number`)throw Error(this._name+` - expected maxResults to be a number`)}return Object.defineProperty(e.prototype,`minConfidence`,{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`maxResults`,{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),e}(),Qh=function(e){Z(t,e);function t(){return e.call(this,`SsdMobilenetv1`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`SsdMobilenetv1 - load model before inference`);return H(function(){var n=Uh(il($c(e.toBatchTensor(512,!1).toFloat(),G(.007843137718737125)),G(1)),t.mobilenetv1),r=Xh(n.out,n.conv11,t.prediction_layer),i=r.boxPredictions,a=r.classPredictions;return Jh(i,a,t.output_layer)})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,_m(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.locateFaces=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S;return $(this,function(C){switch(C.label){case 0:return n=new Zh(t),r=n.maxResults,i=n.minConfidence,[4,_m(e)];case 1:for(a=C.sent(),o=this.forwardInput(a),s=o.boxes,c=o.scores,l=s[0],u=c[0],d=1;d<s.length;d++)s[d].dispose(),c[d].dispose();return m=(p=Array).from,[4,u.data()];case 2:return f=m.apply(p,[C.sent()]),h=.5,g=Wh(l,f,r,h,i),_=a.getReshapedInputDimensions(0),v=a.inputSize,y=v/_.width,b=v/_.height,x=l.arraySync(),S=g.map(function(e){var t=[Math.max(0,x[e][0]),Math.min(1,x[e][2])].map(function(e){return e*b}),n=t[0],r=t[1],i=[Math.max(0,x[e][1]),Math.min(1,x[e][3])].map(function(e){return e*y}),o=i[0],s=i[1];return new Ep(f[e],new Np(o,n,s-o,r-n),{height:a.getInputHeight(0),width:a.getInputWidth(0)})}),l.dispose(),u.dispose(),[2,S]}})})},t.prototype.getDefaultModelName=function(){return`ssd_mobilenetv1_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Rh(e)},t.prototype.extractParams=function(e){return Ih(e)},t}(wm);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Qh);var $h=.4,eg=[new Sp(.738768,.874946),new Sp(2.42204,2.65704),new Sp(4.30971,7.04493),new Sp(10.246,4.59428),new Sp(12.6868,11.8741)],tg=[new Sp(1.603231,2.094468),new Sp(6.041143,7.080126),new Sp(2.882459,3.518061),new Sp(4.266906,5.178857),new Sp(9.041765,10.66308)],ng=[117.001,114.697,97.404],rg=`tiny_yolov2_model`,ig=`tiny_yolov2_separable_conv_model`,ag=function(e){return typeof e==`number`};function og(e){if(!e)throw Error(`invalid config: `+e);if(typeof e.withSeparableConvs!=`boolean`)throw Error(`config.withSeparableConvs has to be a boolean, have: `+e.withSeparableConvs);if(!ag(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw Error(`config.iouThreshold has to be a number between [0, 1], have: `+e.iouThreshold);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(function(e){return typeof e==`string`}))throw Error(`config.classes has to be an array class names: string[], have: `+JSON.stringify(e.classes));if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(function(e){return e||{}}).every(function(e){return ag(e.x)&&ag(e.y)}))throw Error(`config.anchors has to be an array of { x: number, y: number }, have: `+JSON.stringify(e.anchors));if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(ag)))throw Error(`config.meanRgb has to be an array of shape [number, number, number], have: `+JSON.stringify(e.meanRgb))}function sg(e){return H(function(){var t=$c(e,G(.10000000149011612));return zc(vu(il(e,t)),t)})}function cg(e,t){return H(function(){var n=yr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Dl(n,t.conv.filters,[1,1],`valid`),n=il(n,t.bn.sub),n=$c(n,t.bn.truediv),n=zc(n,t.conv.bias),sg(n)})}function lg(e,t){return H(function(){var n=yr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Pl(n,t.depthwise_filter,t.pointwise_filter,[1,1],`valid`),n=zc(n,t.bias),sg(n)})}function ug(e,t){var n=Am(e,t);function r(n,r){var i=An(e(n)),a=An(e(n));return t.push({paramPath:r+`/sub`},{paramPath:r+`/truediv`}),{sub:i,truediv:a}}function i(e,t,i){return{conv:n(e,t,3,i+`/conv`),bn:r(t,i+`/bn`)}}return{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:Nm(e,t)}}function dg(e,t,n,r){var i=Im(e),a=i.extractWeights,o=i.getRemainingWeights,s=[],c=ug(a,s),l=c.extractConvParams,u=c.extractConvWithBatchNormParams,d=c.extractSeparableConvParams,f;if(t.withSeparableConvs){var p=r[0],m=r[1],h=r[2],g=r[3],_=r[4],v=r[5],y=r[6],b=r[7],x=r[8],S=t.isFirstLayerConv2d?l(p,m,3,`conv0`):d(p,m,`conv0`),C=d(m,h,`conv1`),w=d(h,g,`conv2`),T=d(g,_,`conv3`),E=d(_,v,`conv4`),D=d(v,y,`conv5`),O=b?d(y,b,`conv6`):void 0,k=x?d(b,x,`conv7`):void 0,A=l(x||b||y,5*n,1,`conv8`);f={conv0:S,conv1:C,conv2:w,conv3:T,conv4:E,conv5:D,conv6:O,conv7:k,conv8:A}}else{var p=r[0],m=r[1],h=r[2],g=r[3],_=r[4],v=r[5],y=r[6],b=r[7],x=r[8],S=u(p,m,`conv0`),C=u(m,h,`conv1`),w=u(h,g,`conv2`),T=u(g,_,`conv3`),E=u(_,v,`conv4`),D=u(v,y,`conv5`),O=u(y,b,`conv6`),k=u(b,x,`conv7`),A=l(x,5*n,1,`conv8`);f={conv0:S,conv1:C,conv2:w,conv3:T,conv4:E,conv5:D,conv6:O,conv7:k,conv8:A}}if(o().length!==0)throw Error(`weights remaing after extract: `+o().length);return{params:f,paramMappings:s}}function fg(e,t){var n=Fm(e,t);function r(e){return{sub:n(e+`/sub`,1),truediv:n(e+`/truediv`,1)}}function i(e){return{filters:n(e+`/filters`,4),bias:n(e+`/bias`,1)}}function a(e){return{conv:i(e+`/conv`),bn:r(e+`/bn`)}}return{extractConvParams:i,extractConvWithBatchNormParams:a,extractSeparableConvParams:Pm(n)}}function pg(e,t){var n=[],r=fg(e,n),i=r.extractConvParams,a=r.extractConvWithBatchNormParams,o=r.extractSeparableConvParams,s;if(t.withSeparableConvs){var c=t.filterSizes&&t.filterSizes.length||9;s={conv0:t.isFirstLayerConv2d?i(`conv0`):o(`conv0`),conv1:o(`conv1`),conv2:o(`conv2`),conv3:o(`conv3`),conv4:o(`conv4`),conv5:o(`conv5`),conv6:c>7?o(`conv6`):void 0,conv7:c>8?o(`conv7`):void 0,conv8:i(`conv8`)}}else s={conv0:a(`conv0`),conv1:a(`conv1`),conv2:a(`conv2`),conv3:a(`conv3`),conv4:a(`conv4`),conv5:a(`conv5`),conv6:a(`conv6`),conv7:a(`conv7`),conv8:i(`conv8`)};return km(e,n),{params:s,paramMappings:n}}var mg;(function(e){e[e.XS=224]=`XS`,e[e.SM=320]=`SM`,e[e.MD=416]=`MD`,e[e.LG=608]=`LG`})(mg||={});var hg=function(){function e(e){var t=e===void 0?{}:e,n=t.inputSize,r=t.scoreThreshold;if(this._name=`TinyYolov2Options`,this._inputSize=n||416,this._scoreThreshold=r||.5,typeof this._inputSize!=`number`||this._inputSize%32!=0)throw Error(this._name+` - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!=`number`||this._scoreThreshold<=0||this._scoreThreshold>=1)throw Error(this._name+` - expected scoreThreshold to be a number between 0 and 1`)}return Object.defineProperty(e.prototype,`inputSize`,{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scoreThreshold`,{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),e}(),gg=function(e){Z(t,e);function t(t){var n=e.call(this,`TinyYolov2`)||this;return og(t),n._config=t,n}return Object.defineProperty(t.prototype,`config`,{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`withClassScores`,{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`boxEncodingSize`,{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),t.prototype.runTinyYolov2=function(e,t){var n=cg(e,t.conv0);return n=ql(n,[2,2],[2,2],`same`),n=cg(n,t.conv1),n=ql(n,[2,2],[2,2],`same`),n=cg(n,t.conv2),n=ql(n,[2,2],[2,2],`same`),n=cg(n,t.conv3),n=ql(n,[2,2],[2,2],`same`),n=cg(n,t.conv4),n=ql(n,[2,2],[2,2],`same`),n=cg(n,t.conv5),n=ql(n,[2,2],[1,1],`same`),n=cg(n,t.conv6),n=cg(n,t.conv7),Om(n,t.conv8,`valid`,!1)},t.prototype.runMobilenet=function(e,t){var n=this.config.isFirstLayerConv2d?sg(Om(e,t.conv0,`valid`,!1)):lg(e,t.conv0);return n=ql(n,[2,2],[2,2],`same`),n=lg(n,t.conv1),n=ql(n,[2,2],[2,2],`same`),n=lg(n,t.conv2),n=ql(n,[2,2],[2,2],`same`),n=lg(n,t.conv3),n=ql(n,[2,2],[2,2],`same`),n=lg(n,t.conv4),n=ql(n,[2,2],[2,2],`same`),n=lg(n,t.conv5),n=ql(n,[2,2],[1,1],`same`),n=t.conv6?lg(n,t.conv6):n,n=t.conv7?lg(n,t.conv7):n,Om(n,t.conv8,`valid`,!1)},t.prototype.forwardInput=function(e,t){var n=this,r=this.params;if(!r)throw Error(`TinyYolov2 - load model before inference`);return H(function(){var i=e.toBatchTensor(t,!1).toFloat();return i=n.config.meanRgb?Ap(i,n.config.meanRgb):i,i=i.div(G(256)),n.config.withSeparableConvs?n.runMobilenet(i,r):n.runTinyYolov2(i,r)})},t.prototype.forward=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,_m(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent()]}})})},t.prototype.detect=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g=this;return $(this,function(_){switch(_.label){case 0:return n=new hg(t),r=n.inputSize,i=n.scoreThreshold,[4,_m(e)];case 1:return a=_.sent(),[4,this.forwardInput(a,r)];case 2:return o=_.sent(),s=H(function(){return Pr(o)[0].expandDims()}),c={width:a.getInputWidth(0),height:a.getInputHeight(0)},[4,this.extractBoxes(s,a.getReshapedInputDimensions(0),i)];case 3:return l=_.sent(),o.dispose(),s.dispose(),u=l.map(function(e){return e.box}),d=l.map(function(e){return e.score}),f=l.map(function(e){return e.classScore}),p=l.map(function(e){return g.config.classes[e.label]}),m=kp(u.map(function(e){return e.rescale(r)}),d,this.config.iouThreshold,!0),h=m.map(function(e){return new Tp(d[e],f[e],p[e],u[e],c)}),[2,h]}})})},t.prototype.getDefaultModelName=function(){return``},t.prototype.extractParamsFromWeigthMap=function(e){return pg(e,this.config)},t.prototype.extractParams=function(e){var n=this.config.filterSizes||t.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(r!==7&&r!==8&&r!==9)throw Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found `+r+` filterSizes in config`);return dg(e,this.config,this.boxEncodingSize,n)},t.prototype.extractBoxes=function(e,t,n){return Q(this,void 0,void 0,function(){var r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this;return $(this,function(N){switch(N.label){case 0:return r=t.width,i=t.height,a=Math.max(r,i),o=a/r,s=a/i,c=e.shape[1],l=this.config.anchors.length,u=H(function(){var t=e.reshape([c,c,l,M.boxEncodingSize]);return[t.slice([0,0,0,0],[c,c,l,4]),t.slice([0,0,0,4],[c,c,l,1]),M.withClassScores?ni(t.slice([0,0,0,5],[c,c,l,M.config.classes.length]),3):G(0)]}),d=u[0],f=u[1],p=u[2],m=[],[4,f.array()];case 1:return h=N.sent(),[4,d.array()];case 2:g=N.sent(),_=0,N.label=3;case 3:if(!(_<c))return[3,12];v=0,N.label=4;case 4:if(!(v<c))return[3,11];y=0,N.label=5;case 5:return y<l?(b=Mp(h[_][v][y][0]),!n||b>n?(x=(v+Mp(g[_][v][y][0]))/c*o,S=(_+Mp(g[_][v][y][1]))/c*s,C=Math.exp(g[_][v][y][2])*this.config.anchors[y].x/c*o,w=Math.exp(g[_][v][y][3])*this.config.anchors[y].y/c*s,T=x-C/2,E=S-w/2,D={row:_,col:v,anchor:y},this.withClassScores?[4,this.extractPredictedClass(p,D)]:[3,7]):[3,9]):[3,10];case 6:return j=N.sent(),[3,8];case 7:j={classScore:1,label:0},N.label=8;case 8:O=j,k=O.classScore,A=O.label,m.push(op({box:new wp(T,E,T+C,E+w),score:b,classScore:b*k,label:A},D)),N.label=9;case 9:return y++,[3,5];case 10:return v++,[3,4];case 11:return _++,[3,3];case 12:return d.dispose(),f.dispose(),p.dispose(),[2,m]}})})},t.prototype.extractPredictedClass=function(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a;return $(this,function(o){switch(o.label){case 0:return n=t.row,r=t.col,i=t.anchor,[4,e.array()];case 1:return a=o.sent(),[2,Array(this.config.classes.length).fill(0).map(function(e,t){return a[n][r][i][t]}).map(function(e,t){return{classScore:e,label:t}}).reduce(function(e,t){return e.classScore>t.classScore?e:t})]}})})},t.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],t}(wm),_g=function(e){Z(t,e);function t(t){t===void 0&&(t=!0);var n=this,r=Object.assign({},{withSeparableConvs:t,iouThreshold:$h,classes:[`face`]},t?{anchors:tg,meanRgb:ng}:{anchors:eg,withClassScores:!0});return n=e.call(this,r)||this,n}return Object.defineProperty(t.prototype,`withSeparableConvs`,{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`anchors`,{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return[4,this.detect(e,t)];case 1:return n=r.sent(),[2,n.map(function(e){return new Ep(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return this.withSeparableConvs?ig:rg},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(gg),vg=function(e){Z(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t._name=`TinyFaceDetectorOptions`,t}return t}(hg),yg=function(){function e(){}return e.prototype.then=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=e,[4,this.run()];case 1:return[2,t.apply(void 0,[n.sent()])]}})})},e.prototype.run=function(){return Q(this,void 0,void 0,function(){return $(this,function(e){throw Error(`ComposableTask - run is not implemented`)})})},e}();function bg(e,t,n,r,i){return i===void 0&&(i=function(e){return e.alignedRect}),Q(this,void 0,void 0,function(){var a,o,s,c,l;return $(this,function(u){switch(u.label){case 0:return a=e.map(function(e){return Qm(e)?i(e):e.detection}),s=r,s?[3,5]:t instanceof Ve?[4,ym(t,a)]:[3,2];case 1:return c=u.sent(),[3,4];case 2:return[4,vm(t,a)];case 3:c=u.sent(),u.label=4;case 4:s=c,u.label=5;case 5:return o=s,[4,n(o)];case 6:return l=u.sent(),o.forEach(function(e){return e instanceof Ve&&e.dispose()}),[2,l]}})})}function xg(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a=this;return $(this,function(o){return[2,bg([e],t,function(e){return Q(a,void 0,void 0,function(){return $(this,function(t){return[2,n(e[0])]})})},r,i)]})})}function Sg(e){return H(function(){return jr(Pr(e,3).reverse(),3)})}function Cg(e,t){var n=Am(e,t),r=jm(e,t);function i(n,r){var i=An(e(n));return t.push({paramPath:r}),i}function a(e,t,r){return r===void 0&&(r=!1),{conv1:n(e[0],e[1],3,t+`/conv1`),prelu1_alpha:i(e[1],t+`/prelu1_alpha`),conv2:n(e[1],e[2],3,t+`/conv2`),prelu2_alpha:i(e[2],t+`/prelu2_alpha`),conv3:n(e[2],e[3],r?2:3,t+`/conv3`),prelu3_alpha:i(e[3],t+`/prelu3_alpha`)}}function o(){var e=a([3,10,16,32],`pnet`),t=n(32,2,1,`pnet/conv4_1`),r=n(32,4,1,`pnet/conv4_2`);return op(op({},e),{conv4_1:t,conv4_2:r})}function s(){var e=a([3,28,48,64],`rnet`,!0),t=r(576,128,`rnet/fc1`),n=i(128,`rnet/prelu4_alpha`),o=r(128,2,`rnet/fc2_1`),s=r(128,4,`rnet/fc2_2`);return op(op({},e),{fc1:t,prelu4_alpha:n,fc2_1:o,fc2_2:s})}function c(){var e=a([3,32,64,64],`onet`),t=n(64,128,2,`onet/conv4`),o=i(128,`onet/prelu4_alpha`),s=r(1152,256,`onet/fc1`),c=i(256,`onet/prelu5_alpha`),l=r(256,2,`onet/fc2_1`),u=r(256,4,`onet/fc2_2`),d=r(256,10,`onet/fc2_3`);return op(op({},e),{conv4:t,prelu4_alpha:o,fc1:s,prelu5_alpha:c,fc2_1:l,fc2_2:u,fc2_3:d})}return{extractPNetParams:o,extractRNetParams:s,extractONetParams:c}}function wg(e){var t=Im(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],a=Cg(n,i),o=a.extractPNetParams,s=a.extractRNetParams,c=a.extractONetParams,l=o(),u=s(),d=c();if(r().length!==0)throw Error(`weights remaing after extract: `+r().length);return{params:{pnet:l,rnet:u,onet:d},paramMappings:i}}function Tg(e,t){var n=Fm(e,t);function r(e){return{filters:n(e+`/weights`,4,e+`/filters`),bias:n(e+`/bias`,1)}}function i(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}function a(e){return n(e,1)}function o(e){return{conv1:r(e+`/conv1`),prelu1_alpha:a(e+`/prelu1_alpha`),conv2:r(e+`/conv2`),prelu2_alpha:a(e+`/prelu2_alpha`),conv3:r(e+`/conv3`),prelu3_alpha:a(e+`/prelu3_alpha`)}}function s(){var e=o(`pnet`),t=r(`pnet/conv4_1`),n=r(`pnet/conv4_2`);return op(op({},e),{conv4_1:t,conv4_2:n})}function c(){var e=o(`rnet`),t=i(`rnet/fc1`),n=a(`rnet/prelu4_alpha`),r=i(`rnet/fc2_1`),s=i(`rnet/fc2_2`);return op(op({},e),{fc1:t,prelu4_alpha:n,fc2_1:r,fc2_2:s})}function l(){var e=o(`onet`),t=r(`onet/conv4`),n=a(`onet/prelu4_alpha`),s=i(`onet/fc1`),c=a(`onet/prelu5_alpha`),l=i(`onet/fc2_1`),u=i(`onet/fc2_2`),d=i(`onet/fc2_3`);return op(op({},e),{conv4:t,prelu4_alpha:n,fc1:s,prelu5_alpha:c,fc2_1:l,fc2_2:u,fc2_3:d})}return{extractPNetParams:s,extractRNetParams:c,extractONetParams:l}}function Eg(e){var t=[],n=Tg(e,t),r=n.extractPNetParams,i=n.extractRNetParams,a=n.extractONetParams,o=r(),s=i(),c=a();return km(e,t),{params:{pnet:o,rnet:s,onet:c},paramMappings:t}}function Dg(e,t){var n=t[0],r=t[1];return{height:Math.floor(n*e),width:Math.floor(r*e)}}function Og(e,t,n){for(var r=n[0],i=n[1],a=12/e,o=[],s=Math.min(r,i)*a,c=0;s>=12;)o.push(a*t**+c),s*=t,c+=1;return o}var kg=function(e){Z(t,e);function t(t,n,r,i){return e.call(this,{left:t,top:n,right:r,bottom:i},!0)||this}return t}(Cp);function Ag(e){return H(function(){return $c(il(e,G(127.5)),G(.0078125))})}function jg(e,t){return H(function(){return zc(vu(e),$c(t,rc(vu(rc(e)))))})}function Mg(e,t,n){return n===void 0&&(n=!1),H(function(){var r=Om(e,t.conv1,`valid`);return r=jg(r,t.prelu1_alpha),r=ql(r,n?[2,2]:[3,3],[2,2],`same`),r=Om(r,t.conv2,`valid`),r=jg(r,t.prelu2_alpha),r=n?r:ql(r,[3,3],[2,2],`valid`),r=Om(r,t.conv3,`valid`),r=jg(r,t.prelu3_alpha),r})}function Ng(e,t){return H(function(){var n=Mg(e,t,!0),r=Om(n,t.conv4_1,`valid`);return{prob:ni(il(r,hr(lu(r,3),3)),3),regions:Om(n,t.conv4_2,`valid`)}})}function Pg(e,t){return H(function(){var n=Dg(t,e.shape.slice(1)),r=n.height,i=n.width;return xu(Ag(gd.resizeBilinear(e,[r,i])),[0,2,1,3])})}function Fg(e,t,n,r){for(var i=[],a=e.arraySync(),o=0;o<e.shape[0];o++)for(var s=0;s<e.shape[1];s++)a[o][s]>=r&&i.push(new Sp(s,o));return i.map(function(e){var r=new wp(Math.round((e.y*2+1)/n),Math.round((e.x*2+1)/n),Math.round((e.y*2+12)/n),Math.round((e.x*2+12)/n)),i=a[e.y][e.x],o=t.arraySync();return{cell:r,score:i,region:new kg(o[e.y][e.x][0],o[e.y][e.x][1],o[e.y][e.x][2],o[e.y][e.x][3])}})}function Ig(e,t,n,r,i){i.stage1=[];var a=t.map(function(t){return H(function(){var n={scale:t},i=Pg(e,t),a=Date.now(),o=Ng(i,r),s=o.prob,c=o.regions;return n.pnet=Date.now()-a,{scoresTensor:Pr(Pr(s,3)[1])[0],regionsTensor:Pr(c)[0],scale:t,statsForScale:n}})}).map(function(e){var t=e.scoresTensor,r=e.regionsTensor,a=e.scale,o=e.statsForScale,s=Fg(t,r,a,n);if(t.dispose(),r.dispose(),!s.length)return i.stage1.push(o),[];var c=Date.now(),l=kp(s.map(function(e){return e.cell}),s.map(function(e){return e.score}),.5);return o.nms=Date.now()-c,o.numBoxes=l.length,i.stage1.push(o),l.map(function(e){return s[e]})}).reduce(function(e,t){return e.concat(t)},[]),o=[],s=[];if(a.length>0){var c=Date.now(),l=kp(a.map(function(e){return e.cell}),a.map(function(e){return e.score}),.7);i.stage1_nms=Date.now()-c,s=l.map(function(e){return a[e].score}),o=l.map(function(e){return a[e]}).map(function(e){var t=e.cell,n=e.region;return new wp(t.left+n.left*t.width,t.top+n.top*t.height,t.right+n.right*t.width,t.bottom+n.bottom*t.height).toSquare().round()})}return{boxes:o,scores:s}}function Lg(e,t,n){var r=n.width,i=n.height;return Q(this,void 0,void 0,function(){var n,a,o,s=this;return $(this,function(c){switch(c.label){case 0:return n=rm(e),[4,Promise.all(t.map(function(t){return Q(s,void 0,void 0,function(){var r,i,a,o,s,c,l,u;return $(this,function(d){return r=t.padAtBorders(e.height,e.width),i=r.y,a=r.ey,o=r.x,s=r.ex,c=o-1,l=i-1,u=n.getImageData(c,l,s-c,a-l),[2,tm.isNodejs()?fm(u):createImageBitmap(u)]})})}))];case 1:return a=c.sent(),o=[],a.forEach(function(e){var t=rm(dm({width:r,height:i}));t.drawImage(e,0,0,r,i);for(var n=t.getImageData(0,0,r,i).data,a=[],s=0;s<n.length;s+=4)a.push(n[s+2]),a.push(n[s+1]),a.push(n[s]);o.push(a)}),[2,o.map(function(e){return H(function(){return Ag(xu(Nn(e,[1,r,i,3]),[0,2,1,3]).toFloat())})})]}})})}function Rg(e,t){return H(function(){var n=Mg(e,t),r=jg(Um(Or(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu4_alpha),i=Um(r,t.fc2_1),a=ni(il(i,hr(lu(i,1),1)),1),o=Um(r,t.fc2_2);return{scores:Pr(a,1)[1],regions:o}})}function zg(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a,o,s,c,l,u,d,f,p,m,h,g,_,v;return $(this,function(y){switch(y.label){case 0:return a=Date.now(),[4,Lg(e,t,{width:24,height:24})];case 1:return o=y.sent(),i.stage2_extractImagePatches=Date.now()-a,a=Date.now(),s=o.map(function(e){var t=Rg(e,r);return e.dispose(),t}),i.stage2_rnet=Date.now()-a,c=s.length>1?Wn(s.map(function(e){return e.scores})):s[0].scores,d=(u=Array).from,[4,c.data()];case 2:return l=d.apply(u,[y.sent()]),c.dispose(),f=l.map(function(e,t){return{score:e,idx:t}}).filter(function(e){return e.score>n}).map(function(e){return e.idx}),p=f.map(function(e){return t[e]}),m=f.map(function(e){return l[e]}),h=[],g=[],p.length>0&&(a=Date.now(),_=kp(p,m,.7),i.stage2_nms=Date.now()-a,v=_.map(function(e){var t=s[f[e]].regions.arraySync();return new kg(t[0][0],t[0][1],t[0][2],t[0][3])}),g=_.map(function(e){return m[e]}),h=_.map(function(e,t){return p[e].calibrate(v[t])})),s.forEach(function(e){e.regions.dispose(),e.scores.dispose()}),[2,{boxes:h,scores:g}]}})})}function Bg(e,t){return H(function(){var n=Mg(e,t);n=ql(n,[2,2],[2,2],`same`),n=Om(n,t.conv4,`valid`),n=jg(n,t.prelu4_alpha);var r=jg(Um(Or(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu5_alpha),i=Um(r,t.fc2_1),a=ni(il(i,hr(lu(i,1),1)),1),o=Um(r,t.fc2_2),s=Um(r,t.fc2_3);return{scores:Pr(a,1)[1],regions:o,points:s}})}function Vg(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a,o,s,c,l,u,d,f,p,m,h,g,_,v,y;return $(this,function(b){switch(b.label){case 0:return a=Date.now(),[4,Lg(e,t,{width:48,height:48})];case 1:return o=b.sent(),i.stage3_extractImagePatches=Date.now()-a,a=Date.now(),s=o.map(function(e){var t=Bg(e,r);return e.dispose(),t}),i.stage3_onet=Date.now()-a,c=s.length>1?Wn(s.map(function(e){return e.scores})):s[0].scores,d=(u=Array).from,[4,c.data()];case 2:return l=d.apply(u,[b.sent()]),c.dispose(),f=l.map(function(e,t){return{score:e,idx:t}}).filter(function(e){return e.score>n}).map(function(e){return e.idx}),p=f.map(function(e){var t=s[e].regions.arraySync();return new kg(t[0][0],t[0][1],t[0][2],t[0][3])}),m=f.map(function(e,n){return t[e].calibrate(p[n])}),h=f.map(function(e){return l[e]}),g=[],_=[],v=[],m.length>0&&(a=Date.now(),y=kp(m,h,.7,!1),i.stage3_nms=Date.now()-a,g=y.map(function(e){return m[e]}),_=y.map(function(e){return h[e]}),v=y.map(function(e,t){return[,,,,,].fill(0).map(function(n,r){var i=s[e].points.arraySync();return new Sp(i[0][r]*(g[t].width+1)+g[t].left,i[0][r+5]*(g[t].height+1)+g[t].top)})})),s.forEach(function(e){e.regions.dispose(),e.scores.dispose(),e.points.dispose()}),[2,{boxes:g,scores:_,points:v}]}})})}var Hg=function(e){Z(t,e);function t(){return e.call(this,`Mtcnn`)||this}return t.prototype.load=function(t){return Q(this,void 0,void 0,function(){return $(this,function(n){return console.warn(`mtcnn is deprecated and will be removed soon`),[2,e.prototype.load.call(this,t)]})})},t.prototype.loadFromDisk=function(t){return Q(this,void 0,void 0,function(){return $(this,function(n){return console.warn(`mtcnn is deprecated and will be removed soon`),[2,e.prototype.loadFromDisk.call(this,t)]})})},t.prototype.forwardInput=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S;return $(this,function(C){switch(C.label){case 0:if(n=this.params,!n)throw Error(`Mtcnn - load model before inference`);if(r=e.canvases[0],!r)throw Error(`Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.`);return i={},a=Date.now(),o=H(function(){return Sg(hr(Bf.fromPixels(r)).toFloat())}),s=function(e){return o.dispose(),i.total=Date.now()-a,e},c=o.shape.slice(1),l=c[0],u=c[1],d=new Ph(t),f=d.minFaceSize,p=d.scaleFactor,m=d.maxNumScales,h=d.scoreThresholds,g=d.scaleSteps,_=(g||Og(f,p,[l,u])).filter(function(e){var t=Dg(e,[l,u]);return Math.min(t.width,t.height)>12}).slice(0,m),i.scales=_,i.pyramid=_.map(function(e){return Dg(e,[l,u])}),v=Date.now(),[4,Ig(o,_,h[0],n.pnet,i)];case 1:return y=C.sent(),i.total_stage1=Date.now()-v,y.boxes.length?(i.stage2_numInputBoxes=y.boxes.length,v=Date.now(),[4,zg(r,y.boxes,h[1],n.rnet,i)]):[2,s({results:[],stats:i})];case 2:return b=C.sent(),i.total_stage2=Date.now()-v,b.boxes.length?(i.stage3_numInputBoxes=b.boxes.length,v=Date.now(),[4,Vg(r,b.boxes,h[2],n.onet,i)]):[2,s({results:[],stats:i})];case 3:return x=C.sent(),i.total_stage3=Date.now()-v,S=x.boxes.map(function(e,t){return $m(Wp({},new Ep(x.scores[t],new Np(e.left/u,e.top/l,e.width/u,e.height/l),{height:l,width:u})),new Rp(x.points[t].map(function(t){return t.sub(new Sp(e.left,e.top)).div(new Sp(e.width,e.height))}),{width:e.width,height:e.height}))}),[2,s({results:S,stats:i})]}})})},t.prototype.forward=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,_m(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent().results]}})})},t.prototype.forwardWithStats=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,_m(e)];case 1:return[2,n.apply(this,[r.sent(),t])]}})})},t.prototype.getDefaultModelName=function(){return`mtcnn_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Eg(e)},t.prototype.extractParams=function(e){return wg(e)},t}(wm),Ug=.4,Wg=[new Sp(1.603231,2.094468),new Sp(6.041143,7.080126),new Sp(2.882459,3.518061),new Sp(4.266906,5.178857),new Sp(9.041765,10.66308)],Gg=[117.001,114.697,97.404],Kg=function(e){Z(t,e);function t(){var t=this,n={withSeparableConvs:!0,iouThreshold:Ug,classes:[`face`],anchors:Wg,meanRgb:Gg,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return t=e.call(this,n)||this,t}return Object.defineProperty(t.prototype,`anchors`,{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return[4,this.detect(e,t)];case 1:return n=r.sent(),[2,n.map(function(e){return new Ep(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return`tiny_face_detector_model`},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(gg),qg={ssdMobilenetv1:new Qh,tinyFaceDetector:new Kg,tinyYolov2:new _g,mtcnn:new Hg,faceLandmark68Net:new mh,faceLandmark68TinyNet:new vh,faceRecognitionNet:new Ah,faceExpressionNet:new Xm,ageGenderNet:new fh},Jg=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return t}(yg),Yg=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n=this;return $(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return e=r.sent(),[4,bg(e,this.input,function(e){return Q(n,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,Promise.all(e.map(function(e){return qg.faceExpressionNet.predictExpressions(e)}))];case 1:return[2,t.sent()]}})})},this.extractedFaces)];case 2:return t=r.sent(),[2,e.map(function(e,n){return Zm(e,t[n])})]}})})},t.prototype.withAgeAndGender=function(){return new e_(this,this.input)},t}(Jg),Xg=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),e?[4,xg(e,this.input,function(e){return qg.faceExpressionNet.predictExpressions(e)},this.extractedFaces)]:[2];case 2:return t=n.sent(),[2,Zm(e,t)]}})})},t.prototype.withAgeAndGender=function(){return new t_(this,this.input)},t}(Jg),Zg=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new n_(this,this.input)},t.prototype.withFaceDescriptors=function(){return new a_(this,this.input)},t}(Yg),Qg=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new r_(this,this.input)},t.prototype.withFaceDescriptor=function(){return new o_(this,this.input)},t}(Xg),$g=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return t}(yg),e_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n=this;return $(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return e=r.sent(),[4,bg(e,this.input,function(e){return Q(n,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,Promise.all(e.map(function(e){return qg.ageGenderNet.predictAgeAndGender(e)}))];case 1:return[2,t.sent()]}})})},this.extractedFaces)];case 2:return t=r.sent(),[2,e.map(function(e,n){var r=t[n],i=r.age,a=r.gender,o=r.genderProbability;return Mh(Nh(e,a,o),i)})]}})})},t.prototype.withFaceExpressions=function(){return new Yg(this,this.input)},t}($g),t_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i;return $(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),e?[4,xg(e,this.input,function(e){return qg.ageGenderNet.predictAgeAndGender(e)},this.extractedFaces)]:[2];case 2:return t=a.sent(),n=t.age,r=t.gender,i=t.genderProbability,[2,Mh(Nh(e,r,i),n)]}})})},t.prototype.withFaceExpressions=function(){return new Xg(this,this.input)},t}($g),n_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new Zg(this,this.input)},t.prototype.withFaceDescriptors=function(){return new a_(this,this.input)},t}(e_),r_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withFaceDescriptor=function(){return new o_(this,this.input)},t}(t_),i_=function(e){Z(t,e);function t(t,n){var r=e.call(this)||this;return r.parentTask=t,r.input=n,r}return t}(yg),a_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),[4,bg(e,this.input,function(e){return Promise.all(e.map(function(e){return qg.faceRecognitionNet.computeFaceDescriptor(e)}))},null,function(e){return e.landmarks.align(null,{useDlibAlignment:!0})})];case 2:return t=n.sent(),[2,t.map(function(t,n){return jh(e[n],t)})]}})})},t.prototype.withFaceExpressions=function(){return new Zg(this,this.input)},t.prototype.withAgeAndGender=function(){return new n_(this,this.input)},t}(i_),o_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),e?[4,xg(e,this.input,function(e){return qg.faceRecognitionNet.computeFaceDescriptor(e)},null,function(e){return e.landmarks.align(null,{useDlibAlignment:!0})})]:[2];case 2:return t=n.sent(),[2,jh(e,t)]}})})},t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withAgeAndGender=function(){return new r_(this,this.input)},t}(i_),s_=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.useTinyLandmarkNet=r,i}return Object.defineProperty(t.prototype,`landmarkNet`,{get:function(){return this.useTinyLandmarkNet?qg.faceLandmark68TinyNet:qg.faceLandmark68Net},enumerable:!0,configurable:!0}),t}(yg),c_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i,a=this;return $(this,function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return e=o.sent(),t=e.map(function(e){return e.detection}),this.input instanceof Ve?[4,ym(this.input,t)]:[3,3];case 2:return r=o.sent(),[3,5];case 3:return[4,vm(this.input,t)];case 4:r=o.sent(),o.label=5;case 5:return n=r,[4,Promise.all(n.map(function(e){return a.landmarkNet.detectLandmarks(e)}))];case 6:return i=o.sent(),n.forEach(function(e){return e instanceof Ve&&e.dispose()}),[2,e.map(function(e,t){return $m(e,i[t])})]}})})},t.prototype.withFaceExpressions=function(){return new Zg(this,this.input)},t.prototype.withAgeAndGender=function(){return new n_(this,this.input)},t.prototype.withFaceDescriptors=function(){return new a_(this,this.input)},t}(s_),l_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i;return $(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),e?(t=e.detection,this.input instanceof Ve?[4,ym(this.input,[t])]:[3,3]):[2];case 2:return r=a.sent(),[3,5];case 3:return[4,vm(this.input,[t])];case 4:r=a.sent(),a.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return i=a.sent(),n.forEach(function(e){return e instanceof Ve&&e.dispose()}),[2,$m(e,i)]}})})},t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withAgeAndGender=function(){return new r_(this,this.input)},t.prototype.withFaceDescriptor=function(){return new o_(this,this.input)},t}(s_),u_=function(e){Z(t,e);function t(t,n){n===void 0&&(n=new Zh);var r=e.call(this)||this;return r.input=t,r.options=n,r}return t}(yg),d_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r;return $(this,function(i){switch(i.label){case 0:return e=this,t=e.input,n=e.options,n instanceof Ph?[4,qg.mtcnn.forward(t,n)]:[3,2];case 1:return[2,i.sent().map(function(e){return e.detection})];case 2:if(r=n instanceof vg?function(e){return qg.tinyFaceDetector.locateFaces(e,n)}:n instanceof Zh?function(e){return qg.ssdMobilenetv1.locateFaces(e,n)}:n instanceof hg?function(e){return qg.tinyYolov2.locateFaces(e,n)}:null,!r)throw Error(`detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options`);return[2,r(t)]}})})},t.prototype.runAndExtendWithFaceDetections=function(){var e=this;return new Promise(function(t){return Q(e,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e.map(function(e){return Wp({},e)}))]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new c_(this.runAndExtendWithFaceDetections(),this.input,e)},t.prototype.withFaceExpressions=function(){return new Yg(this.runAndExtendWithFaceDetections(),this.input)},t.prototype.withAgeAndGender=function(){return new e_(this.runAndExtendWithFaceDetections(),this.input)},t}(u_);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,new d_(this.input,this.options)];case 1:return e=n.sent(),t=e[0],e.forEach(function(e){e.score>t.score&&(t=e)}),[2,t]}})})},t.prototype.runAndExtendWithFaceDetection=function(){var e=this;return new Promise(function(t){return Q(e,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e?Wp({},e):void 0)]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new l_(this.runAndExtendWithFaceDetection(),this.input,e)},t.prototype.withFaceExpressions=function(){return new Xg(this.runAndExtendWithFaceDetection(),this.input)},t.prototype.withAgeAndGender=function(){return new t_(this.runAndExtendWithFaceDetection(),this.input)},t})(u_);function f_(e,t){return t===void 0&&(t=new Zh),new d_(e,t)}function p_(e,t){if(e.length!==t.length)throw Error(`euclideanDistance: arr1.length !== arr2.length`);var n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map(function(e,t){return e-r[t]}).reduce(function(e,t){return e+t**2},0))}(function(){function e(e,t){t===void 0&&(t=.6),this._distanceThreshold=t;var n=Array.isArray(e)?e:[e];if(!n.length)throw Error(`FaceRecognizer.constructor - expected atleast one input`);var r=1,i=function(){return`person `+ r++};this._labeledDescriptors=n.map(function(e){if(e instanceof Hp)return e;if(e instanceof Float32Array)return new Hp(i(),[e]);if(e.descriptor&&e.descriptor instanceof Float32Array)return new Hp(i(),[e.descriptor]);throw Error(`FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>`)})}return Object.defineProperty(e.prototype,`labeledDescriptors`,{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`distanceThreshold`,{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),e.prototype.computeMeanDistance=function(e,t){return t.map(function(t){return p_(t,e)}).reduce(function(e,t){return e+t},0)/(t.length||1)},e.prototype.matchDescriptor=function(e){var t=this;return this.labeledDescriptors.map(function(n){var r=n.descriptors,i=n.label;return new Bp(i,t.computeMeanDistance(e,r))}).reduce(function(e,t){return e.distance<t.distance?e:t})},e.prototype.findBestMatch=function(e){var t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new Bp(`unknown`,t.distance)},e.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(function(e){return e.toJSON()})}},e.fromJSON=function(t){return new e(t.labeledDescriptors.map(function(e){return Hp.fromJSON(e)}),t.distanceThreshold)},e})();function m_(e){return Math.max(0,Math.min(1,e))}function h_(e){let t=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y),n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5];return(t(r,s)+t(i,o))/(2*t(n,a))}function g_(e,t,n){return!t||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(n()),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}function __(){let e=!1;return{load:async(t,n)=>{if(!e)try{let r=n?.timeoutMs??15e3;await g_(qg.tinyFaceDetector.loadFromUri(t),r,()=>({code:`MODEL_LOAD_TIMEOUT`,message:`Timeout ao carregar modelo TinyFaceDetector em: ${t}`})),await g_(qg.faceLandmark68TinyNet.loadFromUri(t),r,()=>({code:`MODEL_LOAD_TIMEOUT`,message:`Timeout ao carregar modelo faceLandmark68TinyNet em: ${t}`})),e=!0}catch(e){throw e?.code===`MODEL_LOAD_TIMEOUT`?e:{code:`MODEL_LOAD_FAILED`,message:`Falha ao carregar modelos face-api.js em: ${t}`,cause:e}}},detect:async(t,n)=>{if(!e)return{faces:0};let r=new vg({inputSize:416,scoreThreshold:.5}),i=t.videoWidth||1,a=t.videoHeight||1;if(n?.withLandmarks){let e=await f_(t,r).withFaceLandmarks(!0);if(!e||e.length===0)return{faces:0};if(e.length>1)return{faces:e.length};let n=e[0].detection.box,o=e[0].landmarks,s=o.getLeftEye(),c=o.getRightEye(),l=o.getNose(),u=o.getJawOutline(),d=e=>e.map(e=>({x:m_(e.x/i),y:m_(e.y/a)})),f=e=>e.reduce((t,n)=>({x:t.x+n.x/e.length,y:t.y+n.y/e.length}),{x:0,y:0}),p=f(s),m=f(c),h=Math.hypot(p.x-m.x,p.y-m.y),g=f(u),_=l&&l.length>0?l[Math.floor(l.length/2)]:void 0,v=h_(s),y=h_(c),b=e=>m_((e-.16)/.12),x=n.x/i,S=n.y/a,C=n.width/i,w=n.height/a;return{faces:1,box:{x,y:S,width:C,height:w},centerX:m_(x+C/2),area:C*w,leftEyeOpenProb:b(v),rightEyeOpenProb:b(y),leftEyeCenter:{x:m_(p.x/i),y:m_(p.y/a)},rightEyeCenter:{x:m_(m.x/i),y:m_(m.y/a)},eyeDist:m_(h/Math.max(i,a)),leftEyePoints:d(s),rightEyePoints:d(c),noseTip:_?{x:m_(_.x/i),y:m_(_.y/a)}:void 0,jawPoints:u?d(u):void 0,jawCenter:{x:m_(g.x/i),y:m_(g.y/a)},poseSource:`landmarks`}}let o=await f_(t,r);if(!o||o.length===0)return{faces:0};if(o.length>1)return{faces:o.length};let s=o[0].box,c=s.x/i,l=s.y/a,u=s.width/i,d=s.height/a;return{faces:1,box:{x:c,y:l,width:u,height:d},centerX:m_(c+u/2),area:u*d,poseSource:`bbox`}}}}function v_(e,t){return{code:e,message:t}}function y_(e){return Math.max(0,Math.min(1,e))}function b_(e){return y_(e?.strictness??.5)}function x_(e){let t=b_(e),n=e?.lookForwardTolerance;return y_(typeof n==`number`?n:1-t)}function S_(e,t,n){if(e.faces===0)return{feedback:v_(`FACE_NOT_FOUND`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1};if(e.faces>1)return{feedback:v_(`MULTIPLE_FACES`,`Apenas 1 rosto por vez`),valid:!1,frameOk:!1,stepOk:!1};if(!e.box)return{feedback:v_(`FACE_NOT_FOUND`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1};let r=b_(t),i=x_(t),{x:a,y:o,width:s,height:c}=e.box,l=a+s/2,u=o+c/2,d=e.area??s*c,f=s/Math.max(1e-6,c),p=.07+r*.02,m=.22-r*.03;if(d<p)return{feedback:v_(`FACE_TOO_FAR`,`Aproxime o rosto`),valid:!1,frameOk:!1,stepOk:!1};if(d>m)return{feedback:v_(`FACE_TOO_CLOSE`,`Afaste o rosto`),valid:!1,frameOk:!1,stepOk:!1};let h=.12-r*.03;if(Math.abs(l-.5)>h||Math.abs(u-.5)>h)return{feedback:v_(`FACE_OFF_CENTER`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1};let g=t?.requireLookForward!==!1,_=(t?.challenges?.length??0)>0,v=g&&!_,y=.1-r*.02,b=typeof t?.lookForwardCenterTol==`number`?y_(t.lookForwardCenterTol):y_(y+i*.08),x=t?.minEyeDistance??.06,S=(t?.maxEyeSymmetryError??.1-r*.03)+i*.1,C=.74+r*.1,w=typeof t?.minFrontalRatio==`number`?Math.max(.5,t.minFrontalRatio):Math.max(.52,C-i*.18),T=!!e.leftEyeCenter&&!!e.rightEyeCenter&&typeof e.eyeDist==`number`,E=e.eyeDist??0,D=T?Math.abs(Math.abs(e.leftEyeCenter.x-(e.centerX??l))-Math.abs(e.rightEyeCenter.x-(e.centerX??l)))/Math.max(1e-6,E):null,O=.78+r*.12;Math.max(.55,O-i*.18);let k=()=>{let t=Math.abs((e.centerX??l)-.5)>b,n=f>=w,a=!1,o=!1,s=e.jawCenter&&e.noseTip?Math.abs(e.noseTip.x-e.jawCenter.x)/Math.max(1e-6,E||e.box?.width||.15):null,c=.22+i*.25-r*.08;return T&&E>=x&&D!=null?a=!(D<=S)&&!(s!=null&&s<=c)||!n:(o=!0,a=!n),{ok:!t&&!a,usedFallback:o}};if(v){let e=k();if(!e.ok)return{feedback:v_(`LOOK_FORWARD`,e.usedFallback?`Olhe para a câmera (aproxime/ilumine para melhor detecção)`:`Olhe para a câmera`),valid:!1,frameOk:!1,stepOk:!1}}let A=n?.current??null;if(!A)return{feedback:v_(`READY`,`Pronto para capturar`),valid:!0,frameOk:!0,stepOk:!0};let j=t?.lookSideTol??.18-r*.05,M=t?.lookUpDownTol??.12-r*.03,N=t?.zoomInMinArea??.16+r*.02,P=t?.zoomOutMaxArea??.12-r*.02,F=t?.blinkClosedThreshold??.35;if(A===`lookForward`){let e=k();return{feedback:v_(`LOOK_FORWARD`,e.usedFallback?`Olhe para a câmera (aproxime/ilumine para melhor detecção)`:`Olhe para a câmera`),valid:e.ok,frameOk:!0,stepOk:e.ok}}if(A===`lookUp`){let e=(u??.5)<.5-M;return{feedback:v_(`LOOK_UP`,`Olhe para cima`),valid:e,frameOk:!0,stepOk:e}}if(A===`lookDown`){let e=(u??.5)>.5+M;return{feedback:v_(`LOOK_DOWN`,`Olhe para baixo`),valid:e,frameOk:!0,stepOk:e}}if(A===`lookLeft`){let t=(e.centerX??l)<.5-j;return{feedback:v_(`LOOK_LEFT`,`Olhe para a esquerda`),valid:t,frameOk:!0,stepOk:t}}if(A===`lookRight`){let t=(e.centerX??l)>.5+j;return{feedback:v_(`LOOK_RIGHT`,`Olhe para a direita`),valid:t,frameOk:!0,stepOk:t}}if(A===`zoomIn`){let e=d>N;return{feedback:v_(`ZOOM_IN`,`Aproxime (zoom in)`),valid:e,frameOk:!0,stepOk:e}}if(A===`zoomOut`){let e=d<P;return{feedback:v_(`ZOOM_OUT`,`Afaste (zoom out)`),valid:e,frameOk:!0,stepOk:e}}if(A===`blink`){let t=e.leftEyeOpenProb,n=e.rightEyeOpenProb,r=typeof t==`number`&&typeof n==`number`&&t<F&&n<F;return{feedback:v_(`BLINK`,`Pisque`),valid:!!r,frameOk:!0,stepOk:!!r}}return{feedback:v_(`READY`,`Pronto para capturar`),valid:!0,frameOk:!0,stepOk:!0}}e.AlphaValid=class{_camera=null;_overlay=null;_container=null;_faceDetector=__();_loopTimer=null;_lastStatusValid=!1;_options=null;_challengeIndex=0;_challengeStartedAt=null;_blinkArmed=!1;_state=null;_status=`idle`;async start(e){n(e.container,`options.container`),await this.stop(),this._options={overlay:!0,uiMode:`default`,guideCircleRatio:.72,detectionIntervalMs:200,modelsPath:`/alphavalid-models`,...e},this._container=this._options.container,this._status=`initializing`,e.onStateChange?.({status:this._status,feedback:{code:`INITIALIZING`,message:`Inicializando câmera...`},message:`Inicializando câmera...`,isReadyToCapture:!1,challenge:{enabled:!1,index:0,total:0,completed:!1}});try{this._options.onFeedback?.({code:`INITIALIZING`,message:`Inicializando câmera...`}),this._camera=await i(this._container),this._options.onVideo?.(this._camera.video),this._options.uiMode!==`headless`&&this._options.overlay!==!1&&(this._overlay=o(this._container,this._options.guideCircleRatio)),this._options.onReady?.(),this._options.modelsPath&&await this._faceDetector.load(this._options.modelsPath,{timeoutMs:this._options.modelLoadTimeoutMs??15e3}),this._status=`running`,this.startDetectionLoop()}catch(e){this._status=`error`;let t=e,n=t&&typeof t==`object`&&typeof t.code==`string`&&typeof t.message==`string`?t:{code:`CAMERA_UNKNOWN`,message:`Erro inesperado ao iniciar o SDK.`,cause:e};throw this._options?.onError?.(n),this._options?.onStateChange?.({status:this._status,feedback:{code:`FACE_NOT_FOUND`,message:`Centralize seu rosto`},message:`Centralize seu rosto`,isReadyToCapture:!1,challenge:{enabled:!1,index:0,total:0,completed:!1}}),await this.stop(),e}}async stop(){this._loopTimer!=null&&(window.clearTimeout(this._loopTimer),this._loopTimer=null),this._lastStatusValid=!1,this._overlay&&=(this._overlay.dispose(),null),this._camera&&=(this._camera.stop(),null),this._container=null,this._options=null,this._challengeIndex=0,this._challengeStartedAt=null,this._blinkArmed=!1,this._state=null,this._status=`idle`}async capture(){if(!this._camera)throw Error(`Camera not started. Call start() first.`);if(!this._lastStatusValid)throw Error(`Face not valid for capture yet. Wait for feedback "Pronto para capturar".`);return await a(this._camera.video,.9)}getState(){return this._state}getCurrentChallenge(){let e=this._options?.liveness?.challenges;return!e||e.length===0?null:e[Math.min(this._challengeIndex,e.length-1)]?.type??null}markStepCompletedIfNeeded(e){let t=this._options,n=t?.liveness?.challenges;if(!t||!n||n.length===0)return;let r=this.getCurrentChallenge();if(!r)return;let i=n[this._challengeIndex];if(i?.timeoutMs&&this._challengeStartedAt!=null&&Date.now()-this._challengeStartedAt>i.timeoutMs){this._challengeStartedAt=Date.now(),this._blinkArmed=!1;return}if(r===`blink`){if(!this._blinkArmed){e||(this._blinkArmed=!0);return}if(!e)return}else if(!e)return;this._challengeIndex+=1,this._challengeStartedAt=Date.now(),this._blinkArmed=!1}startDetectionLoop(){let e=async()=>{let t=this._camera,n=this._options;if(!(!t||!n))try{let e=this.getCurrentChallenge(),r=e===`blink`||n.liveness?.requireLookForward!==!1,i=await this._faceDetector.detect(t.video,{withLandmarks:r}),a=n.liveness?.challenges,o=!!a&&a.length>0;o&&this._challengeStartedAt==null&&(this._challengeStartedAt=Date.now());let s=S_(i,n.liveness,{current:e});this.markStepCompletedIfNeeded(s.stepOk);let c=!o||this._challengeIndex>=(a?.length??0),l=s.frameOk&&c;this._lastStatusValid=l,this._status=l?`ready`:`running`;let u={status:this._status,feedback:s.feedback,message:s.feedback.message,isReadyToCapture:l,challenge:{enabled:o,index:Math.min(this._challengeIndex,a?.length??0),total:a?.length??0,current:c?void 0:this.getCurrentChallenge()??void 0,completed:c}};this._state=u,n.onStateChange?.(u),n.onFeedback?.(s.feedback);let d=n.debug?.drawLandmarks===!0;this._overlay?.render({message:s.feedback.message,box:i.box,valid:l,landmarks:d?{leftEye:i.leftEyePoints,rightEye:i.rightEyePoints,leftEyeCenter:i.leftEyeCenter,rightEyeCenter:i.rightEyeCenter}:void 0})}catch(e){this._status=`error`;let t=e,r=t&&typeof t==`object`&&typeof t.code==`string`&&typeof t.message==`string`?t:{code:`CAMERA_UNKNOWN`,message:`Erro durante detecção/validação.`,cause:e};n.onError?.(r),n.onStateChange?.({status:this._status,feedback:{code:`FACE_NOT_FOUND`,message:`Centralize seu rosto`},message:`Centralize seu rosto`,isReadyToCapture:!1,challenge:this._state?.challenge})}finally{this._loopTimer=window.setTimeout(e,n.detectionIntervalMs??200)}};e()}}});
|
|
3804
|
+
Expected: `+l+`.`)}}function cp(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}Object.freeze({TEST_EPSILON_FLOAT16:ap,expectArraysClose:function(e,t,n){return n??=op(),sp(e,t,(function(e,t){return cp(e,t,n)}))},testEpsilon:op,expectPromiseToFail:function(e,t){e().then((function(){return t.fail()}),(function(){return t()}))},expectArraysEqual:function(e,t){var n=typeof t==`string`||typeof t==`number`||typeof t==`boolean`?[t]:t;return we(e)||we(e[0])||we(t)||we(t[0])?sp(e,n,(function(e,t){return e==t})):sp(e,t,(function(e,t){return cp(e,t,0)}))},expectNumbersClose:function(e,t,n){if(n??=op(),!cp(e,t,n))throw Error(`Numbers differ: actual === `+e+`, expected === `+t)},expectValuesInRange:function(e,t,n){for(var r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw Error(`Value out of range:`+e[r]+` low: `+t+`, high: `+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),Object.freeze({gpgpu_util:jo,webgl_util:yn,forceHalfFloat:function(){O().set(`WEBGL_FORCE_F16_TEXTURES`,!0)},MathBackendWebGL:Ys,setWebGLContext:St,GPGPUContext:Mo});var lp=function(e){function t(){return e!==null&&e.apply(this,arguments)||this}return C(t,e),t.prototype.minimize=function(e,t,n){t===void 0&&(t=!1);var r=this.computeGradients(e,n),i=r.value,a=r.grads;if(n!=null){var o=n.map((function(e){return{name:e.name,tensor:a[e.name]}}));this.applyGradients(o)}else this.applyGradients(a);return xn(a),t?i:(i.dispose(),null)},Object.defineProperty(t.prototype,`iterations`,{get:function(){return this.iterations_??=0,this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,t){return fi(e,t)},t.prototype.dispose=function(){this.iterations_!=null&&xn(this.iterations_)},t.prototype.saveIterations=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){return this.iterations_??=0,[2,{name:`iter`,tensor:q(this.iterations_,`int32`)}]}))}))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){throw Error(`getWeights() is not implemented for this optimizer yet.`)}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(e){throw Error(`setWeights() is not implemented for this optimizer class `+this.getClassName())}))}))},t.prototype.extractIterations=function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){switch(n.label){case 0:return t=this,[4,e[0].tensor.data()];case 1:return t.iterations_=n.sent()[0],[2,e.slice(1)]}}))}))},t}(tp);Object.defineProperty(lp,Symbol.hasInstance,{value:function(e){return e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null}});var up=function(e){function t(t,n,r){r===void 0&&(r=null);var i=e.call(this)||this;return i.learningRate=t,i.rho=n,i.epsilon=r,i.accumulatedGrads=[],i.accumulatedUpdates=[],r??(i.epsilon=V.backend.epsilon()),i}return C(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=V.registeredVariables[n];t.accumulatedGrads[r]??(t.accumulatedGrads[r]={originalName:n+`/accum_grad`,variable:W((function(){return tr(i).variable(!1)}))}),t.accumulatedUpdates[r]??(t.accumulatedUpdates[r]={originalName:n+`/accum_var`,variable:W((function(){return tr(i).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedGrads[r].variable,s=t.accumulatedUpdates[r].variable;W((function(){var e=o.mul(t.rho).add(a.square().mul(1-t.rho)),n=s.add(t.epsilon).sqrt().div(o.add(t.epsilon).sqrt()).mul(a),r=s.mul(t.rho).add(n.square().mul(1-t.rho));o.assign(e),s.assign(r);var c=n.mul(-t.learningRate).add(i);i.assign(c)}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedUpdates!=null&&(xn(this.accumulatedGrads.map((function(e){return e.variable}))),xn(this.accumulatedUpdates.map((function(e){return e.variable}))))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=e.length/2,this.accumulatedGrads=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedUpdates=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className=`Adadelta`,t}(lp);rp(up);var dp=function(e){function t(t,n){n===void 0&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return C(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=V.registeredVariables[n];t.accumulatedGrads[r]??(t.accumulatedGrads[r]={originalName:n+`/accumulator`,variable:W((function(){return Zn(i.shape,t.initialAccumulatorValue).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedGrads[r].variable;W((function(){var e=o.add(a.square());o.assign(e);var n=a.div(e.add(V.backend.epsilon()).sqrt()).mul(-t.learningRate).add(i);i.assign(n)}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedGrads!=null&&xn(this.accumulatedGrads.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulatedGrads=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className=`Adagrad`,t}(lp);rp(dp);var fp=function(e){function t(t,n,r,i){i===void 0&&(i=null);var a=e.call(this)||this;return a.learningRate=t,a.beta1=n,a.beta2=r,a.epsilon=i,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],W((function(){a.accBeta1=q(n).variable(),a.accBeta2=q(r).variable()})),i??(a.epsilon=V.backend.epsilon()),a}return C(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);W((function(){var r=vl(1,t.accBeta1),i=vl(1,t.accBeta2);n.forEach((function(n,a){var o=V.registeredVariables[n];t.accumulatedFirstMoment[a]??(t.accumulatedFirstMoment[a]={originalName:n+`/m`,variable:W((function(){return tr(o).variable(!1)}))}),t.accumulatedSecondMoment[a]??(t.accumulatedSecondMoment[a]={originalName:n+`/v`,variable:W((function(){return tr(o).variable(!1)}))});var s=Array.isArray(e)?e[a].tensor:e[n];if(s!=null){var c=t.accumulatedFirstMoment[a].variable,l=t.accumulatedSecondMoment[a].variable,u=c.mul(t.beta1).add(s.mul(1-t.beta1)),d=l.mul(t.beta2).add(s.square().mul(1-t.beta2)),f=u.div(r),p=d.div(i);c.assign(u),l.assign(d);var m=f.div(p.sqrt().add(t.epsilon)).mul(-t.learningRate).add(o);o.assign(m)}})),t.accBeta1.assign(t.accBeta1.mul(t.beta1)),t.accBeta2.assign(t.accBeta2.mul(t.beta2))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&xn(this.accumulatedFirstMoment.map((function(e){return e.variable}))),this.accumulatedSecondMoment!=null&&xn(this.accumulatedSecondMoment.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){var t,n=this;return T(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),W((function(){n.accBeta1.assign(hl(n.beta1,n.iterations_+1)),n.accBeta2.assign(hl(n.beta2,n.iterations_+1))})),t=e.length/2,this.accumulatedFirstMoment=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedSecondMoment=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className=`Adam`,t}(lp);rp(fp);var pp=function(e){function t(t,n,r,i,a){i===void 0&&(i=null),a===void 0&&(a=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=i,o.decay=a,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],W((function(){o.iteration=q(0).variable(),o.accBeta1=q(n).variable()})),i??(o.epsilon=V.backend.epsilon()),o}return C(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);W((function(){var r=vl(1,t.accBeta1),i=rl(-t.learningRate,t.iteration.mul(t.decay).add(1));n.forEach((function(n,a){var o=V.registeredVariables[n];t.accumulatedFirstMoment[a]??(t.accumulatedFirstMoment[a]={originalName:n+`/m`,variable:tr(o).variable(!1)}),t.accumulatedWeightedInfNorm[a]??(t.accumulatedWeightedInfNorm[a]={originalName:n+`/v`,variable:tr(o).variable(!1)});var s=Array.isArray(e)?e[a].tensor:e[n];if(s!=null){var c=t.accumulatedFirstMoment[a].variable,l=t.accumulatedWeightedInfNorm[a].variable,u=c.mul(t.beta1).add(s.mul(1-t.beta1)),d=l.mul(t.beta2),f=s.abs(),p=d.maximum(f);c.assign(u),l.assign(p);var m=i.div(r).mul(u.div(p.add(t.epsilon))).add(o);o.assign(m)}})),t.iteration.assign(t.iteration.add(1)),t.accBeta1.assign(t.accBeta1.mul(t.beta1))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&xn(this.accumulatedFirstMoment.map((function(e){return e.variable}))),this.accumulatedWeightedInfNorm!=null&&xn(this.accumulatedWeightedInfNorm.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){throw Error(`getWeights() is not implemented for Adamax yet.`)}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(e){throw Error(`setWeights() is not implemented for Adamax yet.`)}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className=`Adamax`,t}(lp);rp(pp);var mp=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return C(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=Array.isArray(e)?e[r].tensor:e[n];if(i!=null){var a=V.registeredVariables[n];W((function(){var e=t.c.mul(i).add(a);a.assign(e)}))}})),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Sn(q(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:if((e=t.sent()).length!==0)throw Error(`SGD optimizer does not have settable weights.`);return[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className=`SGD`,t}(lp);rp(mp);var hp=function(e){function t(t,n,r){r===void 0&&(r=!1);var i=e.call(this,t)||this;return i.learningRate=t,i.momentum=n,i.useNesterov=r,i.accumulations=[],i.m=q(i.momentum),i}return C(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=V.registeredVariables[n];t.accumulations[r]??(t.accumulations[r]={originalName:n+`/momentum`,variable:W((function(){return tr(i).variable(!1)}))});var a=t.accumulations[r].variable,o=Array.isArray(e)?e[r].tensor:e[n];o!=null&&W((function(){var e,n=t.m.mul(a).add(o);e=t.useNesterov?t.c.mul(o.add(n.mul(t.m))).add(i):t.c.mul(n).add(i),a.assign(n),i.assign(e)}))})),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&xn(this.accumulations.map((function(e){return e.variable})))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){return T(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){return T(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulations=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className=`Momentum`,t}(mp);rp(hp);var gp=function(e){function t(t,n,r,i,a){n===void 0&&(n=.9),r===void 0&&(r=0),i===void 0&&(i=null),a===void 0&&(a=!1);var o=e.call(this)||this;if(o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=i,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=a,i??(o.epsilon=V.backend.epsilon()),t==null)throw Error(`learningRate for RMSPropOptimizer must be defined.`);return o}return C(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=V.registeredVariables[n];t.accumulatedMeanSquares[r]??(t.accumulatedMeanSquares[r]={originalName:n+`/rms`,variable:W((function(){return tr(i).variable(!1)}))}),t.accumulatedMoments[r]??(t.accumulatedMoments[r]={originalName:n+`/momentum`,variable:W((function(){return tr(i).variable(!1)}))}),t.accumulatedMeanGrads[r]==null&&t.centered&&(t.accumulatedMeanGrads[r]={originalName:n+`/mg`,variable:W((function(){return tr(i).variable(!1)}))});var a=Array.isArray(e)?e[r].tensor:e[n];if(a!=null){var o=t.accumulatedMeanSquares[r].variable,s=t.accumulatedMoments[r].variable;W((function(){var e=o.mul(t.decay).add(a.square().mul(1-t.decay));if(t.centered){var n=t.accumulatedMeanGrads[r].variable,c=n.mul(t.decay).add(a.mul(1-t.decay)),l=s.mul(t.momentum).add(a.mul(t.learningRate).div(e.sub(c.square().add(t.epsilon)).sqrt()));o.assign(e),n.assign(c),s.assign(l);var u=i.sub(l);i.assign(u)}else{var d=o.mul(t.decay).add(a.square().mul(1-t.decay));l=s.mul(t.momentum).add(a.mul(t.learningRate).div(d.add(t.epsilon).sqrt())),o.assign(d),s.assign(l),u=i.sub(l),i.assign(u)}}))}})),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&xn(this.accumulatedMeanSquares.map((function(e){return e.variable}))),this.accumulatedMeanGrads!=null&&this.centered&&xn(this.accumulatedMeanGrads.map((function(e){return e.variable}))),this.accumulatedMoments!=null&&xn(this.accumulatedMoments.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return w(this,void 0,void 0,(function(){var e;return T(this,(function(t){switch(t.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return w(this,void 0,void 0,(function(){var t;return T(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=this.centered?e.length/3:e.length/2,this.accumulatedMeanSquares=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedMoments=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}))),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className=`RMSProp`,t}(lp);rp(gp);var _p=function(){function e(){}return e.sgd=function(e){return new mp(e)},e.momentum=function(e,t,n){return n===void 0&&(n=!1),new hp(e,t,n)},e.rmsprop=function(e,t,n,r,i){return t===void 0&&(t=.9),n===void 0&&(n=0),r===void 0&&(r=null),i===void 0&&(i=!1),new gp(e,t,n,r,i)},e.adam=function(e,t,n,r){return e===void 0&&(e=.001),t===void 0&&(t=.9),n===void 0&&(n=.999),r===void 0&&(r=null),new fp(e,t,n,r)},e.adadelta=function(e,t,n){return e===void 0&&(e=.001),t===void 0&&(t=.95),n===void 0&&(n=null),new up(e,t,n)},e.adamax=function(e,t,n,r,i){return e===void 0&&(e=.002),t===void 0&&(t=.9),n===void 0&&(n=.999),r===void 0&&(r=null),i===void 0&&(i=0),new pp(e,t,n,r,i)},e.adagrad=function(e,t){return t===void 0&&(t=.1),new dp(e,t)},e}();_p.sgd,_p.momentum,_p.adadelta,_p.adagrad,_p.rmsprop,_p.adamax,_p.adam,$e.prototype.squaredDifference=function(e){return Qs(this,e)},B=zd;function vp(e,t,n){if(n===void 0&&(n=!1),e.beginPath(),t.slice(1).forEach(function(n,r){var i=n.x,a=n.y,o=t[r];e.moveTo(o.x,o.y),e.lineTo(i,a)}),n){var r=t[t.length-1],i=t[0];if(!r||!i)return;e.moveTo(r.x,r.y),e.lineTo(i.x,i.y)}e.stroke()}var yp=function(e,t){return yp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},yp(e,t)};function Z(e,t){yp(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var bp=function(){return bp=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},bp.apply(this,arguments)};function Q(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function $(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}}function xp(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}var Sp=function(){function e(e,t){if(!Pp(e)||!Pp(t))throw Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have `+JSON.stringify({width:e,height:t}));this._width=e,this._height=t}return Object.defineProperty(e.prototype,`width`,{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`height`,{get:function(){return this._height},enumerable:!0,configurable:!0}),e.prototype.reverse=function(){return new e(1/this.width,1/this.height)},e}();function Cp(e,t){return e instanceof $e&&e.shape.length===t}function wp(e){return Cp(e,2)}function Tp(e){return Cp(e,3)}function Ep(e){return Cp(e,4)}function Dp(e){return e%1!=0}function Op(e){return e%2==0}function kp(e,t){t===void 0&&(t=2);var n=10**t;return Math.floor(e*n)/n}function Ap(e){return e&&e.width&&e.height}function jp(e,t){var n=e.width,r=e.height,i=t/Math.max(r,n);return new Sp(Math.round(n*i),Math.round(r*i))}function Mp(e){return e.reduce(function(e,t){return e.add(t)},new Ip(0,0)).div(new Ip(e.length,e.length))}function Np(e,t,n){return Array(e).fill(0).map(function(e,r){return t+r*n})}function Pp(e){return!!e&&e!==1/0&&e!==-1/0&&!isNaN(e)||e===0}function Fp(e){return Pp(e)&&0<=e&&e<=1}var Ip=function(){function e(e,t){this._x=e,this._y=t}return Object.defineProperty(e.prototype,`x`,{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`y`,{get:function(){return this._y},enumerable:!0,configurable:!0}),e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.sub=function(t){return new e(this.x-t.x,this.y-t.y)},e.prototype.mul=function(t){return new e(this.x*t.x,this.y*t.y)},e.prototype.div=function(t){return new e(this.x/t.x,this.y/t.y)},e.prototype.abs=function(){return new e(Math.abs(this.x),Math.abs(this.y))},e.prototype.magnitude=function(){return Math.sqrt(this.x**2+this.y**2)},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y))},e}(),Lp=function(){function e(t,n){n===void 0&&(n=!0);var r=t||{},i=[r.left,r.top,r.right,r.bottom].every(Pp),a=[r.x,r.y,r.width,r.height].every(Pp);if(!a&&!i)throw Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have `+JSON.stringify(r));var o=a?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top],s=o[0],c=o[1],l=o[2],u=o[3];e.assertIsValidBox({x:s,y:c,width:l,height:u},`Box.constructor`,n),this._x=s,this._y=c,this._width=l,this._height=u}return e.isRect=function(e){return!!e&&[e.x,e.y,e.width,e.height].every(Pp)},e.assertIsValidBox=function(t,n,r){if(r===void 0&&(r=!1),!e.isRect(t))throw Error(n+` - invalid box: `+JSON.stringify(t)+`, expected object with properties x, y, width, height`);if(!r&&(t.width<0||t.height<0))throw Error(n+` - width (`+t.width+`) and height (`+t.height+`) must be positive numbers`)},Object.defineProperty(e.prototype,`x`,{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`y`,{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`width`,{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`height`,{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`left`,{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`top`,{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`right`,{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottom`,{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`area`,{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`topLeft`,{get:function(){return new Ip(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`topRight`,{get:function(){return new Ip(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottomLeft`,{get:function(){return new Ip(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`bottomRight`,{get:function(){return new Ip(this.right,this.bottom)},enumerable:!0,configurable:!0}),e.prototype.round=function(){var t=[this.x,this.y,this.width,this.height].map(function(e){return Math.round(e)}),n=t[0],r=t[1],i=t[2],a=t[3];return new e({x:n,y:r,width:i,height:a})},e.prototype.floor=function(){var t=[this.x,this.y,this.width,this.height].map(function(e){return Math.floor(e)}),n=t[0],r=t[1],i=t[2],a=t[3];return new e({x:n,y:r,width:i,height:a})},e.prototype.toSquare=function(){var t=this,n=t.x,r=t.y,i=t.width,a=t.height,o=Math.abs(i-a);return i<a&&(n-=o/2,i+=o),a<i&&(r-=o/2,a+=o),new e({x:n,y:r,width:i,height:a})},e.prototype.rescale=function(t){var n=Ap(t)?t.width:t,r=Ap(t)?t.height:t;return new e({x:this.x*n,y:this.y*r,width:this.width*n,height:this.height*r})},e.prototype.pad=function(t,n){var r=[this.x-t/2,this.y-n/2,this.width+t,this.height+n],i=r[0],a=r[1],o=r[2],s=r[3];return new e({x:i,y:a,width:o,height:s})},e.prototype.clipAtImageBorders=function(t,n){var r=this,i=r.x,a=r.y,o=r.right,s=r.bottom,c=Math.max(i,0),l=Math.max(a,0),u=o-c,d=s-l;return new e({x:c,y:l,width:Math.min(u,t-c),height:Math.min(d,n-l)}).floor()},e.prototype.shift=function(t,n){var r=this,i=r.width,a=r.height;return new e({x:this.x+t,y:this.y+n,width:i,height:a})},e.prototype.padAtBorders=function(e,t){var n=this.width+1,r=this.height+1,i=1,a=1,o=n,s=r,c=this.left,l=this.top,u=this.right,d=this.bottom;return u>t&&(o=-u+t+n,u=t),d>e&&(s=-d+e+r,d=e),c<1&&(s=2-c,c=1),l<1&&(s=2-l,l=1),{dy:a,edy:s,dx:i,edx:o,y:l,ey:d,x:c,ex:u,w:n,h:r}},e.prototype.calibrate=function(t){return new e({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()},e}(),Rp=function(e){Z(t,e);function t(t,n,r,i,a){return a===void 0&&(a=!1),e.call(this,{left:t,top:n,right:r,bottom:i},a)||this}return t}(Lp),zp=function(){function e(e,t,n,r,i){this._imageDims=new Sp(i.width,i.height),this._score=e,this._classScore=t,this._className=n,this._box=new Lp(r).rescale(this._imageDims)}return Object.defineProperty(e.prototype,`score`,{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`classScore`,{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`className`,{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`box`,{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageDims`,{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageWidth`,{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageHeight`,{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`relativeBox`,{get:function(){return new Lp(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),e.prototype.forSize=function(t,n){return new e(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})},e}(),Bp=function(e){Z(t,e);function t(t,n,r){return e.call(this,t,t,``,n,r)||this}return t.prototype.forSize=function(n,r){var i=e.prototype.forSize.call(this,n,r),a=i.score,o=i.relativeBox,s=i.imageDims;return new t(a,o,s)},t}(zp);function Vp(e,t,n){n===void 0&&(n=!0);var r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top));return n?r/(e.area+t.area-r):r/Math.min(e.area,t.area)}function Hp(e){var t=e.map(function(e){return e.x}),n=e.map(function(e){return e.y});return new Rp(t.reduce(function(e,t){return t<e?t:e},1/0),n.reduce(function(e,t){return t<e?t:e},1/0),t.reduce(function(e,t){return e<t?t:e},0),n.reduce(function(e,t){return e<t?t:e},0))}function Up(e,t,n,r){r===void 0&&(r=!0);for(var i=t.map(function(e,t){return{score:e,boxIndex:t}}).sort(function(e,t){return e.score-t.score}).map(function(e){return e.boxIndex}),a=[],o=function(){var t=i.pop();a.push(t);for(var o=i,s=[],c=0;c<o.length;c++){var l=o[c],u=e[t],d=e[l];s.push(Vp(u,d,r))}i=i.filter(function(e,t){return s[t]<=n})};i.length>0;)o();return a}function Wp(e,t){return W(function(){var n=t[0],r=t[1],i=t[2];return vl(e,nr([Zn(xp(e.shape.slice(0,3),[1]),n),Zn(xp(e.shape.slice(0,3),[1]),r),Zn(xp(e.shape.slice(0,3),[1]),i)],3))})}function Gp(e,t){return t===void 0&&(t=!1),W(function(){var n=e.shape.slice(1),r=n[0],i=n[1];if(r===i)return e;var a=Math.abs(r-i),o=Math.round(a*(t?.5:1)),s=r>i?2:1,c=function(t){var n=e.shape.slice();return n[s]=t,Zn(n,0)},l=c(o),u=a-l.shape[s];return nr([t&&u?c(u):null,e,l].filter(function(e){return!!e}).map(function(e){return e.toFloat()}),s)})}function Kp(e){return 1/(1+Math.exp(-e))}var qp=function(e){Z(t,e);function t(t,n,r,i,a){return a===void 0&&(a=!1),e.call(this,{x:t,y:n,width:r,height:i},a)||this}return t}(Lp),Jp=.5,Yp=.43,Xp=.45,Zp=function(){function e(e,t,n){n===void 0&&(n=new Ip(0,0));var r=t.width,i=t.height;this._imgDims=new Sp(r,i),this._shift=n,this._positions=e.map(function(e){return e.mul(new Ip(r,i)).add(n)})}return Object.defineProperty(e.prototype,`shift`,{get:function(){return new Ip(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageWidth`,{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`imageHeight`,{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`positions`,{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`relativePositions`,{get:function(){var e=this;return this._positions.map(function(t){return t.sub(e._shift).div(new Ip(e.imageWidth,e.imageHeight))})},enumerable:!0,configurable:!0}),e.prototype.forSize=function(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})},e.prototype.shiftBy=function(e,t){return new this.constructor(this.relativePositions,this._imgDims,new Ip(e,t))},e.prototype.shiftByPoint=function(e){return this.shiftBy(e.x,e.y)},e.prototype.align=function(e,t){if(t===void 0&&(t={}),e){var n=e instanceof Bp?e.box.floor():new Lp(e);return this.shiftBy(n.x,n.y).align(null,t)}var r=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t),i=r.useDlibAlignment,a=r.minBoxPadding;return i?this.alignDlib():this.alignMinBbox(a)},e.prototype.alignDlib=function(){var e=this.getRefPointsForAlignment(),t=e[0],n=e[1],r=e[2],i=function(e){return r.sub(e).magnitude()},a=(i(t)+i(n))/2,o=Math.floor(a/Xp),s=Mp(e),c=Math.floor(Math.max(0,s.x-Jp*o)),l=Math.floor(Math.max(0,s.y-Yp*o));return new qp(c,l,Math.min(o,this.imageWidth+c),Math.min(o,this.imageHeight+l))},e.prototype.alignMinBbox=function(e){var t=Hp(this.positions);return t.pad(t.width*e,t.height*e)},e.prototype.getRefPointsForAlignment=function(){throw Error(`getRefPointsForAlignment not implemented by base class`)},e}(),Qp=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getRefPointsForAlignment=function(){var e=this.positions;return[e[0],e[1],Mp([e[3],e[4]])]},t}(Zp),$p=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getJawOutline=function(){return this.positions.slice(0,17)},t.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},t.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},t.prototype.getNose=function(){return this.positions.slice(27,36)},t.prototype.getLeftEye=function(){return this.positions.slice(36,42)},t.prototype.getRightEye=function(){return this.positions.slice(42,48)},t.prototype.getMouth=function(){return this.positions.slice(48,68)},t.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Mp)},t}(Zp),em=function(){function e(e,t){this._label=e,this._distance=t}return Object.defineProperty(e.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`distance`,{get:function(){return this._distance},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){return e===void 0&&(e=!0),``+this.label+(e?` (`+kp(this.distance)+`)`:``)},e}(),tm=function(e){Z(t,e);function t(t,n){var r=e.call(this,t)||this;return r._label=n,r}return t.assertIsValidLabeledBox=function(e,t){if(Lp.assertIsValidBox(e,t),!Pp(e.label))throw Error(t+` - expected property label (`+e.label+`) to be a number`)},Object.defineProperty(t.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),t}(Lp),nm=function(){function e(e,t){if(typeof e!=`string`)throw Error(`LabeledFaceDescriptors - constructor expected label to be a string`);if(!Array.isArray(t)||t.some(function(e){return!(e instanceof Float32Array)}))throw Error(`LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array`);this._label=e,this._descriptors=t}return Object.defineProperty(e.prototype,`label`,{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`descriptors`,{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),e.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map(function(e){return Array.from(e)})}},e.fromJSON=function(t){var n=t.descriptors.map(function(e){return new Float32Array(e)});return new e(t.label,n)},e}();(function(e){Z(t,e);function t(t,n,r,i){var a=e.call(this,t,n)||this;return a._score=r,a._classScore=i,a}return t.assertIsValidPredictedBox=function(e,t){if(tm.assertIsValidLabeledBox(e,t),!Fp(e.score)||!Fp(e.classScore))throw Error(t+` - expected properties score (`+e.score+`) and (`+e.classScore+`) to be a number between [0, 1]`)},Object.defineProperty(t.prototype,`score`,{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`classScore`,{get:function(){return this._classScore},enumerable:!0,configurable:!0}),t})(tm);function rm(e){return e.detection instanceof Bp}function im(e,t){return Object.assign({},e,{detection:t})}function am(){var e=window.fetch||function(){throw Error(`fetch - missing fetch implementation for browser environment`)};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement(`canvas`)},createImageElement:function(){return document.createElement(`img`)},fetch:e,readFile:function(){throw Error(`readFile - filesystem not available for browser environment`)}}}function om(e){var t=``;if(!e)try{e=x()}catch(e){t=e.toString()}return{readFile:e?function(t){return new Promise(function(n,r){e.readFile(t,function(e,t){return e?r(e):n(t)})})}:function(){throw Error(`readFile - failed to require fs in nodejs environment with error: `+t)}}}function sm(){var e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=function(){if(e)return new e;throw Error(`createCanvasElement - missing Canvas implementation for nodejs environment`)},r=function(){if(t)return new t;throw Error(`createImageElement - missing Image implementation for nodejs environment`)},i=global.fetch||function(){throw Error(`fetch - missing fetch implementation for nodejs environment`)},a=om();return bp({Canvas:e||function(){function e(){}return e}(),CanvasRenderingContext2D:global.CanvasRenderingContext2D||function(){function e(){}return e}(),Image:t||function(){function e(){}return e}(),ImageData:global.ImageData||function(){function e(){}return e}(),Video:global.HTMLVideoElement||function(){function e(){}return e}(),createCanvasElement:n,createImageElement:r,fetch:i},a)}function cm(){return typeof window==`object`&&typeof document<`u`&&typeof HTMLImageElement<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLVideoElement<`u`&&typeof ImageData<`u`&&typeof CanvasRenderingContext2D<`u`}function lm(){return typeof global==`object`&&typeof require==`function`&&typeof module<`u`&&typeof process<`u`&&!!process.version}var um;function dm(){if(!um)throw Error(`getEnv - environment is not defined, check isNodejs() and isBrowser()`);return um}function fm(e){um=e}function pm(){cm()&&fm(am()),lm()&&fm(sm())}function mm(e){if(um||pm(),!um)throw Error(`monkeyPatch - environment is not defined, check isNodejs() and isBrowser()`);var t=e.Canvas,n=t===void 0?um.Canvas:t,r=e.Image,i=r===void 0?um.Image:r;um.Canvas=n,um.Image=i,um.createCanvasElement=e.createCanvasElement||(function(){return new n}),um.createImageElement=e.createImageElement||(function(){return new i}),um.ImageData=e.ImageData||um.ImageData,um.Video=e.Video||um.Video,um.fetch=e.fetch||um.fetch,um.readFile=e.readFile||um.readFile}var hm={getEnv:dm,setEnv:fm,initialize:pm,createBrowserEnv:am,createFileSystem:om,createNodejsEnv:sm,monkeyPatch:mm,isBrowser:cm,isNodejs:lm};pm();function gm(e){return!hm.isNodejs()&&typeof e==`string`?document.getElementById(e):e}function _m(e){var t=hm.getEnv(),n=t.Canvas;if(e instanceof t.CanvasRenderingContext2D)return e;var r=gm(e);if(!(r instanceof n))throw Error(`resolveContext2d - expected canvas to be of instance of Canvas`);var i=r.getContext(`2d`);if(!i)throw Error(`resolveContext2d - canvas 2d context is null`);return i}var vm;(function(e){e.TOP_LEFT=`TOP_LEFT`,e.TOP_RIGHT=`TOP_RIGHT`,e.BOTTOM_LEFT=`BOTTOM_LEFT`,e.BOTTOM_RIGHT=`BOTTOM_RIGHT`})(vm||={});var ym=function(){function e(e){e===void 0&&(e={});var t=e.anchorPosition,n=e.backgroundColor,r=e.fontColor,i=e.fontSize,a=e.fontStyle,o=e.padding;this.anchorPosition=t||vm.TOP_LEFT,this.backgroundColor=n||`rgba(0, 0, 0, 0.5)`,this.fontColor=r||`rgba(255, 255, 255, 1)`,this.fontSize=i||14,this.fontStyle=a||`Georgia`,this.padding=o||4}return e}(),bm=function(){function e(t,n,r){r===void 0&&(r={}),this.text=typeof t==`string`?[t]:t instanceof e?t.text:t,this.anchor=n,this.options=new ym(r)}return e.prototype.measureWidth=function(e){var t=this.options.padding;return this.text.map(function(t){return e.measureText(t).width}).reduce(function(e,t){return e<t?t:e},0)+2*t},e.prototype.measureHeight=function(){var e=this.options,t=e.fontSize,n=e.padding;return this.text.length*t+2*n},e.prototype.getUpperLeft=function(e,t){var n=this.options.anchorPosition,r=n===vm.BOTTOM_RIGHT||n===vm.TOP_RIGHT,i=n===vm.BOTTOM_LEFT||n===vm.BOTTOM_RIGHT,a=this.measureWidth(e),o=this.measureHeight(),s=r?this.anchor.x-a:this.anchor.x,c=i?this.anchor.y-o:this.anchor.y;if(t){var l=t.width,u=t.height;return{x:Math.max(Math.min(s,l-a),0),y:Math.max(Math.min(c,u-o),0)}}return{x:s,y:c}},e.prototype.draw=function(e){var t=gm(e),n=_m(t),r=this.options,i=r.backgroundColor,a=r.fontColor,o=r.fontSize,s=r.fontStyle,c=r.padding;n.font=o+`px `+s;var l=this.measureWidth(n),u=this.measureHeight();n.fillStyle=i;var d=this.getUpperLeft(n,t);n.fillRect(d.x,d.y,l,u),n.fillStyle=a,this.text.forEach(function(e,t){var r=c+d.x,i=c+d.y+(t+1)*o;n.fillText(e,r,i)})},e}(),xm=function(){function e(e){e===void 0&&(e={});var t=e.boxColor,n=e.lineWidth,r=e.label,i=e.drawLabelOptions;this.boxColor=t||`rgba(0, 0, 255, 1)`,this.lineWidth=n||2,this.label=r;var a={anchorPosition:vm.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new ym(Object.assign({},a,i))}return e}();(function(){function e(e,t){t===void 0&&(t={}),this.box=new Lp(e),this.options=new xm(t)}return e.prototype.draw=function(e){var t=_m(e),n=this.options,r=n.boxColor,i=n.lineWidth,a=this.box,o=a.x,s=a.y,c=a.width,l=a.height;t.strokeStyle=r,t.lineWidth=i,t.strokeRect(o,s,c,l);var u=this.options.label;u&&new bm([u],{x:o-i/2,y:s},this.options.drawLabelOptions).draw(e)},e})();function Sm(e){var t=hm.getEnv(),n=t.Image,r=t.Video;return e instanceof n&&e.complete||e instanceof r&&e.readyState>=3}function Cm(e){return new Promise(function(t,n){if(e instanceof hm.getEnv().Canvas||Sm(e))return t();function r(e){e.currentTarget&&(e.currentTarget.removeEventListener(`load`,r),e.currentTarget.removeEventListener(`error`,i),t(e))}function i(e){e.currentTarget&&(e.currentTarget.removeEventListener(`load`,r),e.currentTarget.removeEventListener(`error`,i),n(e))}e.addEventListener(`load`,r),e.addEventListener(`error`,i)})}function wm(e){var t=hm.getEnv(),n=t.Image,r=t.Video;return e instanceof n?new Sp(e.naturalWidth,e.naturalHeight):e instanceof r?new Sp(e.videoWidth,e.videoHeight):new Sp(e.width,e.height)}function Tm(e){var t=e.width,n=e.height,r=hm.getEnv().createCanvasElement,i=r();return i.width=t,i.height=n,i}function Em(e,t){var n=hm.getEnv().ImageData;if(!(e instanceof n)&&!Sm(e))throw Error(`createCanvasFromMedia - media has not finished loading yet`);var r=t||wm(e),i=r.width,a=r.height,o=Tm({width:i,height:a});return e instanceof n?_m(o).putImageData(e,0,0):_m(o).drawImage(e,0,0,i,a),o}function Dm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a,o,s;return $(this,function(c){switch(c.label){case 0:return n=t||hm.getEnv().createCanvasElement(),r=e.shape.slice(Ep(e)?1:0),i=r[0],a=r[1],o=r[2],s=W(function(){return e.as3D(i,a,o).toInt()}),[4,ep.toPixels(s,n)];case 1:return c.sent(),s.dispose(),[2,n]}})})}function Om(e){var t=hm.getEnv(),n=t.Image,r=t.Canvas,i=t.Video;return e instanceof n||e instanceof r||e instanceof i}function km(e,t,n){n===void 0&&(n=!1);var r=hm.getEnv(),i=r.Image,a=r.Canvas;if(!(e instanceof i||e instanceof a))throw Error(`imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement`);var o=wm(e),s=t/Math.max(o.height,o.width),c=s*o.width,l=s*o.height,u=Tm({width:t,height:t}),d=e instanceof a?e:Em(e),f=Math.abs(c-l)/2,p=n&&c<l?f:0,m=n&&l<c?f:0;return _m(u).drawImage(d,p,m,c,l),u}var Am=function(){function e(e,t){var n=this;if(t===void 0&&(t=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have `+e);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach(function(e,t){if(Tp(e)){n._imageTensors[t]=e,n._inputDimensions[t]=e.shape;return}if(Ep(e)){var r=e.shape[0];if(r!==1)throw Error(`NetInput - tf.Tensor4D with batchSize `+r+` passed, but not supported in input array`);n._imageTensors[t]=e,n._inputDimensions[t]=e.shape.slice(1);return}var i=e instanceof hm.getEnv().Canvas?e:Em(e);n._canvases[t]=i,n._inputDimensions[t]=[i.height,i.width,3]})}return Object.defineProperty(e.prototype,`imageTensors`,{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`canvases`,{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`isBatchInput`,{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`batchSize`,{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`inputDimensions`,{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`inputSize`,{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`reshapedInputDimensions`,{get:function(){var e=this;return Np(this.batchSize,0,1).map(function(t,n){return e.getReshapedInputDimensions(n)})},enumerable:!0,configurable:!0}),e.prototype.getInput=function(e){return this.canvases[e]||this.imageTensors[e]},e.prototype.getInputDimensions=function(e){return this._inputDimensions[e]},e.prototype.getInputHeight=function(e){return this._inputDimensions[e][0]},e.prototype.getInputWidth=function(e){return this._inputDimensions[e][1]},e.prototype.getReshapedInputDimensions=function(e){if(typeof this.inputSize!=`number`)throw Error(`getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet`);return jp({width:this.getInputWidth(e),height:this.getInputHeight(e)},this.inputSize)},e.prototype.toBatchTensor=function(e,t){var n=this;return t===void 0&&(t=!0),this._inputSize=e,W(function(){return Ur(Np(n.batchSize,0,1).map(function(r){var i=n.getInput(r);if(i instanceof $e){var a=Ep(i)?i:i.expandDims();return a=Gp(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Ad.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof hm.getEnv().Canvas)return ep.fromPixels(km(i,e,t));throw Error(`toBatchTensor - at batchIdx `+r+`, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have `+i)}).map(function(e){return e.toFloat()})).as4D(n.batchSize,e,e,3)})},e}();function jm(e){return Q(this,void 0,void 0,function(){var t,n,r;return $(this,function(i){switch(i.label){case 0:if(e instanceof Am)return[2,e];if(t=Array.isArray(e)?e:[e],!t.length)throw Error(`toNetInput - empty array passed as input`);return n=function(t){return Array.isArray(e)?` at input index `+t+`:`:``},r=t.map(gm),r.forEach(function(e,r){if(!Om(e)&&!Tp(e)&&!Ep(e))throw typeof t[r]==`string`?Error(`toNetInput -`+n(r)+` string passed, but could not resolve HTMLElement for element id `+t[r]):Error(`toNetInput -`+n(r)+` expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Ep(e)){var i=e.shape[0];if(i!==1)throw Error(`toNetInput -`+n(r)+` tf.Tensor4D with batchSize `+i+` passed, but not supported in input array`)}}),[4,Promise.all(r.map(function(e){return Om(e)&&Cm(e)}))];case 1:return i.sent(),[2,new Am(r,Array.isArray(e))]}})})}function Mm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c;return $(this,function(l){switch(l.label){case 0:return n=hm.getEnv().Canvas,r=e,e instanceof n?[3,5]:[4,jm(e)];case 1:if(i=l.sent(),i.batchSize>1)throw Error(`extractFaces - batchSize > 1 not supported`);return a=i.getInput(0),a instanceof n?(o=a,[3,4]):[3,2];case 2:return[4,Dm(a)];case 3:o=l.sent(),l.label=4;case 4:r=o,l.label=5;case 5:return s=_m(r),c=t.map(function(e){return e instanceof Bp?e.forSize(r.width,r.height).box.floor():e}).map(function(e){return e.clipAtImageBorders(r.width,r.height)}),[2,c.map(function(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Tm({width:r,height:i});return _m(a).putImageData(s.getImageData(t,n,r,i),0,0),a})]}})})}function Nm(e,t){return Q(this,void 0,void 0,function(){return $(this,function(n){if(!Tp(e)&&!Ep(e))throw Error(`extractFaceTensors - expected image tensor to be 3D or 4D`);if(Ep(e)&&e.shape[0]>1)throw Error(`extractFaceTensors - batchSize > 1 not supported`);return[2,W(function(){var n=e.shape.slice(Ep(e)?1:0),r=n[0],i=n[1],a=n[2];return t.map(function(e){return e instanceof Bp?e.forSize(i,r).box:e}).map(function(e){return e.clipAtImageBorders(i,r)}).map(function(t){var n=t.x,o=t.y,s=t.width,c=t.height;return hu(e.as3D(r,i,a),[o,n,0],[c,s,a])})})]})})}function Pm(e,t){return Q(this,void 0,void 0,function(){var n,r;return $(this,function(i){switch(i.label){case 0:return n=hm.getEnv().fetch,[4,n(e,t)];case 1:if(r=i.sent(),!(r.status<400))throw Error(`failed to fetch: (`+r.status+`) `+r.statusText+`, from url: `+r.url);return[2,r]}})})}function Fm(e){return Q(this,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,Pm(e)];case 1:return[2,t.sent().json()]}})})}function Im(e,t){var n=t+`-weights_manifest.json`;if(!e)return{modelBaseUri:``,manifestUri:n};if(e===`/`)return{modelBaseUri:`/`,manifestUri:`/`+n};var r=e.startsWith(`http://`)?`http://`:e.startsWith(`https://`)?`https://`:``;e=e.replace(r,``);var i=e.split(`/`).filter(function(e){return e}),a=e.endsWith(`.json`)?i[i.length-1]:n,o=r+(e.endsWith(`.json`)?i.slice(0,i.length-1):i).join(`/`);return o=e.startsWith(`/`)?`/`+o:o,{modelBaseUri:o,manifestUri:o===`/`?`/`+a:o+`/`+a}}function Lm(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a;return $(this,function(o){switch(o.label){case 0:return n=Im(e,t),r=n.manifestUri,i=n.modelBaseUri,[4,Fm(r)];case 1:return a=o.sent(),[2,Xf.loadWeights(a,i)]}})})}var Rm=function(){function e(e){this._name=e,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(e.prototype,`params`,{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`paramMappings`,{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`isLoaded`,{get:function(){return!!this.params},enumerable:!0,configurable:!0}),e.prototype.getParamFromPath=function(e){var t=this.traversePropertyPath(e);return t.obj[t.objProp]},e.prototype.reassignParamFromPath=function(e,t){var n=this.traversePropertyPath(e),r=n.obj,i=n.objProp;r[i].dispose(),r[i]=t},e.prototype.getParamList=function(){var e=this;return this._paramMappings.map(function(t){var n=t.paramPath;return{path:n,tensor:e.getParamFromPath(n)}})},e.prototype.getTrainableParams=function(){return this.getParamList().filter(function(e){return e.tensor instanceof at})},e.prototype.getFrozenParams=function(){return this.getParamList().filter(function(e){return!(e.tensor instanceof at)})},e.prototype.variable=function(){var e=this;this.getFrozenParams().forEach(function(t){var n=t.path,r=t.tensor;e.reassignParamFromPath(n,r.variable())})},e.prototype.freeze=function(){var e=this;this.getTrainableParams().forEach(function(t){var n=t.path,r=t.tensor,i=Bn(r.dataSync());r.dispose(),e.reassignParamFromPath(n,i)})},e.prototype.dispose=function(e){e===void 0&&(e=!0),this.getParamList().forEach(function(t){if(e&&t.tensor.isDisposed)throw Error(`param tensor has already been disposed for path `+t.path);t.tensor.dispose()}),this._params=void 0},e.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map(function(e){var t=e.tensor;return Array.from(t.dataSync())}).reduce(function(e,t){return e.concat(t)}))},e.prototype.load=function(e){return Q(this,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return e instanceof Float32Array?(this.extractWeights(e),[2]):[4,this.loadFromUri(e)];case 1:return t.sent(),[2]}})})},e.prototype.loadFromUri=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:if(e&&typeof e!=`string`)throw Error(this._name+`.loadFromUri - expected model uri`);return[4,Lm(e,this.getDefaultModelName())];case 1:return t=n.sent(),this.loadFromWeightMap(t),[2]}})})},e.prototype.loadFromDisk=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a,o,s,c,l,u;return $(this,function(d){switch(d.label){case 0:if(e&&typeof e!=`string`)throw Error(this._name+`.loadFromDisk - expected model file path`);return t=hm.getEnv().readFile,n=Im(e,this.getDefaultModelName()),r=n.manifestUri,i=n.modelBaseUri,a=function(e){return Promise.all(e.map(function(e){return t(e).then(function(e){return e.buffer})}))},o=Xf.weightsLoaderFactory(a),l=(c=JSON).parse,[4,t(r)];case 1:return s=l.apply(c,[d.sent().toString()]),[4,o(s,i)];case 2:return u=d.sent(),this.loadFromWeightMap(u),[2]}})})},e.prototype.loadFromWeightMap=function(e){var t=this.extractParamsFromWeigthMap(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.extractWeights=function(e){var t=this.extractParams(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.traversePropertyPath=function(e){if(!this.params)throw Error(`traversePropertyPath - model has no loaded params`);var t=e.split(`/`).reduce(function(t,n){if(!t.nextObj.hasOwnProperty(n))throw Error(`traversePropertyPath - object does not have property `+n+`, for path `+e);return{obj:t.nextObj,objProp:n,nextObj:t.nextObj[n]}},{nextObj:this.params}),n=t.obj,r=t.objProp;if(!n||!r||!(n[r]instanceof $e))throw Error(`traversePropertyPath - parameter is not a tensor, for path `+e);return{obj:n,objProp:r}},e}();function zm(e,t,n){return W(function(){var r=Jl(e,t.depthwise_filter,t.pointwise_filter,n,`same`);return r=$c(r,t.bias),r})}function Bm(e,t,n){return n===void 0&&(n=!1),W(function(){var r=Mu(n?$c(Vl(e,t.conv0.filters,[2,2],`same`),t.conv0.bias):zm(e,t.conv0,[2,2])),i=zm(r,t.conv1,[1,1]);return Mu($c(r,$c(i,zm(Mu($c(r,i)),t.conv2,[1,1]))))})}function Vm(e,t,n,r){return n===void 0&&(n=!1),r===void 0&&(r=!0),W(function(){var i=Mu(n?$c(Vl(e,t.conv0.filters,r?[2,2]:[1,1],`same`),t.conv0.bias):zm(e,t.conv0,r?[2,2]:[1,1])),a=zm(i,t.conv1,[1,1]),o=zm(Mu($c(i,a)),t.conv2,[1,1]);return Mu($c(i,$c(a,$c(o,zm(Mu($c(i,$c(a,o))),t.conv3,[1,1])))))})}function Hm(e,t,n,r){return n===void 0&&(n=`same`),r===void 0&&(r=!1),W(function(){var i=$c(Vl(e,t.filters,[1,1],n),t.bias);return r?Mu(i):i})}function Um(e,t){Object.keys(e).forEach(function(n){t.some(function(e){return e.originalPath===n})||e[n].dispose()})}function Wm(e,t){return function(n,r,i,a){var o=Gn(e(n*r*i*i),[i,i,n,r]),s=Hn(e(r));return t.push({paramPath:a+`/filters`},{paramPath:a+`/bias`}),{filters:o,bias:s}}}function Gm(e,t){return function(n,r,i){var a=Un(e(n*r),[n,r]),o=Hn(e(r));return t.push({paramPath:i+`/weights`},{paramPath:i+`/bias`}),{weights:a,bias:o}}}var Km=function(){function e(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}return e}();function qm(e,t){return function(n,r,i){var a=Gn(e(9*n),[3,3,n,1]),o=Gn(e(n*r),[1,1,n,r]),s=Hn(e(r));return t.push({paramPath:i+`/depthwise_filter`},{paramPath:i+`/pointwise_filter`},{paramPath:i+`/bias`}),new Km(a,o,s)}}function Jm(e){return function(t){return new Km(e(t+`/depthwise_filter`,4),e(t+`/pointwise_filter`,4),e(t+`/bias`,1))}}function Ym(e,t){return function(n,r,i){var a=e[n];if(!Cp(a,r))throw Error(`expected weightMap[`+n+`] to be a Tensor`+r+`D, instead have `+a);return t.push({originalPath:n,paramPath:i||n}),a}}function Xm(e){var t=e;function n(e){var n=t.slice(0,e);return t=t.slice(e),n}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}function Zm(e,t){var n=Wm(e,t),r=qm(e,t);function i(e,t,i,a){return a===void 0&&(a=!1),{conv0:a?n(e,t,3,i+`/conv0`):r(e,t,i+`/conv0`),conv1:r(t,t,i+`/conv1`),conv2:r(t,t,i+`/conv2`)}}function a(e,t,n,a){a===void 0&&(a=!1);var o=i(e,t,n,a);return{conv0:o.conv0,conv1:o.conv1,conv2:o.conv2,conv3:r(t,t,n+`/conv3`)}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function Qm(e){var t=[],n=Xm(e),r=n.extractWeights,i=n.getRemainingWeights,a=Zm(r,t).extractDenseBlock4Params,o=a(3,32,`dense0`,!0),s=a(32,64,`dense1`),c=a(64,128,`dense2`),l=a(128,256,`dense3`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{dense0:o,dense1:s,dense2:c,dense3:l}}}function $m(e){return function(t){return{filters:e(t+`/filters`,4),bias:e(t+`/bias`,1)}}}function eh(e,t){var n=Ym(e,t),r=$m(n),i=Jm(n);function a(e,t){return t===void 0&&(t=!1),{conv0:t?r(e+`/conv0`):i(e+`/conv0`),conv1:i(e+`/conv1`),conv2:i(e+`/conv2`)}}function o(e,t){return t===void 0&&(t=!1),{conv0:t?r(e+`/conv0`):i(e+`/conv0`),conv1:i(e+`/conv1`),conv2:i(e+`/conv2`),conv3:i(e+`/conv3`)}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:o}}function th(e){var t=[],n=eh(e,t).extractDenseBlock4Params,r={dense0:n(`dense0`,!0),dense1:n(`dense1`),dense2:n(`dense2`),dense3:n(`dense3`)};return Um(e,t),{params:r,paramMappings:t}}var nh=function(e){Z(t,e);function t(){return e.call(this,`FaceFeatureExtractor`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`FaceFeatureExtractor - load model before inference`);return W(function(){var n=Vm(Wp(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(q(255)),t.dense0,!0);return n=Vm(n,t.dense1),n=Vm(n,t.dense2),n=Vm(n,t.dense3),n=cu(n,[7,7],[2,2],`valid`),n})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`face_feature_extractor_model`},t.prototype.extractParamsFromWeigthMap=function(e){return th(e)},t.prototype.extractParams=function(e){return Qm(e)},t}(Rm);function rh(e,t){return W(function(){return $c(Zl(e,t.weights),t.bias)})}function ih(e,t,n){var r=[],i=Xm(e),a=i.extractWeights,o=i.getRemainingWeights,s=Gm(a,r)(t,n,`fc`);if(o().length!==0)throw Error(`weights remaing after extract: `+o().length);return{paramMappings:r,params:{fc:s}}}function ah(e){var t=[],n=Ym(e,t);function r(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}var i={fc:r(`fc`)};return Um(e,t),{params:i,paramMappings:t}}function oh(e){var t={},n={};return Object.keys(e).forEach(function(r){var i=r.startsWith(`fc`)?n:t;i[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}var sh=function(e){Z(t,e);function t(t,n){var r=e.call(this,t)||this;return r._faceFeatureExtractor=n,r}return Object.defineProperty(t.prototype,`faceFeatureExtractor`,{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw Error(this._name+` - load model before inference`);return W(function(){var r=e instanceof Am?t.faceFeatureExtractor.forwardInput(e):e;return rh(r.as2D(r.shape[0],-1),n.fc)})},t.prototype.dispose=function(t){t===void 0&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return ih(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},t.prototype.extractParamsFromWeigthMap=function(e){var t=oh(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),ah(r)},t.prototype.extractParams=function(e){var t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,i=e.slice(0,e.length-r),a=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(a)},t}(Rm),ch=[`neutral`,`happy`,`sad`,`angry`,`fearful`,`disgusted`,`surprised`],lh=function(){function e(e){var t=this;if(e.length!==7)throw Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: `+e.length);ch.forEach(function(n,r){t[n]=e[r]})}return e.prototype.asSortedArray=function(){var e=this;return ch.map(function(t){return{expression:t,probability:e[t]}}).sort(function(e,t){return t.probability-e.probability})},e}(),uh=function(e){Z(t,e);function t(t){return t===void 0&&(t=new nh),e.call(this,`FaceExpressionNet`,t)||this}return t.prototype.forwardInput=function(e){var t=this;return W(function(){return mi(t.runNet(e))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.predictExpressions=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a=this;return $(this,function(o){switch(o.label){case 0:return[4,jm(e)];case 1:return t=o.sent(),[4,this.forwardInput(t)];case 2:return n=o.sent(),[4,Promise.all(Kr(n).map(function(e){return Q(a,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return[4,e.data()];case 1:return t=n.sent(),e.dispose(),[2,t]}})})}))];case 3:return r=o.sent(),n.dispose(),i=r.map(function(e){return new lh(e)}),[2,t.isBatchInput?i:i[0]]}})})},t.prototype.getDefaultModelName=function(){return`face_expression_model`},t.prototype.getClassifierChannelsIn=function(){return 256},t.prototype.getClassifierChannelsOut=function(){return 7},t}(sh);function dh(e,t){return Object.assign({},e,{expressions:t})}function fh(e){return rm(e)&&e.landmarks instanceof Zp&&e.unshiftedLandmarks instanceof Zp&&e.alignedRect instanceof Bp}function ph(e,t){var n=e.detection.box,r=t.shiftBy(n.x,n.y),i=r.align(),a=e.detection.imageDims,o={landmarks:r,unshiftedLandmarks:t,alignedRect:new Bp(e.detection.score,i.rescale(a.reverse()),a)};return Object.assign({},e,o)}var mh=function(){function e(e){e===void 0&&(e={});var t=e.drawLines,n=t===void 0?!0:t,r=e.drawPoints,i=r===void 0?!0:r,a=e.lineWidth,o=e.lineColor,s=e.pointSize,c=e.pointColor;this.drawLines=n,this.drawPoints=i,this.lineWidth=a||1,this.pointSize=s||2,this.lineColor=o||`rgba(0, 255, 255, 1)`,this.pointColor=c||`rgba(255, 0, 255, 1)`}return e}();(function(){function e(e,t){t===void 0&&(t={}),this.faceLandmarks=e,this.options=new mh(t)}return e.prototype.draw=function(e){var t=_m(e),n=this.options,r=n.drawLines,i=n.drawPoints,a=n.lineWidth,o=n.lineColor,s=n.pointSize,c=n.pointColor;r&&this.faceLandmarks instanceof $p&&(t.strokeStyle=o,t.lineWidth=a,vp(t,this.faceLandmarks.getJawOutline()),vp(t,this.faceLandmarks.getLeftEyeBrow()),vp(t,this.faceLandmarks.getRightEyeBrow()),vp(t,this.faceLandmarks.getNose()),vp(t,this.faceLandmarks.getLeftEye(),!0),vp(t,this.faceLandmarks.getRightEye(),!0),vp(t,this.faceLandmarks.getMouth(),!0)),i&&(t.strokeStyle=c,t.fillStyle=c,this.faceLandmarks.positions.forEach(function(e){t.beginPath(),t.arc(e.x,e.y,s,0,2*Math.PI),t.fill()}))},e})();function hh(e,t){var n=Wm(e,t),r=qm(e,t);function i(e,t,i){return{separable_conv0:r(e,t,i+`/separable_conv0`),separable_conv1:r(t,t,i+`/separable_conv1`),expansion_conv:n(e,t,1,i+`/expansion_conv`)}}function a(e,t){return{separable_conv0:r(e,e,t+`/separable_conv0`),separable_conv1:r(e,e,t+`/separable_conv1`),separable_conv2:r(e,e,t+`/separable_conv2`)}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:i,extractMainBlockParams:a}}function gh(e,t){var n=[],r=Xm(e),i=r.extractWeights,a=r.getRemainingWeights,o=hh(i,n),s=o.extractConvParams,c=o.extractSeparableConvParams,l=o.extractReductionBlockParams,u=o.extractMainBlockParams,d={conv_in:s(3,32,3,`entry_flow/conv_in`),reduction_block_0:l(32,64,`entry_flow/reduction_block_0`),reduction_block_1:l(64,128,`entry_flow/reduction_block_1`)},f={};Np(t,0,1).forEach(function(e){f[`main_block_`+e]=u(128,`middle_flow/main_block_`+e)});var p={reduction_block:l(128,256,`exit_flow/reduction_block`),separable_conv:c(256,512,`exit_flow/separable_conv`)};if(a().length!==0)throw Error(`weights remaing after extract: `+a().length);return{paramMappings:n,params:{entry_flow:d,middle_flow:f,exit_flow:p}}}function _h(e,t){var n=Ym(e,t),r=$m(n),i=Jm(n);function a(e){return{separable_conv0:i(e+`/separable_conv0`),separable_conv1:i(e+`/separable_conv1`),expansion_conv:r(e+`/expansion_conv`)}}function o(e){return{separable_conv0:i(e+`/separable_conv0`),separable_conv1:i(e+`/separable_conv1`),separable_conv2:i(e+`/separable_conv2`)}}return{extractConvParams:r,extractSeparableConvParams:i,extractReductionBlockParams:a,extractMainBlockParams:o}}function vh(e,t){var n=[],r=_h(e,n),i=r.extractConvParams,a=r.extractSeparableConvParams,o=r.extractReductionBlockParams,s=r.extractMainBlockParams,c={conv_in:i(`entry_flow/conv_in`),reduction_block_0:o(`entry_flow/reduction_block_0`),reduction_block_1:o(`entry_flow/reduction_block_1`)},l={};Np(t,0,1).forEach(function(e){l[`main_block_`+e]=s(`middle_flow/main_block_`+e)});var u={reduction_block:o(`exit_flow/reduction_block`),separable_conv:a(`exit_flow/separable_conv`)};return Um(e,n),{params:{entry_flow:c,middle_flow:l,exit_flow:u},paramMappings:n}}function yh(e,t,n){return $c(Vl(e,t.filters,n,`same`),t.bias)}function bh(e,t,n){n===void 0&&(n=!0);var r=n?Mu(e):e;return r=zm(r,t.separable_conv0,[1,1]),r=zm(Mu(r),t.separable_conv1,[1,1]),r=su(r,[3,3],[2,2],`same`),r=$c(r,yh(e,t.expansion_conv,[2,2])),r}function xh(e,t){var n=zm(Mu(e),t.separable_conv0,[1,1]);return n=zm(Mu(n),t.separable_conv1,[1,1]),n=zm(Mu(n),t.separable_conv2,[1,1]),n=$c(n,e),n}var Sh=function(e){Z(t,e);function t(t){var n=e.call(this,`TinyXception`)||this;return n._numMainBlocks=t,n}return t.prototype.forwardInput=function(e){var t=this,n=this.params;if(!n)throw Error(`TinyXception - load model before inference`);return W(function(){var r=Mu(yh(Wp(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(q(256)),n.entry_flow.conv_in,[2,2]));return r=bh(r,n.entry_flow.reduction_block_0,!1),r=bh(r,n.entry_flow.reduction_block_1),Np(t._numMainBlocks,0,1).forEach(function(e){r=xh(r,n.middle_flow[`main_block_`+e])}),r=bh(r,n.exit_flow.reduction_block),r=Mu(zm(r,n.exit_flow.separable_conv,[1,1])),r})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`tiny_xception_model`},t.prototype.extractParamsFromWeigthMap=function(e){return vh(e,this._numMainBlocks)},t.prototype.extractParams=function(e){return gh(e,this._numMainBlocks)},t}(Rm);function Ch(e){var t=[],n=Xm(e),r=n.extractWeights,i=n.getRemainingWeights,a=Gm(r,t),o=a(512,1,`fc/age`),s=a(512,2,`fc/gender`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{fc:{age:o,gender:s}}}}function wh(e){var t=[],n=Ym(e,t);function r(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}var i={fc:{age:r(`fc/age`),gender:r(`fc/gender`)}};return Um(e,t),{params:i,paramMappings:t}}var Th;(function(e){e.FEMALE=`female`,e.MALE=`male`})(Th||={});var Eh=function(e){Z(t,e);function t(t){t===void 0&&(t=new Sh(2));var n=e.call(this,`AgeGenderNet`)||this;return n._faceFeatureExtractor=t,n}return Object.defineProperty(t.prototype,`faceFeatureExtractor`,{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw Error(this._name+` - load model before inference`);return W(function(){var r=e instanceof Am?t.faceFeatureExtractor.forwardInput(e):e,i=cu(r,[7,7],[2,2],`valid`).as2D(r.shape[0],-1);return{age:rh(i,n.fc.age).as1D(),gender:rh(i,n.fc.gender)}})},t.prototype.forwardInput=function(e){var t=this;return W(function(){var n=t.runNet(e),r=n.age,i=n.gender;return{age:r,gender:mi(i)}})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.predictAgeAndGender=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i,a,o,s=this;return $(this,function(c){switch(c.label){case 0:return[4,jm(e)];case 1:return t=c.sent(),[4,this.forwardInput(t)];case 2:return n=c.sent(),r=Kr(n.age),i=Kr(n.gender),a=r.map(function(e,t){return{ageTensor:e,genderTensor:i[t]}}),[4,Promise.all(a.map(function(e){var t=e.ageTensor,n=e.genderTensor;return Q(s,void 0,void 0,function(){var e,r,i,a,o;return $(this,function(s){switch(s.label){case 0:return[4,t.data()];case 1:return e=s.sent()[0],[4,n.data()];case 2:return r=s.sent()[0],i=r>.5,a=i?Th.MALE:Th.FEMALE,o=i?r:1-r,t.dispose(),n.dispose(),[2,{age:e,gender:a,genderProbability:o}]}})})}))];case 3:return o=c.sent(),n.age.dispose(),n.gender.dispose(),[2,t.isBatchInput?o:o[0]]}})})},t.prototype.getDefaultModelName=function(){return`age_gender_model`},t.prototype.dispose=function(t){t===void 0&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return Ch(e)},t.prototype.extractParamsFromWeigthMap=function(e){var t=oh(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),wh(r)},t.prototype.extractParams=function(e){var t=1539,n=e.slice(0,e.length-t),r=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(r)},t}(Rm),Dh=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.postProcess=function(e,t,n){var r=n.map(function(e){var n=e.width,r=e.height,i=t/Math.max(r,n);return{width:n*i,height:r*i}}),i=r.length;return W(function(){var n=function(e,t){return Ur([Zn([68],e),Zn([68],t)],1).as2D(1,136).as1D()},a=function(e,t){var n=r[e],i=n.width,a=n.height;return t(i,a)?Math.abs(i-a)/2:0},o=function(e){return a(e,function(e,t){return e<t})},s=function(e){return a(e,function(e,t){return t<e})};return e.mul(Zn([i,136],t)).sub(Ur(Array.from(Array(i),function(e,t){return n(o(t),s(t))}))).div(Ur(Array.from(Array(i),function(e,t){return n(r[t].width,r[t].height)})))})},t.prototype.forwardInput=function(e){var t=this;return W(function(){var n=t.runNet(e);return t.postProcess(n,e.inputSize,e.inputDimensions.map(function(e){return{height:e[0],width:e[1]}}))})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.detectLandmarks=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i=this;return $(this,function(a){switch(a.label){case 0:return[4,jm(e)];case 1:return t=a.sent(),n=W(function(){return Kr(i.forwardInput(t))}),[4,Promise.all(n.map(function(e,n){return Q(i,void 0,void 0,function(){var r,i,a,o,s;return $(this,function(c){switch(c.label){case 0:return a=(i=Array).from,[4,e.data()];case 1:return r=a.apply(i,[c.sent()]),o=r.filter(function(e,t){return Op(t)}),s=r.filter(function(e,t){return!Op(t)}),[2,new $p(Array(68).fill(0).map(function(e,t){return new Ip(o[t],s[t])}),{height:t.getInputHeight(n),width:t.getInputWidth(n)})]}})})}))];case 2:return r=a.sent(),n.forEach(function(e){return e.dispose()}),[2,t.isBatchInput?r:r[0]]}})})},t.prototype.getClassifierChannelsOut=function(){return 136},t}(sh),Oh=function(e){Z(t,e);function t(t){return t===void 0&&(t=new nh),e.call(this,`FaceLandmark68Net`,t)||this}return t.prototype.getDefaultModelName=function(){return`face_landmark_68_model`},t.prototype.getClassifierChannelsIn=function(){return 256},t}(Dh);function kh(e){var t=[],n=eh(e,t).extractDenseBlock3Params,r={dense0:n(`dense0`,!0),dense1:n(`dense1`),dense2:n(`dense2`)};return Um(e,t),{params:r,paramMappings:t}}function Ah(e){var t=[],n=Xm(e),r=n.extractWeights,i=n.getRemainingWeights,a=Zm(r,t).extractDenseBlock3Params,o=a(3,32,`dense0`,!0),s=a(32,64,`dense1`),c=a(64,128,`dense2`);if(i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{paramMappings:t,params:{dense0:o,dense1:s,dense2:c}}}var jh=function(e){Z(t,e);function t(){return e.call(this,`TinyFaceFeatureExtractor`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`TinyFaceFeatureExtractor - load model before inference`);return W(function(){var n=Bm(Wp(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(q(255)),t.dense0,!0);return n=Bm(n,t.dense1),n=Bm(n,t.dense2),n=cu(n,[14,14],[2,2],`valid`),n})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.getDefaultModelName=function(){return`face_feature_extractor_tiny_model`},t.prototype.extractParamsFromWeigthMap=function(e){return kh(e)},t.prototype.extractParams=function(e){return Ah(e)},t}(Rm),Mh=function(e){Z(t,e);function t(t){return t===void 0&&(t=new jh),e.call(this,`FaceLandmark68TinyNet`,t)||this}return t.prototype.getDefaultModelName=function(){return`face_landmark_68_tiny_model`},t.prototype.getClassifierChannelsIn=function(){return 128},t}(Dh);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Oh);function Nh(e,t){return $c(pl(e,t.weights),t.biases)}function Ph(e,t,n,r,i){i===void 0&&(i=`same`);var a=t.conv,o=a.filters,s=a.bias,c=Vl(e,o,n,i);return c=$c(c,s),c=Nh(c,t.scale),r?Mu(c):c}function Fh(e,t){return Ph(e,t,[1,1],!0)}function Ih(e,t){return Ph(e,t,[1,1],!1)}function Lh(e,t){return Ph(e,t,[2,2],!0,`valid`)}function Rh(e,t){function n(t,n,r){var i=e(t),a=i.length/(n*r*r);if(Dp(a))throw Error(`depth has to be an integer: `+a+`, weights.length: `+i.length+`, numFilters: `+n+`, filterSize: `+r);return W(function(){return Fu(Gn(i,[n,a,r,r]),[2,3,1,0])})}function r(r,i,a,o){var s=n(r,i,a),c=Hn(e(i));return t.push({paramPath:o+`/filters`},{paramPath:o+`/bias`}),{filters:s,bias:c}}function i(n,r){var i=Hn(e(n)),a=Hn(e(n));return t.push({paramPath:r+`/weights`},{paramPath:r+`/biases`}),{weights:i,biases:a}}function a(e,t,n,a){return{conv:r(e,t,n,a+`/conv`),scale:i(t,a+`/scale`)}}function o(e,t,n,r,i){return i===void 0&&(i=!1),{conv1:a((i?.5:1)*e,t,n,r+`/conv1`),conv2:a(e,t,n,r+`/conv2`)}}return{extractConvLayerParams:a,extractResidualLayerParams:o}}function zh(e){var t=Xm(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],a=Rh(n,i),o=a.extractConvLayerParams,s=a.extractResidualLayerParams,c=o(4704,32,7,`conv32_down`),l=s(9216,32,3,`conv32_1`),u=s(9216,32,3,`conv32_2`),d=s(9216,32,3,`conv32_3`),f=s(36864,64,3,`conv64_down`,!0),p=s(36864,64,3,`conv64_1`),m=s(36864,64,3,`conv64_2`),h=s(36864,64,3,`conv64_3`),g=s(147456,128,3,`conv128_down`,!0),_=s(147456,128,3,`conv128_1`),v=s(147456,128,3,`conv128_2`),y=s(589824,256,3,`conv256_down`,!0),b=s(589824,256,3,`conv256_1`),x=s(589824,256,3,`conv256_2`),S=s(589824,256,3,`conv256_down_out`),C=W(function(){return Fu(Un(n(256*128),[128,256]),[1,0])});if(i.push({paramPath:`fc`}),r().length!==0)throw Error(`weights remaing after extract: `+r().length);return{params:{conv32_down:c,conv32_1:l,conv32_2:u,conv32_3:d,conv64_down:f,conv64_1:p,conv64_2:m,conv64_3:h,conv128_down:g,conv128_1:_,conv128_2:v,conv256_down:y,conv256_1:b,conv256_2:x,conv256_down_out:S,fc:C},paramMappings:i}}function Bh(e,t){var n=Ym(e,t);function r(e){return{weights:n(e+`/scale/weights`,1),biases:n(e+`/scale/biases`,1)}}function i(e){var t=n(e+`/conv/filters`,4),i=n(e+`/conv/bias`,1),a=r(e);return{conv:{filters:t,bias:i},scale:a}}function a(e){return{conv1:i(e+`/conv1`),conv2:i(e+`/conv2`)}}return{extractConvLayerParams:i,extractResidualLayerParams:a}}function Vh(e){var t=[],n=Bh(e,t),r=n.extractConvLayerParams,i=n.extractResidualLayerParams,a=r(`conv32_down`),o=i(`conv32_1`),s=i(`conv32_2`),c=i(`conv32_3`),l=i(`conv64_down`),u=i(`conv64_1`),d=i(`conv64_2`),f=i(`conv64_3`),p=i(`conv128_down`),m=i(`conv128_1`),h=i(`conv128_2`),g=i(`conv256_down`),_=i(`conv256_1`),v=i(`conv256_2`),y=i(`conv256_down_out`),b=e.fc;if(t.push({originalPath:`fc`,paramPath:`fc`}),!wp(b))throw Error(`expected weightMap[fc] to be a Tensor2D, instead have `+b);var x={conv32_down:a,conv32_1:o,conv32_2:s,conv32_3:c,conv64_down:l,conv64_1:u,conv64_2:d,conv64_3:f,conv128_down:p,conv128_1:m,conv128_2:h,conv256_down:g,conv256_1:_,conv256_2:v,conv256_down_out:y,fc:b};return Um(e,t),{params:x,paramMappings:t}}function Hh(e,t){var n=Fh(e,t.conv1);return n=Ih(n,t.conv2),n=$c(n,e),n=Mu(n),n}function Uh(e,t){var n=Lh(e,t.conv1);n=Ih(n,t.conv2);var r=cu(e,2,2,`valid`),i=Xn(r.shape),a=r.shape[3]!==n.shape[3];if(r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2]){var o=xp(n.shape);o[1]=1;var s=Xn(o);n=nr([n,s],1);var c=xp(n.shape);c[2]=1;var l=Xn(c);n=nr([n,l],2)}return r=a?nr([r,i],3):r,n=$c(r,n),n=Mu(n),n}var Wh=function(e){Z(t,e);function t(){return e.call(this,`FaceRecognitionNet`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`FaceRecognitionNet - load model before inference`);return W(function(){var n=Lh(Wp(e.toBatchTensor(150,!0).toFloat(),[122.782,117.001,104.298]).div(q(256)),t.conv32_down);return n=su(n,3,2,`valid`),n=Hh(n,t.conv32_1),n=Hh(n,t.conv32_2),n=Hh(n,t.conv32_3),n=Uh(n,t.conv64_down),n=Hh(n,t.conv64_1),n=Hh(n,t.conv64_2),n=Hh(n,t.conv64_3),n=Uh(n,t.conv128_down),n=Hh(n,t.conv128_1),n=Hh(n,t.conv128_2),n=Uh(n,t.conv256_down),n=Hh(n,t.conv256_1),n=Hh(n,t.conv256_2),n=Uh(n,t.conv256_down_out),Zl(n.mean([1,2]),t.fc)})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.computeFaceDescriptor=function(e){return Q(this,void 0,void 0,function(){var t,n,r,i=this;return $(this,function(a){switch(a.label){case 0:return[4,jm(e)];case 1:return t=a.sent(),n=W(function(){return Kr(i.forwardInput(t))}),[4,Promise.all(n.map(function(e){return e.data()}))];case 2:return r=a.sent(),n.forEach(function(e){return e.dispose()}),[2,t.isBatchInput?r:r[0]]}})})},t.prototype.getDefaultModelName=function(){return`face_recognition_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Vh(e)},t.prototype.extractParams=function(e){return zh(e)},t}(Rm);function Gh(e,t){return Object.assign({},e,{descriptor:t})}function Kh(e,t){return Object.assign({},e,{age:t})}function qh(e,t,n){return Object.assign({},e,{gender:t,genderProbability:n})}var Jh=function(){function e(e){var t=e===void 0?{}:e,n=t.minFaceSize,r=t.scaleFactor,i=t.maxNumScales,a=t.scoreThresholds,o=t.scaleSteps;if(this._name=`MtcnnOptions`,this._minFaceSize=n||20,this._scaleFactor=r||.709,this._maxNumScales=i||10,this._scoreThresholds=a||[.6,.7,.7],this._scaleSteps=o,typeof this._minFaceSize!=`number`||this._minFaceSize<0)throw Error(this._name+` - expected minFaceSize to be a number > 0`);if(typeof this._scaleFactor!=`number`||this._scaleFactor<=0||this._scaleFactor>=1)throw Error(this._name+` - expected scaleFactor to be a number between 0 and 1`);if(typeof this._maxNumScales!=`number`||this._maxNumScales<0)throw Error(this._name+` - expected maxNumScales to be a number > 0`);if(!Array.isArray(this._scoreThresholds)||this._scoreThresholds.length!==3||this._scoreThresholds.some(function(e){return typeof e!=`number`}))throw Error(this._name+` - expected scoreThresholds to be an array of numbers of length 3`);if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some(function(e){return typeof e!=`number`})))throw Error(this._name+` - expected scaleSteps to be an array of numbers`)}return Object.defineProperty(e.prototype,`minFaceSize`,{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scaleFactor`,{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`maxNumScales`,{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scoreThresholds`,{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scaleSteps`,{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),e}();function Yh(e,t){function n(n,r){var i=Gn(e(9*n),[3,3,n,1]),a=Hn(e(n)),o=Hn(e(n)),s=Hn(e(n)),c=Hn(e(n));return t.push({paramPath:r+`/filters`},{paramPath:r+`/batch_norm_scale`},{paramPath:r+`/batch_norm_offset`},{paramPath:r+`/batch_norm_mean`},{paramPath:r+`/batch_norm_variance`}),{filters:i,batch_norm_scale:a,batch_norm_offset:o,batch_norm_mean:s,batch_norm_variance:c}}function r(n,r,i,a,o){var s=Gn(e(n*r*i*i),[i,i,n,r]),c=Hn(e(r));return t.push({paramPath:a+`/filters`},{paramPath:a+`/`+(o?`batch_norm_offset`:`bias`)}),{filters:s,bias:c}}function i(e,t,n,i){var a=r(e,t,n,i,!0);return{filters:a.filters,batch_norm_offset:a.bias}}function a(e,t,r){return{depthwise_conv:n(e,r+`/depthwise_conv`),pointwise_conv:i(e,t,1,r+`/pointwise_conv`)}}function o(){return{conv_0:i(3,32,3,`mobilenetv1/conv_0`),conv_1:a(32,64,`mobilenetv1/conv_1`),conv_2:a(64,128,`mobilenetv1/conv_2`),conv_3:a(128,128,`mobilenetv1/conv_3`),conv_4:a(128,256,`mobilenetv1/conv_4`),conv_5:a(256,256,`mobilenetv1/conv_5`),conv_6:a(256,512,`mobilenetv1/conv_6`),conv_7:a(512,512,`mobilenetv1/conv_7`),conv_8:a(512,512,`mobilenetv1/conv_8`),conv_9:a(512,512,`mobilenetv1/conv_9`),conv_10:a(512,512,`mobilenetv1/conv_10`),conv_11:a(512,512,`mobilenetv1/conv_11`),conv_12:a(512,1024,`mobilenetv1/conv_12`),conv_13:a(1024,1024,`mobilenetv1/conv_13`)}}function s(){var e=i(1024,256,1,`prediction_layer/conv_0`),t=i(256,512,3,`prediction_layer/conv_1`),n=i(512,128,1,`prediction_layer/conv_2`),a=i(128,256,3,`prediction_layer/conv_3`),o=i(256,128,1,`prediction_layer/conv_4`),s=i(128,256,3,`prediction_layer/conv_5`),c=i(256,64,1,`prediction_layer/conv_6`),l=i(64,128,3,`prediction_layer/conv_7`),u=r(512,12,1,`prediction_layer/box_predictor_0/box_encoding_predictor`),d=r(512,9,1,`prediction_layer/box_predictor_0/class_predictor`),f=r(1024,24,1,`prediction_layer/box_predictor_1/box_encoding_predictor`),p=r(1024,18,1,`prediction_layer/box_predictor_1/class_predictor`),m=r(512,24,1,`prediction_layer/box_predictor_2/box_encoding_predictor`),h=r(512,18,1,`prediction_layer/box_predictor_2/class_predictor`),g=r(256,24,1,`prediction_layer/box_predictor_3/box_encoding_predictor`),_=r(256,18,1,`prediction_layer/box_predictor_3/class_predictor`),v=r(256,24,1,`prediction_layer/box_predictor_4/box_encoding_predictor`),y=r(256,18,1,`prediction_layer/box_predictor_4/class_predictor`),b=r(128,24,1,`prediction_layer/box_predictor_5/box_encoding_predictor`),x=r(128,18,1,`prediction_layer/box_predictor_5/class_predictor`);return{conv_0:e,conv_1:t,conv_2:n,conv_3:a,conv_4:o,conv_5:s,conv_6:c,conv_7:l,box_predictor_0:{box_encoding_predictor:u,class_predictor:d},box_predictor_1:{box_encoding_predictor:f,class_predictor:p},box_predictor_2:{box_encoding_predictor:m,class_predictor:h},box_predictor_3:{box_encoding_predictor:g,class_predictor:_},box_predictor_4:{box_encoding_predictor:v,class_predictor:y},box_predictor_5:{box_encoding_predictor:b,class_predictor:x}}}return{extractMobilenetV1Params:o,extractPredictionLayerParams:s}}function Xh(e){var t=[],n=Xm(e),r=n.extractWeights,i=n.getRemainingWeights,a=Yh(r,t),o=a.extractMobilenetV1Params,s=a.extractPredictionLayerParams,c=o(),l=s(),u={extra_dim:Wn(r(5118*4),[1,5118,4])};if(t.push({paramPath:`output_layer/extra_dim`}),i().length!==0)throw Error(`weights remaing after extract: `+i().length);return{params:{mobilenetv1:c,prediction_layer:l,output_layer:u},paramMappings:t}}function Zh(e,t){var n=Ym(e,t);function r(e,t,r){return{filters:n(e+`/Conv2d_`+t+`_pointwise/weights`,4,r+`/filters`),batch_norm_offset:n(e+`/Conv2d_`+t+`_pointwise/convolution_bn_offset`,1,r+`/batch_norm_offset`)}}function i(e){var t=`mobilenetv1/conv_`+e,i=`MobilenetV1/Conv2d_`+e+`_depthwise`,a=t+`/depthwise_conv`,o=t+`/pointwise_conv`;return{depthwise_conv:{filters:n(i+`/depthwise_weights`,4,a+`/filters`),batch_norm_scale:n(i+`/BatchNorm/gamma`,1,a+`/batch_norm_scale`),batch_norm_offset:n(i+`/BatchNorm/beta`,1,a+`/batch_norm_offset`),batch_norm_mean:n(i+`/BatchNorm/moving_mean`,1,a+`/batch_norm_mean`),batch_norm_variance:n(i+`/BatchNorm/moving_variance`,1,a+`/batch_norm_variance`)},pointwise_conv:r(`MobilenetV1`,e,o)}}function a(){return{conv_0:r(`MobilenetV1`,0,`mobilenetv1/conv_0`),conv_1:i(1),conv_2:i(2),conv_3:i(3),conv_4:i(4),conv_5:i(5),conv_6:i(6),conv_7:i(7),conv_8:i(8),conv_9:i(9),conv_10:i(10),conv_11:i(11),conv_12:i(12),conv_13:i(13)}}function o(e,t){return{filters:n(e+`/weights`,4,t+`/filters`),bias:n(e+`/biases`,1,t+`/bias`)}}function s(e){return{box_encoding_predictor:o(`Prediction/BoxPredictor_`+e+`/BoxEncodingPredictor`,`prediction_layer/box_predictor_`+e+`/box_encoding_predictor`),class_predictor:o(`Prediction/BoxPredictor_`+e+`/ClassPredictor`,`prediction_layer/box_predictor_`+e+`/class_predictor`)}}function c(){return{conv_0:r(`Prediction`,0,`prediction_layer/conv_0`),conv_1:r(`Prediction`,1,`prediction_layer/conv_1`),conv_2:r(`Prediction`,2,`prediction_layer/conv_2`),conv_3:r(`Prediction`,3,`prediction_layer/conv_3`),conv_4:r(`Prediction`,4,`prediction_layer/conv_4`),conv_5:r(`Prediction`,5,`prediction_layer/conv_5`),conv_6:r(`Prediction`,6,`prediction_layer/conv_6`),conv_7:r(`Prediction`,7,`prediction_layer/conv_7`),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:c}}function Qh(e){var t=[],n=Zh(e,t),r=n.extractMobilenetV1Params,i=n.extractPredictionLayerParams,a=e[`Output/extra_dim`];if(t.push({originalPath:`Output/extra_dim`,paramPath:`output_layer/extra_dim`}),!Tp(a))throw Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have `+a);var o={mobilenetv1:r(),prediction_layer:i(),output_layer:{extra_dim:a}};return Um(e,t),{params:o,paramMappings:t}}function $h(e,t,n){return W(function(){var r=Vl(e,t.filters,n,`same`);return r=$c(r,t.batch_norm_offset),sc(r,0,6)})}var eg=.0010000000474974513;function tg(e,t,n){return W(function(){var r=Gl(e,t.filters,n,`same`);return r=Uc(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,eg),sc(r,0,6)})}function ng(e){return[2,4,6,12].some(function(t){return t===e})?[2,2]:[1,1]}function rg(e,t){return W(function(){var n=null,r=$h(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach(function(e,t){var i=t+1,a=ng(i);r=tg(r,e.depthwise_conv,a),r=$h(r,e.pointwise_conv,[1,1]),i===11&&(n=r)}),n===null)throw Error(`mobileNetV1 - output of conv layer 11 is null`);return{out:r,conv11:n}})}function ig(e,t,n,r,i){var a=e.shape[0],o=Math.min(n,a),s=t.map(function(e,t){return{score:e,boxIndex:t}}).filter(function(e){return e.score>i}).sort(function(e,t){return t.score-e.score}),c=function(e){return e<=r?1:0},l=[];return s.forEach(function(t){if(!(l.length>=o)){for(var n=t.score,r=l.length-1;r>=0;--r){var a=ag(e,t.boxIndex,l[r]);if(a!==0&&(t.score*=c(a),t.score<=i))break}n===t.score&&l.push(t.boxIndex)}}),l}function ag(e,t,n){var r=e.arraySync(),i=Math.min(r[t][0],r[t][2]),a=Math.min(r[t][1],r[t][3]),o=Math.max(r[t][0],r[t][2]),s=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),l=Math.min(r[n][1],r[n][3]),u=Math.max(r[n][0],r[n][2]),d=Math.max(r[n][1],r[n][3]),f=(o-i)*(s-a),p=(u-c)*(d-l);if(f<=0||p<=0)return 0;var m=Math.max(i,c),h=Math.max(a,l),g=Math.min(o,u),_=Math.min(s,d),v=Math.max(g-m,0)*Math.max(_-h,0);return v/(f+p-v)}function og(e){var t=Kr(Fu(e,[1,0])),n=[vl(t[2],t[0]),vl(t[3],t[1])];return{sizes:n,centers:[$c(t[0],rl(n[0],q(2))),$c(t[1],rl(n[1],q(2)))]}}function sg(e,t){var n=og(e),r=n.sizes,i=n.centers,a=Kr(Fu(t,[1,0])),o=rl(pl(dc(rl(a[2],q(5))),r[0]),q(2)),s=$c(pl(rl(a[0],q(10)),r[0]),i[0]),c=rl(pl(dc(rl(a[3],q(5))),r[1]),q(2)),l=$c(pl(rl(a[1],q(10)),r[1]),i[1]);return Fu(Ur([vl(s,o),vl(l,c),$c(s,o),$c(l,c)]),[1,0])}function cg(e,t,n){return W(function(){var r=e.shape[0],i=sg(Br(Wr(n.extra_dim,[r,1,1]),[-1,4]),Br(e,[-1,4]));i=Br(i,[r,i.shape[0]/r,4]);var a=fu(xc(fu(t,[0,0,1],[-1,-1,-1])),[0,0,0],[-1,-1,1]);return a=Br(a,[r,a.shape[1]]),{boxes:Kr(i),scores:Kr(a)}})}function lg(e,t){return W(function(){var n=e.shape[0];return{boxPredictionEncoding:Br(Hm(e,t.box_encoding_predictor),[n,-1,1,4]),classPrediction:Br(Hm(e,t.class_predictor),[n,-1,3])}})}function ug(e,t,n){return W(function(){var r=$h($h(e,n.conv_0,[1,1]),n.conv_1,[2,2]),i=$h($h(r,n.conv_2,[1,1]),n.conv_3,[2,2]),a=$h($h(i,n.conv_4,[1,1]),n.conv_5,[2,2]),o=$h($h(a,n.conv_6,[1,1]),n.conv_7,[2,2]),s=lg(t,n.box_predictor_0),c=lg(e,n.box_predictor_1),l=lg(r,n.box_predictor_2),u=lg(i,n.box_predictor_3),d=lg(a,n.box_predictor_4),f=lg(o,n.box_predictor_5);return{boxPredictions:nr([s.boxPredictionEncoding,c.boxPredictionEncoding,l.boxPredictionEncoding,u.boxPredictionEncoding,d.boxPredictionEncoding,f.boxPredictionEncoding],1),classPredictions:nr([s.classPrediction,c.classPrediction,l.classPrediction,u.classPrediction,d.classPrediction,f.classPrediction],1)}})}var dg=function(){function e(e){var t=e===void 0?{}:e,n=t.minConfidence,r=t.maxResults;if(this._name=`SsdMobilenetv1Options`,this._minConfidence=n||.5,this._maxResults=r||100,typeof this._minConfidence!=`number`||this._minConfidence<=0||this._minConfidence>=1)throw Error(this._name+` - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!=`number`)throw Error(this._name+` - expected maxResults to be a number`)}return Object.defineProperty(e.prototype,`minConfidence`,{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`maxResults`,{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),e}(),fg=function(e){Z(t,e);function t(){return e.call(this,`SsdMobilenetv1`)||this}return t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw Error(`SsdMobilenetv1 - load model before inference`);return W(function(){var n=rg(vl(pl(e.toBatchTensor(512,!1).toFloat(),q(.007843137718737125)),q(1)),t.mobilenetv1),r=ug(n.out,n.conv11,t.prediction_layer),i=r.boxPredictions,a=r.classPredictions;return cg(i,a,t.output_layer)})},t.prototype.forward=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=this.forwardInput,[4,jm(e)];case 1:return[2,t.apply(this,[n.sent()])]}})})},t.prototype.locateFaces=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S;return $(this,function(C){switch(C.label){case 0:return n=new dg(t),r=n.maxResults,i=n.minConfidence,[4,jm(e)];case 1:for(a=C.sent(),o=this.forwardInput(a),s=o.boxes,c=o.scores,l=s[0],u=c[0],d=1;d<s.length;d++)s[d].dispose(),c[d].dispose();return m=(p=Array).from,[4,u.data()];case 2:return f=m.apply(p,[C.sent()]),h=.5,g=ig(l,f,r,h,i),_=a.getReshapedInputDimensions(0),v=a.inputSize,y=v/_.width,b=v/_.height,x=l.arraySync(),S=g.map(function(e){var t=[Math.max(0,x[e][0]),Math.min(1,x[e][2])].map(function(e){return e*b}),n=t[0],r=t[1],i=[Math.max(0,x[e][1]),Math.min(1,x[e][3])].map(function(e){return e*y}),o=i[0],s=i[1];return new Bp(f[e],new qp(o,n,s-o,r-n),{height:a.getInputHeight(0),width:a.getInputWidth(0)})}),l.dispose(),u.dispose(),[2,S]}})})},t.prototype.getDefaultModelName=function(){return`ssd_mobilenetv1_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Qh(e)},t.prototype.extractParams=function(e){return Xh(e)},t}(Rm);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(fg);var pg=.4,mg=[new Ip(.738768,.874946),new Ip(2.42204,2.65704),new Ip(4.30971,7.04493),new Ip(10.246,4.59428),new Ip(12.6868,11.8741)],hg=[new Ip(1.603231,2.094468),new Ip(6.041143,7.080126),new Ip(2.882459,3.518061),new Ip(4.266906,5.178857),new Ip(9.041765,10.66308)],gg=[117.001,114.697,97.404],_g=`tiny_yolov2_model`,vg=`tiny_yolov2_separable_conv_model`,yg=function(e){return typeof e==`number`};function bg(e){if(!e)throw Error(`invalid config: `+e);if(typeof e.withSeparableConvs!=`boolean`)throw Error(`config.withSeparableConvs has to be a boolean, have: `+e.withSeparableConvs);if(!yg(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw Error(`config.iouThreshold has to be a number between [0, 1], have: `+e.iouThreshold);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(function(e){return typeof e==`string`}))throw Error(`config.classes has to be an array class names: string[], have: `+JSON.stringify(e.classes));if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(function(e){return e||{}}).every(function(e){return yg(e.x)&&yg(e.y)}))throw Error(`config.anchors has to be an array of { x: number, y: number }, have: `+JSON.stringify(e.anchors));if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(yg)))throw Error(`config.meanRgb has to be an array of shape [number, number, number], have: `+JSON.stringify(e.meanRgb))}function xg(e){return W(function(){var t=pl(e,q(.10000000149011612));return $c(Mu(vl(e,t)),t)})}function Sg(e,t){return W(function(){var n=jr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Vl(n,t.conv.filters,[1,1],`valid`),n=vl(n,t.bn.sub),n=pl(n,t.bn.truediv),n=$c(n,t.conv.bias),xg(n)})}function Cg(e,t){return W(function(){var n=jr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Jl(n,t.depthwise_filter,t.pointwise_filter,[1,1],`valid`),n=$c(n,t.bias),xg(n)})}function wg(e,t){var n=Wm(e,t);function r(n,r){var i=Hn(e(n)),a=Hn(e(n));return t.push({paramPath:r+`/sub`},{paramPath:r+`/truediv`}),{sub:i,truediv:a}}function i(e,t,i){return{conv:n(e,t,3,i+`/conv`),bn:r(t,i+`/bn`)}}return{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:qm(e,t)}}function Tg(e,t,n,r){var i=Xm(e),a=i.extractWeights,o=i.getRemainingWeights,s=[],c=wg(a,s),l=c.extractConvParams,u=c.extractConvWithBatchNormParams,d=c.extractSeparableConvParams,f;if(t.withSeparableConvs){var p=r[0],m=r[1],h=r[2],g=r[3],_=r[4],v=r[5],y=r[6],b=r[7],x=r[8],S=t.isFirstLayerConv2d?l(p,m,3,`conv0`):d(p,m,`conv0`),C=d(m,h,`conv1`),w=d(h,g,`conv2`),T=d(g,_,`conv3`),E=d(_,v,`conv4`),D=d(v,y,`conv5`),O=b?d(y,b,`conv6`):void 0,k=x?d(b,x,`conv7`):void 0,A=l(x||b||y,5*n,1,`conv8`);f={conv0:S,conv1:C,conv2:w,conv3:T,conv4:E,conv5:D,conv6:O,conv7:k,conv8:A}}else{var p=r[0],m=r[1],h=r[2],g=r[3],_=r[4],v=r[5],y=r[6],b=r[7],x=r[8],S=u(p,m,`conv0`),C=u(m,h,`conv1`),w=u(h,g,`conv2`),T=u(g,_,`conv3`),E=u(_,v,`conv4`),D=u(v,y,`conv5`),O=u(y,b,`conv6`),k=u(b,x,`conv7`),A=l(x,5*n,1,`conv8`);f={conv0:S,conv1:C,conv2:w,conv3:T,conv4:E,conv5:D,conv6:O,conv7:k,conv8:A}}if(o().length!==0)throw Error(`weights remaing after extract: `+o().length);return{params:f,paramMappings:s}}function Eg(e,t){var n=Ym(e,t);function r(e){return{sub:n(e+`/sub`,1),truediv:n(e+`/truediv`,1)}}function i(e){return{filters:n(e+`/filters`,4),bias:n(e+`/bias`,1)}}function a(e){return{conv:i(e+`/conv`),bn:r(e+`/bn`)}}return{extractConvParams:i,extractConvWithBatchNormParams:a,extractSeparableConvParams:Jm(n)}}function Dg(e,t){var n=[],r=Eg(e,n),i=r.extractConvParams,a=r.extractConvWithBatchNormParams,o=r.extractSeparableConvParams,s;if(t.withSeparableConvs){var c=t.filterSizes&&t.filterSizes.length||9;s={conv0:t.isFirstLayerConv2d?i(`conv0`):o(`conv0`),conv1:o(`conv1`),conv2:o(`conv2`),conv3:o(`conv3`),conv4:o(`conv4`),conv5:o(`conv5`),conv6:c>7?o(`conv6`):void 0,conv7:c>8?o(`conv7`):void 0,conv8:i(`conv8`)}}else s={conv0:a(`conv0`),conv1:a(`conv1`),conv2:a(`conv2`),conv3:a(`conv3`),conv4:a(`conv4`),conv5:a(`conv5`),conv6:a(`conv6`),conv7:a(`conv7`),conv8:i(`conv8`)};return Um(e,n),{params:s,paramMappings:n}}var Og;(function(e){e[e.XS=224]=`XS`,e[e.SM=320]=`SM`,e[e.MD=416]=`MD`,e[e.LG=608]=`LG`})(Og||={});var kg=function(){function e(e){var t=e===void 0?{}:e,n=t.inputSize,r=t.scoreThreshold;if(this._name=`TinyYolov2Options`,this._inputSize=n||416,this._scoreThreshold=r||.5,typeof this._inputSize!=`number`||this._inputSize%32!=0)throw Error(this._name+` - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!=`number`||this._scoreThreshold<=0||this._scoreThreshold>=1)throw Error(this._name+` - expected scoreThreshold to be a number between 0 and 1`)}return Object.defineProperty(e.prototype,`inputSize`,{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`scoreThreshold`,{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),e}(),Ag=function(e){Z(t,e);function t(t){var n=e.call(this,`TinyYolov2`)||this;return bg(t),n._config=t,n}return Object.defineProperty(t.prototype,`config`,{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`withClassScores`,{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`boxEncodingSize`,{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),t.prototype.runTinyYolov2=function(e,t){var n=Sg(e,t.conv0);return n=su(n,[2,2],[2,2],`same`),n=Sg(n,t.conv1),n=su(n,[2,2],[2,2],`same`),n=Sg(n,t.conv2),n=su(n,[2,2],[2,2],`same`),n=Sg(n,t.conv3),n=su(n,[2,2],[2,2],`same`),n=Sg(n,t.conv4),n=su(n,[2,2],[2,2],`same`),n=Sg(n,t.conv5),n=su(n,[2,2],[1,1],`same`),n=Sg(n,t.conv6),n=Sg(n,t.conv7),Hm(n,t.conv8,`valid`,!1)},t.prototype.runMobilenet=function(e,t){var n=this.config.isFirstLayerConv2d?xg(Hm(e,t.conv0,`valid`,!1)):Cg(e,t.conv0);return n=su(n,[2,2],[2,2],`same`),n=Cg(n,t.conv1),n=su(n,[2,2],[2,2],`same`),n=Cg(n,t.conv2),n=su(n,[2,2],[2,2],`same`),n=Cg(n,t.conv3),n=su(n,[2,2],[2,2],`same`),n=Cg(n,t.conv4),n=su(n,[2,2],[2,2],`same`),n=Cg(n,t.conv5),n=su(n,[2,2],[1,1],`same`),n=t.conv6?Cg(n,t.conv6):n,n=t.conv7?Cg(n,t.conv7):n,Hm(n,t.conv8,`valid`,!1)},t.prototype.forwardInput=function(e,t){var n=this,r=this.params;if(!r)throw Error(`TinyYolov2 - load model before inference`);return W(function(){var i=e.toBatchTensor(t,!1).toFloat();return i=n.config.meanRgb?Wp(i,n.config.meanRgb):i,i=i.div(q(256)),n.config.withSeparableConvs?n.runMobilenet(i,r):n.runTinyYolov2(i,r)})},t.prototype.forward=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,jm(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent()]}})})},t.prototype.detect=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g=this;return $(this,function(_){switch(_.label){case 0:return n=new kg(t),r=n.inputSize,i=n.scoreThreshold,[4,jm(e)];case 1:return a=_.sent(),[4,this.forwardInput(a,r)];case 2:return o=_.sent(),s=W(function(){return Kr(o)[0].expandDims()}),c={width:a.getInputWidth(0),height:a.getInputHeight(0)},[4,this.extractBoxes(s,a.getReshapedInputDimensions(0),i)];case 3:return l=_.sent(),o.dispose(),s.dispose(),u=l.map(function(e){return e.box}),d=l.map(function(e){return e.score}),f=l.map(function(e){return e.classScore}),p=l.map(function(e){return g.config.classes[e.label]}),m=Up(u.map(function(e){return e.rescale(r)}),d,this.config.iouThreshold,!0),h=m.map(function(e){return new zp(d[e],f[e],p[e],u[e],c)}),[2,h]}})})},t.prototype.getDefaultModelName=function(){return``},t.prototype.extractParamsFromWeigthMap=function(e){return Dg(e,this.config)},t.prototype.extractParams=function(e){var n=this.config.filterSizes||t.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(r!==7&&r!==8&&r!==9)throw Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found `+r+` filterSizes in config`);return Tg(e,this.config,this.boxEncodingSize,n)},t.prototype.extractBoxes=function(e,t,n){return Q(this,void 0,void 0,function(){var r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this;return $(this,function(N){switch(N.label){case 0:return r=t.width,i=t.height,a=Math.max(r,i),o=a/r,s=a/i,c=e.shape[1],l=this.config.anchors.length,u=W(function(){var t=e.reshape([c,c,l,M.boxEncodingSize]);return[t.slice([0,0,0,0],[c,c,l,4]),t.slice([0,0,0,4],[c,c,l,1]),M.withClassScores?mi(t.slice([0,0,0,5],[c,c,l,M.config.classes.length]),3):q(0)]}),d=u[0],f=u[1],p=u[2],m=[],[4,f.array()];case 1:return h=N.sent(),[4,d.array()];case 2:g=N.sent(),_=0,N.label=3;case 3:if(!(_<c))return[3,12];v=0,N.label=4;case 4:if(!(v<c))return[3,11];y=0,N.label=5;case 5:return y<l?(b=Kp(h[_][v][y][0]),!n||b>n?(x=(v+Kp(g[_][v][y][0]))/c*o,S=(_+Kp(g[_][v][y][1]))/c*s,C=Math.exp(g[_][v][y][2])*this.config.anchors[y].x/c*o,w=Math.exp(g[_][v][y][3])*this.config.anchors[y].y/c*s,T=x-C/2,E=S-w/2,D={row:_,col:v,anchor:y},this.withClassScores?[4,this.extractPredictedClass(p,D)]:[3,7]):[3,9]):[3,10];case 6:return j=N.sent(),[3,8];case 7:j={classScore:1,label:0},N.label=8;case 8:O=j,k=O.classScore,A=O.label,m.push(bp({box:new Rp(T,E,T+C,E+w),score:b,classScore:b*k,label:A},D)),N.label=9;case 9:return y++,[3,5];case 10:return v++,[3,4];case 11:return _++,[3,3];case 12:return d.dispose(),f.dispose(),p.dispose(),[2,m]}})})},t.prototype.extractPredictedClass=function(e,t){return Q(this,void 0,void 0,function(){var n,r,i,a;return $(this,function(o){switch(o.label){case 0:return n=t.row,r=t.col,i=t.anchor,[4,e.array()];case 1:return a=o.sent(),[2,Array(this.config.classes.length).fill(0).map(function(e,t){return a[n][r][i][t]}).map(function(e,t){return{classScore:e,label:t}}).reduce(function(e,t){return e.classScore>t.classScore?e:t})]}})})},t.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],t}(Rm),jg=function(e){Z(t,e);function t(t){t===void 0&&(t=!0);var n=this,r=Object.assign({},{withSeparableConvs:t,iouThreshold:pg,classes:[`face`]},t?{anchors:hg,meanRgb:gg}:{anchors:mg,withClassScores:!0});return n=e.call(this,r)||this,n}return Object.defineProperty(t.prototype,`withSeparableConvs`,{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,`anchors`,{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return[4,this.detect(e,t)];case 1:return n=r.sent(),[2,n.map(function(e){return new Bp(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return this.withSeparableConvs?vg:_g},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(Ag),Mg=function(e){Z(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t._name=`TinyFaceDetectorOptions`,t}return t}(kg),Ng=function(){function e(){}return e.prototype.then=function(e){return Q(this,void 0,void 0,function(){var t;return $(this,function(n){switch(n.label){case 0:return t=e,[4,this.run()];case 1:return[2,t.apply(void 0,[n.sent()])]}})})},e.prototype.run=function(){return Q(this,void 0,void 0,function(){return $(this,function(e){throw Error(`ComposableTask - run is not implemented`)})})},e}();function Pg(e,t,n,r,i){return i===void 0&&(i=function(e){return e.alignedRect}),Q(this,void 0,void 0,function(){var a,o,s,c,l;return $(this,function(u){switch(u.label){case 0:return a=e.map(function(e){return fh(e)?i(e):e.detection}),s=r,s?[3,5]:t instanceof $e?[4,Nm(t,a)]:[3,2];case 1:return c=u.sent(),[3,4];case 2:return[4,Mm(t,a)];case 3:c=u.sent(),u.label=4;case 4:s=c,u.label=5;case 5:return o=s,[4,n(o)];case 6:return l=u.sent(),o.forEach(function(e){return e instanceof $e&&e.dispose()}),[2,l]}})})}function Fg(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a=this;return $(this,function(o){return[2,Pg([e],t,function(e){return Q(a,void 0,void 0,function(){return $(this,function(t){return[2,n(e[0])]})})},r,i)]})})}function Ig(e){return W(function(){return Ur(Kr(e,3).reverse(),3)})}function Lg(e,t){var n=Wm(e,t),r=Gm(e,t);function i(n,r){var i=Hn(e(n));return t.push({paramPath:r}),i}function a(e,t,r){return r===void 0&&(r=!1),{conv1:n(e[0],e[1],3,t+`/conv1`),prelu1_alpha:i(e[1],t+`/prelu1_alpha`),conv2:n(e[1],e[2],3,t+`/conv2`),prelu2_alpha:i(e[2],t+`/prelu2_alpha`),conv3:n(e[2],e[3],r?2:3,t+`/conv3`),prelu3_alpha:i(e[3],t+`/prelu3_alpha`)}}function o(){var e=a([3,10,16,32],`pnet`),t=n(32,2,1,`pnet/conv4_1`),r=n(32,4,1,`pnet/conv4_2`);return bp(bp({},e),{conv4_1:t,conv4_2:r})}function s(){var e=a([3,28,48,64],`rnet`,!0),t=r(576,128,`rnet/fc1`),n=i(128,`rnet/prelu4_alpha`),o=r(128,2,`rnet/fc2_1`),s=r(128,4,`rnet/fc2_2`);return bp(bp({},e),{fc1:t,prelu4_alpha:n,fc2_1:o,fc2_2:s})}function c(){var e=a([3,32,64,64],`onet`),t=n(64,128,2,`onet/conv4`),o=i(128,`onet/prelu4_alpha`),s=r(1152,256,`onet/fc1`),c=i(256,`onet/prelu5_alpha`),l=r(256,2,`onet/fc2_1`),u=r(256,4,`onet/fc2_2`),d=r(256,10,`onet/fc2_3`);return bp(bp({},e),{conv4:t,prelu4_alpha:o,fc1:s,prelu5_alpha:c,fc2_1:l,fc2_2:u,fc2_3:d})}return{extractPNetParams:o,extractRNetParams:s,extractONetParams:c}}function Rg(e){var t=Xm(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],a=Lg(n,i),o=a.extractPNetParams,s=a.extractRNetParams,c=a.extractONetParams,l=o(),u=s(),d=c();if(r().length!==0)throw Error(`weights remaing after extract: `+r().length);return{params:{pnet:l,rnet:u,onet:d},paramMappings:i}}function zg(e,t){var n=Ym(e,t);function r(e){return{filters:n(e+`/weights`,4,e+`/filters`),bias:n(e+`/bias`,1)}}function i(e){return{weights:n(e+`/weights`,2),bias:n(e+`/bias`,1)}}function a(e){return n(e,1)}function o(e){return{conv1:r(e+`/conv1`),prelu1_alpha:a(e+`/prelu1_alpha`),conv2:r(e+`/conv2`),prelu2_alpha:a(e+`/prelu2_alpha`),conv3:r(e+`/conv3`),prelu3_alpha:a(e+`/prelu3_alpha`)}}function s(){var e=o(`pnet`),t=r(`pnet/conv4_1`),n=r(`pnet/conv4_2`);return bp(bp({},e),{conv4_1:t,conv4_2:n})}function c(){var e=o(`rnet`),t=i(`rnet/fc1`),n=a(`rnet/prelu4_alpha`),r=i(`rnet/fc2_1`),s=i(`rnet/fc2_2`);return bp(bp({},e),{fc1:t,prelu4_alpha:n,fc2_1:r,fc2_2:s})}function l(){var e=o(`onet`),t=r(`onet/conv4`),n=a(`onet/prelu4_alpha`),s=i(`onet/fc1`),c=a(`onet/prelu5_alpha`),l=i(`onet/fc2_1`),u=i(`onet/fc2_2`),d=i(`onet/fc2_3`);return bp(bp({},e),{conv4:t,prelu4_alpha:n,fc1:s,prelu5_alpha:c,fc2_1:l,fc2_2:u,fc2_3:d})}return{extractPNetParams:s,extractRNetParams:c,extractONetParams:l}}function Bg(e){var t=[],n=zg(e,t),r=n.extractPNetParams,i=n.extractRNetParams,a=n.extractONetParams,o=r(),s=i(),c=a();return Um(e,t),{params:{pnet:o,rnet:s,onet:c},paramMappings:t}}function Vg(e,t){var n=t[0],r=t[1];return{height:Math.floor(n*e),width:Math.floor(r*e)}}function Hg(e,t,n){for(var r=n[0],i=n[1],a=12/e,o=[],s=Math.min(r,i)*a,c=0;s>=12;)o.push(a*t**+c),s*=t,c+=1;return o}var Ug=function(e){Z(t,e);function t(t,n,r,i){return e.call(this,{left:t,top:n,right:r,bottom:i},!0)||this}return t}(Lp);function Wg(e){return W(function(){return pl(vl(e,q(127.5)),q(.0078125))})}function Gg(e,t){return W(function(){return $c(Mu(e),pl(t,_c(Mu(_c(e)))))})}function Kg(e,t,n){return n===void 0&&(n=!1),W(function(){var r=Hm(e,t.conv1,`valid`);return r=Gg(r,t.prelu1_alpha),r=su(r,n?[2,2]:[3,3],[2,2],`same`),r=Hm(r,t.conv2,`valid`),r=Gg(r,t.prelu2_alpha),r=n?r:su(r,[3,3],[2,2],`valid`),r=Hm(r,t.conv3,`valid`),r=Gg(r,t.prelu3_alpha),r})}function qg(e,t){return W(function(){var n=Kg(e,t,!0),r=Hm(n,t.conv4_1,`valid`);return{prob:mi(vl(r,Dr(Cu(r,3),3)),3),regions:Hm(n,t.conv4_2,`valid`)}})}function Jg(e,t){return W(function(){var n=Vg(t,e.shape.slice(1)),r=n.height,i=n.width;return Fu(Wg(Ad.resizeBilinear(e,[r,i])),[0,2,1,3])})}function Yg(e,t,n,r){for(var i=[],a=e.arraySync(),o=0;o<e.shape[0];o++)for(var s=0;s<e.shape[1];s++)a[o][s]>=r&&i.push(new Ip(s,o));return i.map(function(e){var r=new Rp(Math.round((e.y*2+1)/n),Math.round((e.x*2+1)/n),Math.round((e.y*2+12)/n),Math.round((e.x*2+12)/n)),i=a[e.y][e.x],o=t.arraySync();return{cell:r,score:i,region:new Ug(o[e.y][e.x][0],o[e.y][e.x][1],o[e.y][e.x][2],o[e.y][e.x][3])}})}function Xg(e,t,n,r,i){i.stage1=[];var a=t.map(function(t){return W(function(){var n={scale:t},i=Jg(e,t),a=Date.now(),o=qg(i,r),s=o.prob,c=o.regions;return n.pnet=Date.now()-a,{scoresTensor:Kr(Kr(s,3)[1])[0],regionsTensor:Kr(c)[0],scale:t,statsForScale:n}})}).map(function(e){var t=e.scoresTensor,r=e.regionsTensor,a=e.scale,o=e.statsForScale,s=Yg(t,r,a,n);if(t.dispose(),r.dispose(),!s.length)return i.stage1.push(o),[];var c=Date.now(),l=Up(s.map(function(e){return e.cell}),s.map(function(e){return e.score}),.5);return o.nms=Date.now()-c,o.numBoxes=l.length,i.stage1.push(o),l.map(function(e){return s[e]})}).reduce(function(e,t){return e.concat(t)},[]),o=[],s=[];if(a.length>0){var c=Date.now(),l=Up(a.map(function(e){return e.cell}),a.map(function(e){return e.score}),.7);i.stage1_nms=Date.now()-c,s=l.map(function(e){return a[e].score}),o=l.map(function(e){return a[e]}).map(function(e){var t=e.cell,n=e.region;return new Rp(t.left+n.left*t.width,t.top+n.top*t.height,t.right+n.right*t.width,t.bottom+n.bottom*t.height).toSquare().round()})}return{boxes:o,scores:s}}function Zg(e,t,n){var r=n.width,i=n.height;return Q(this,void 0,void 0,function(){var n,a,o,s=this;return $(this,function(c){switch(c.label){case 0:return n=_m(e),[4,Promise.all(t.map(function(t){return Q(s,void 0,void 0,function(){var r,i,a,o,s,c,l,u;return $(this,function(d){return r=t.padAtBorders(e.height,e.width),i=r.y,a=r.ey,o=r.x,s=r.ex,c=o-1,l=i-1,u=n.getImageData(c,l,s-c,a-l),[2,hm.isNodejs()?Em(u):createImageBitmap(u)]})})}))];case 1:return a=c.sent(),o=[],a.forEach(function(e){var t=_m(Tm({width:r,height:i}));t.drawImage(e,0,0,r,i);for(var n=t.getImageData(0,0,r,i).data,a=[],s=0;s<n.length;s+=4)a.push(n[s+2]),a.push(n[s+1]),a.push(n[s]);o.push(a)}),[2,o.map(function(e){return W(function(){return Wg(Fu(Gn(e,[1,r,i,3]),[0,2,1,3]).toFloat())})})]}})})}function Qg(e,t){return W(function(){var n=Kg(e,t),r=Gg(rh(Br(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu4_alpha),i=rh(r,t.fc2_1),a=mi(vl(i,Dr(Cu(i,1),1)),1),o=rh(r,t.fc2_2);return{scores:Kr(a,1)[1],regions:o}})}function $g(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a,o,s,c,l,u,d,f,p,m,h,g,_,v;return $(this,function(y){switch(y.label){case 0:return a=Date.now(),[4,Zg(e,t,{width:24,height:24})];case 1:return o=y.sent(),i.stage2_extractImagePatches=Date.now()-a,a=Date.now(),s=o.map(function(e){var t=Qg(e,r);return e.dispose(),t}),i.stage2_rnet=Date.now()-a,c=s.length>1?nr(s.map(function(e){return e.scores})):s[0].scores,d=(u=Array).from,[4,c.data()];case 2:return l=d.apply(u,[y.sent()]),c.dispose(),f=l.map(function(e,t){return{score:e,idx:t}}).filter(function(e){return e.score>n}).map(function(e){return e.idx}),p=f.map(function(e){return t[e]}),m=f.map(function(e){return l[e]}),h=[],g=[],p.length>0&&(a=Date.now(),_=Up(p,m,.7),i.stage2_nms=Date.now()-a,v=_.map(function(e){var t=s[f[e]].regions.arraySync();return new Ug(t[0][0],t[0][1],t[0][2],t[0][3])}),g=_.map(function(e){return m[e]}),h=_.map(function(e,t){return p[e].calibrate(v[t])})),s.forEach(function(e){e.regions.dispose(),e.scores.dispose()}),[2,{boxes:h,scores:g}]}})})}function e_(e,t){return W(function(){var n=Kg(e,t);n=su(n,[2,2],[2,2],`same`),n=Hm(n,t.conv4,`valid`),n=Gg(n,t.prelu4_alpha);var r=Gg(rh(Br(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu5_alpha),i=rh(r,t.fc2_1),a=mi(vl(i,Dr(Cu(i,1),1)),1),o=rh(r,t.fc2_2),s=rh(r,t.fc2_3);return{scores:Kr(a,1)[1],regions:o,points:s}})}function t_(e,t,n,r,i){return Q(this,void 0,void 0,function(){var a,o,s,c,l,u,d,f,p,m,h,g,_,v,y;return $(this,function(b){switch(b.label){case 0:return a=Date.now(),[4,Zg(e,t,{width:48,height:48})];case 1:return o=b.sent(),i.stage3_extractImagePatches=Date.now()-a,a=Date.now(),s=o.map(function(e){var t=e_(e,r);return e.dispose(),t}),i.stage3_onet=Date.now()-a,c=s.length>1?nr(s.map(function(e){return e.scores})):s[0].scores,d=(u=Array).from,[4,c.data()];case 2:return l=d.apply(u,[b.sent()]),c.dispose(),f=l.map(function(e,t){return{score:e,idx:t}}).filter(function(e){return e.score>n}).map(function(e){return e.idx}),p=f.map(function(e){var t=s[e].regions.arraySync();return new Ug(t[0][0],t[0][1],t[0][2],t[0][3])}),m=f.map(function(e,n){return t[e].calibrate(p[n])}),h=f.map(function(e){return l[e]}),g=[],_=[],v=[],m.length>0&&(a=Date.now(),y=Up(m,h,.7,!1),i.stage3_nms=Date.now()-a,g=y.map(function(e){return m[e]}),_=y.map(function(e){return h[e]}),v=y.map(function(e,t){return[,,,,,].fill(0).map(function(n,r){var i=s[e].points.arraySync();return new Ip(i[0][r]*(g[t].width+1)+g[t].left,i[0][r+5]*(g[t].height+1)+g[t].top)})})),s.forEach(function(e){e.regions.dispose(),e.scores.dispose(),e.points.dispose()}),[2,{boxes:g,scores:_,points:v}]}})})}var n_=function(e){Z(t,e);function t(){return e.call(this,`Mtcnn`)||this}return t.prototype.load=function(t){return Q(this,void 0,void 0,function(){return $(this,function(n){return console.warn(`mtcnn is deprecated and will be removed soon`),[2,e.prototype.load.call(this,t)]})})},t.prototype.loadFromDisk=function(t){return Q(this,void 0,void 0,function(){return $(this,function(n){return console.warn(`mtcnn is deprecated and will be removed soon`),[2,e.prototype.loadFromDisk.call(this,t)]})})},t.prototype.forwardInput=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S;return $(this,function(C){switch(C.label){case 0:if(n=this.params,!n)throw Error(`Mtcnn - load model before inference`);if(r=e.canvases[0],!r)throw Error(`Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.`);return i={},a=Date.now(),o=W(function(){return Ig(Dr(ep.fromPixels(r)).toFloat())}),s=function(e){return o.dispose(),i.total=Date.now()-a,e},c=o.shape.slice(1),l=c[0],u=c[1],d=new Jh(t),f=d.minFaceSize,p=d.scaleFactor,m=d.maxNumScales,h=d.scoreThresholds,g=d.scaleSteps,_=(g||Hg(f,p,[l,u])).filter(function(e){var t=Vg(e,[l,u]);return Math.min(t.width,t.height)>12}).slice(0,m),i.scales=_,i.pyramid=_.map(function(e){return Vg(e,[l,u])}),v=Date.now(),[4,Xg(o,_,h[0],n.pnet,i)];case 1:return y=C.sent(),i.total_stage1=Date.now()-v,y.boxes.length?(i.stage2_numInputBoxes=y.boxes.length,v=Date.now(),[4,$g(r,y.boxes,h[1],n.rnet,i)]):[2,s({results:[],stats:i})];case 2:return b=C.sent(),i.total_stage2=Date.now()-v,b.boxes.length?(i.stage3_numInputBoxes=b.boxes.length,v=Date.now(),[4,t_(r,b.boxes,h[2],n.onet,i)]):[2,s({results:[],stats:i})];case 3:return x=C.sent(),i.total_stage3=Date.now()-v,S=x.boxes.map(function(e,t){return ph(im({},new Bp(x.scores[t],new qp(e.left/u,e.top/l,e.width/u,e.height/l),{height:l,width:u})),new Qp(x.points[t].map(function(t){return t.sub(new Ip(e.left,e.top)).div(new Ip(e.width,e.height))}),{width:e.width,height:e.height}))}),[2,s({results:S,stats:i})]}})})},t.prototype.forward=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,jm(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent().results]}})})},t.prototype.forwardWithStats=function(e,t){return t===void 0&&(t={}),Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return n=this.forwardInput,[4,jm(e)];case 1:return[2,n.apply(this,[r.sent(),t])]}})})},t.prototype.getDefaultModelName=function(){return`mtcnn_model`},t.prototype.extractParamsFromWeigthMap=function(e){return Bg(e)},t.prototype.extractParams=function(e){return Rg(e)},t}(Rm),r_=.4,i_=[new Ip(1.603231,2.094468),new Ip(6.041143,7.080126),new Ip(2.882459,3.518061),new Ip(4.266906,5.178857),new Ip(9.041765,10.66308)],a_=[117.001,114.697,97.404],o_=function(e){Z(t,e);function t(){var t=this,n={withSeparableConvs:!0,iouThreshold:r_,classes:[`face`],anchors:i_,meanRgb:a_,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return t=e.call(this,n)||this,t}return Object.defineProperty(t.prototype,`anchors`,{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return Q(this,void 0,void 0,function(){var n;return $(this,function(r){switch(r.label){case 0:return[4,this.detect(e,t)];case 1:return n=r.sent(),[2,n.map(function(e){return new Bp(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return`tiny_face_detector_model`},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(Ag),s_={ssdMobilenetv1:new fg,tinyFaceDetector:new o_,tinyYolov2:new jg,mtcnn:new n_,faceLandmark68Net:new Oh,faceLandmark68TinyNet:new Mh,faceRecognitionNet:new Wh,faceExpressionNet:new uh,ageGenderNet:new Eh},c_=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return t}(Ng),l_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n=this;return $(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return e=r.sent(),[4,Pg(e,this.input,function(e){return Q(n,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,Promise.all(e.map(function(e){return s_.faceExpressionNet.predictExpressions(e)}))];case 1:return[2,t.sent()]}})})},this.extractedFaces)];case 2:return t=r.sent(),[2,e.map(function(e,n){return dh(e,t[n])})]}})})},t.prototype.withAgeAndGender=function(){return new m_(this,this.input)},t}(c_),u_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),e?[4,Fg(e,this.input,function(e){return s_.faceExpressionNet.predictExpressions(e)},this.extractedFaces)]:[2];case 2:return t=n.sent(),[2,dh(e,t)]}})})},t.prototype.withAgeAndGender=function(){return new h_(this,this.input)},t}(c_),d_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new g_(this,this.input)},t.prototype.withFaceDescriptors=function(){return new y_(this,this.input)},t}(l_),f_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withAgeAndGender=function(){return new __(this,this.input)},t.prototype.withFaceDescriptor=function(){return new b_(this,this.input)},t}(u_),p_=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return t}(Ng),m_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n=this;return $(this,function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return e=r.sent(),[4,Pg(e,this.input,function(e){return Q(n,void 0,void 0,function(){return $(this,function(t){switch(t.label){case 0:return[4,Promise.all(e.map(function(e){return s_.ageGenderNet.predictAgeAndGender(e)}))];case 1:return[2,t.sent()]}})})},this.extractedFaces)];case 2:return t=r.sent(),[2,e.map(function(e,n){var r=t[n],i=r.age,a=r.gender,o=r.genderProbability;return Kh(qh(e,a,o),i)})]}})})},t.prototype.withFaceExpressions=function(){return new l_(this,this.input)},t}(p_),h_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i;return $(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),e?[4,Fg(e,this.input,function(e){return s_.ageGenderNet.predictAgeAndGender(e)},this.extractedFaces)]:[2];case 2:return t=a.sent(),n=t.age,r=t.gender,i=t.genderProbability,[2,Kh(qh(e,r,i),n)]}})})},t.prototype.withFaceExpressions=function(){return new u_(this,this.input)},t}(p_),g_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new d_(this,this.input)},t.prototype.withFaceDescriptors=function(){return new y_(this,this.input)},t}(m_),__=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.withFaceExpressions=function(){return new f_(this,this.input)},t.prototype.withFaceDescriptor=function(){return new b_(this,this.input)},t}(h_),v_=function(e){Z(t,e);function t(t,n){var r=e.call(this)||this;return r.parentTask=t,r.input=n,r}return t}(Ng),y_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),[4,Pg(e,this.input,function(e){return Promise.all(e.map(function(e){return s_.faceRecognitionNet.computeFaceDescriptor(e)}))},null,function(e){return e.landmarks.align(null,{useDlibAlignment:!0})})];case 2:return t=n.sent(),[2,t.map(function(t,n){return Gh(e[n],t)})]}})})},t.prototype.withFaceExpressions=function(){return new d_(this,this.input)},t.prototype.withAgeAndGender=function(){return new g_(this,this.input)},t}(v_),b_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return e=n.sent(),e?[4,Fg(e,this.input,function(e){return s_.faceRecognitionNet.computeFaceDescriptor(e)},null,function(e){return e.landmarks.align(null,{useDlibAlignment:!0})})]:[2];case 2:return t=n.sent(),[2,Gh(e,t)]}})})},t.prototype.withFaceExpressions=function(){return new f_(this,this.input)},t.prototype.withAgeAndGender=function(){return new __(this,this.input)},t}(v_),x_=function(e){Z(t,e);function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.useTinyLandmarkNet=r,i}return Object.defineProperty(t.prototype,`landmarkNet`,{get:function(){return this.useTinyLandmarkNet?s_.faceLandmark68TinyNet:s_.faceLandmark68Net},enumerable:!0,configurable:!0}),t}(Ng),S_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i,a=this;return $(this,function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return e=o.sent(),t=e.map(function(e){return e.detection}),this.input instanceof $e?[4,Nm(this.input,t)]:[3,3];case 2:return r=o.sent(),[3,5];case 3:return[4,Mm(this.input,t)];case 4:r=o.sent(),o.label=5;case 5:return n=r,[4,Promise.all(n.map(function(e){return a.landmarkNet.detectLandmarks(e)}))];case 6:return i=o.sent(),n.forEach(function(e){return e instanceof $e&&e.dispose()}),[2,e.map(function(e,t){return ph(e,i[t])})]}})})},t.prototype.withFaceExpressions=function(){return new d_(this,this.input)},t.prototype.withAgeAndGender=function(){return new g_(this,this.input)},t.prototype.withFaceDescriptors=function(){return new y_(this,this.input)},t}(x_),C_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r,i;return $(this,function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),e?(t=e.detection,this.input instanceof $e?[4,Nm(this.input,[t])]:[3,3]):[2];case 2:return r=a.sent(),[3,5];case 3:return[4,Mm(this.input,[t])];case 4:r=a.sent(),a.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return i=a.sent(),n.forEach(function(e){return e instanceof $e&&e.dispose()}),[2,ph(e,i)]}})})},t.prototype.withFaceExpressions=function(){return new f_(this,this.input)},t.prototype.withAgeAndGender=function(){return new __(this,this.input)},t.prototype.withFaceDescriptor=function(){return new b_(this,this.input)},t}(x_),w_=function(e){Z(t,e);function t(t,n){n===void 0&&(n=new dg);var r=e.call(this)||this;return r.input=t,r.options=n,r}return t}(Ng),T_=function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t,n,r;return $(this,function(i){switch(i.label){case 0:return e=this,t=e.input,n=e.options,n instanceof Jh?[4,s_.mtcnn.forward(t,n)]:[3,2];case 1:return[2,i.sent().map(function(e){return e.detection})];case 2:if(r=n instanceof Mg?function(e){return s_.tinyFaceDetector.locateFaces(e,n)}:n instanceof dg?function(e){return s_.ssdMobilenetv1.locateFaces(e,n)}:n instanceof kg?function(e){return s_.tinyYolov2.locateFaces(e,n)}:null,!r)throw Error(`detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options`);return[2,r(t)]}})})},t.prototype.runAndExtendWithFaceDetections=function(){var e=this;return new Promise(function(t){return Q(e,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e.map(function(e){return im({},e)}))]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new S_(this.runAndExtendWithFaceDetections(),this.input,e)},t.prototype.withFaceExpressions=function(){return new l_(this.runAndExtendWithFaceDetections(),this.input)},t.prototype.withAgeAndGender=function(){return new m_(this.runAndExtendWithFaceDetections(),this.input)},t}(w_);(function(e){Z(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.run=function(){return Q(this,void 0,void 0,function(){var e,t;return $(this,function(n){switch(n.label){case 0:return[4,new T_(this.input,this.options)];case 1:return e=n.sent(),t=e[0],e.forEach(function(e){e.score>t.score&&(t=e)}),[2,t]}})})},t.prototype.runAndExtendWithFaceDetection=function(){var e=this;return new Promise(function(t){return Q(e,void 0,void 0,function(){var e;return $(this,function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e?im({},e):void 0)]}})})})},t.prototype.withFaceLandmarks=function(e){return e===void 0&&(e=!1),new C_(this.runAndExtendWithFaceDetection(),this.input,e)},t.prototype.withFaceExpressions=function(){return new u_(this.runAndExtendWithFaceDetection(),this.input)},t.prototype.withAgeAndGender=function(){return new h_(this.runAndExtendWithFaceDetection(),this.input)},t})(w_);function E_(e,t){return t===void 0&&(t=new dg),new T_(e,t)}function D_(e,t){if(e.length!==t.length)throw Error(`euclideanDistance: arr1.length !== arr2.length`);var n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map(function(e,t){return e-r[t]}).reduce(function(e,t){return e+t**2},0))}(function(){function e(e,t){t===void 0&&(t=.6),this._distanceThreshold=t;var n=Array.isArray(e)?e:[e];if(!n.length)throw Error(`FaceRecognizer.constructor - expected atleast one input`);var r=1,i=function(){return`person `+ r++};this._labeledDescriptors=n.map(function(e){if(e instanceof nm)return e;if(e instanceof Float32Array)return new nm(i(),[e]);if(e.descriptor&&e.descriptor instanceof Float32Array)return new nm(i(),[e.descriptor]);throw Error(`FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>`)})}return Object.defineProperty(e.prototype,`labeledDescriptors`,{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,`distanceThreshold`,{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),e.prototype.computeMeanDistance=function(e,t){return t.map(function(t){return D_(t,e)}).reduce(function(e,t){return e+t},0)/(t.length||1)},e.prototype.matchDescriptor=function(e){var t=this;return this.labeledDescriptors.map(function(n){var r=n.descriptors,i=n.label;return new em(i,t.computeMeanDistance(e,r))}).reduce(function(e,t){return e.distance<t.distance?e:t})},e.prototype.findBestMatch=function(e){var t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new em(`unknown`,t.distance)},e.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(function(e){return e.toJSON()})}},e.fromJSON=function(t){return new e(t.labeledDescriptors.map(function(e){return nm.fromJSON(e)}),t.distanceThreshold)},e})();function O_(e){return Math.max(0,Math.min(1,e))}function k_(e){let t=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y),n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5];return(t(r,s)+t(i,o))/(2*t(n,a))}function A_(e,t,n){return!t||t<=0?e:new Promise((r,i)=>{let a=setTimeout(()=>i(n()),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}function j_(){let e=!1;return{load:async(t,n)=>{if(!e)try{let r=n?.timeoutMs??15e3;await A_(s_.tinyFaceDetector.loadFromUri(t),r,()=>({code:`MODEL_LOAD_TIMEOUT`,message:`Timeout ao carregar modelo TinyFaceDetector em: ${t}`})),await A_(s_.faceLandmark68TinyNet.loadFromUri(t),r,()=>({code:`MODEL_LOAD_TIMEOUT`,message:`Timeout ao carregar modelo faceLandmark68TinyNet em: ${t}`})),e=!0}catch(e){throw e?.code===`MODEL_LOAD_TIMEOUT`?e:{code:`MODEL_LOAD_FAILED`,message:`Falha ao carregar modelos face-api.js em: ${t}`,cause:e}}},detect:async(t,n)=>{if(!e)return{faces:0};let r=new Mg({inputSize:416,scoreThreshold:.45}),i=t.videoWidth||1,a=t.videoHeight||1,o=e=>{let t=e.x/i,n=e.y/a,r=e.width/i,o=e.height/a;return{faces:1,box:{x:t,y:n,width:r,height:o},centerX:O_(t+r/2),area:r*o,poseSource:`bbox`}},s=async()=>{let e=await E_(t,r);return e&&e.length>0?e:await E_(t,r)};if(n?.withLandmarks){let e=[];try{e=await E_(t,r).withFaceLandmarks(!0)}catch{e=[]}if(!e||e.length===0){let e=await s();return!e||e.length===0?{faces:0}:e.length>1?{faces:e.length}:o(e[0].box)}if(e.length>1)return{faces:e.length};let n=e[0].detection.box,c=e[0].landmarks,l=c.getLeftEye(),u=c.getRightEye(),d=c.getNose(),f=c.getJawOutline(),p=c.getMouth(),m=e=>e.map(e=>({x:O_(e.x/i),y:O_(e.y/a)})),h=e=>({x:O_(e.x/i),y:O_(e.y/a)}),g=e=>e.reduce((t,n)=>({x:t.x+n.x/e.length,y:t.y+n.y/e.length}),{x:0,y:0}),_=g(l),v=g(u),y=Math.hypot(_.x-v.x,_.y-v.y),b=g(f),x=d&&d.length>0?d[Math.floor(d.length/2)]:void 0,S=(_.x+v.x)/2,C=x?(x.x-S)/Math.max(1e-6,y):void 0,w=k_(l),T=k_(u),E=e=>O_((e-.16)/.12),D=n.x/i,O=n.y/a,k=n.width/i,A=n.height/a,j=p&&p.length>0?p.reduce((e,t)=>t.x<e.x?t:e,p[0]):void 0,M=p&&p.length>0?p.reduce((e,t)=>t.x>e.x?t:e,p[0]):void 0,N=f&&f.length>0?f[Math.max(0,Math.min(f.length-1,4))]:void 0,P=f&&f.length>0?f[Math.max(0,Math.min(f.length-1,f.length-5))]:void 0,F=p&&p.length>=9?p[2]:void 0,ee=p&&p.length>=9?p[8]:void 0,te=F?h(F):void 0,ne=ee?h(ee):void 0,re=F&&ee?Math.abs(F.y-ee.y):0,ie=y>1e-6?re/y:0,ae=(e,t)=>e&&t?Math.hypot(e.x-t.x,e.y-t.y):0,I=ae(j,N),L=ae(M,P),oe=y>1e-6?I/y:0,se=y>1e-6?L/y:0,R,z;f&&f.length>=2&&(R=f.slice(0,5).reduce((e,t)=>t.y<e.y?t:e,f[0]),z=f.slice(-5).reduce((e,t)=>t.y<e.y?t:e,f[f.length-1]));let ce=R?h(R):void 0,le=z?h(z):void 0;return{faces:1,box:{x:D,y:O,width:k,height:A},centerX:O_(D+k/2),area:k*A,leftEyeOpenProb:E(w),rightEyeOpenProb:E(T),leftEyeCenter:{x:O_(_.x/i),y:O_(_.y/a)},rightEyeCenter:{x:O_(v.x/i),y:O_(v.y/a)},eyeDist:O_(y/Math.max(i,a)),yawProxy:C,mouthLeft:j?h(j):void 0,mouthRight:M?h(M):void 0,jawLeft:N?h(N):void 0,jawRight:P?h(P):void 0,mouthUpper:te,mouthLower:ne,mouthOpenPx:re,mouthOpenNorm:ie,mouthJawLeftDist:oe,mouthJawRightDist:se,jawTopL:ce,jawTopR:le,mouthJawLeftDistPx:I,mouthJawRightDistPx:L,leftEyePoints:m(l),rightEyePoints:m(u),noseTip:x?{x:O_(x.x/i),y:O_(x.y/a)}:void 0,nosePoints:d?m(d):void 0,mouthPoints:p?m(p):void 0,jawPoints:f?m(f):void 0,jawCenter:{x:O_(b.x/i),y:O_(b.y/a)},poseSource:`landmarks`}}let c=await s();return!c||c.length===0?{faces:0}:c.length>1?{faces:c.length}:o(c[0].box)}}}function M_(e,t){return{code:e,message:t}}function N_(e){return _(e?.strictness??.5)}function P_(e){let t=N_(e),n=e?.lookForwardTolerance;return _(typeof n==`number`?n:1-t)}function F_(e,t,n){let r=!!n?.current,i=n?.current??null,a=(t?.mirrorMode??`mirrored`)===`mirrored`;if(e.faces===0)return{feedback:M_(`FACE_NOT_FOUND`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1};if(e.faces>1)return{feedback:M_(`MULTIPLE_FACES`,`Apenas 1 rosto por vez`),valid:!1,frameOk:!1,stepOk:!1};if(!e.box)return{feedback:M_(`FACE_NOT_FOUND`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1};let o=N_(t),s=P_(t),{x:c,y:l,width:u,height:d}=e.box,f=c+u/2,p=l+d/2,m=e.centerX??f,h=p,v=e.area??u*d,y=u/Math.max(1e-6,d),b=.07+o*.02,x=.22-o*.03,S=.12-o*.03+(r?.16:0),C=t?.lookSideTol??.18-o*.05,w=t?.lookUpDownTol??.12-o*.03,T=t?.zoomInMinArea??.16+o*.02,E=t?.zoomOutMaxArea??.12-o*.02;if(i===`zoomIn`){let t=v>=T,n=_((v-E)/Math.max(1e-6,T-E));return{feedback:M_(`ZOOM_IN`,t?`Mantenha...`:`Aproxime-se da câmera`),valid:t,frameOk:!0,stepOk:t,debug:{strict:o,lfTol:s,forwardTol:0,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:e.eyeDist??0,noseDx:e.noseTip?e.noseTip.x-m:null,cx:f,cy:p,centerTol:S,faceArea:v,zoomInMinArea:T,zoomOutMaxArea:E,zoomProgress:n}}}if(i===`zoomOut`){let t=v<=E,n=_((T-v)/Math.max(1e-6,T-E));return{feedback:M_(`ZOOM_OUT`,t?`Mantenha...`:`Afaste-se da câmera`),valid:t,frameOk:!0,stepOk:t,debug:{strict:o,lfTol:s,forwardTol:0,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:e.eyeDist??0,noseDx:e.noseTip?e.noseTip.x-m:null,cx:f,cy:p,centerTol:S,faceArea:v,zoomInMinArea:T,zoomOutMaxArea:E,zoomProgress:n}}}let D=t?.blinkClosedThreshold??.65;t?.cheeseThreshold;let O=t?.openMouthThreshold??.5,k=e.eyeDist??0,A=e.noseTip?e.noseTip.x-m:null,j=.1-o*.02,M=typeof t?.lookForwardCenterTol==`number`?_(t.lookForwardCenterTol):_(j+s*.08);if(v<b)return{feedback:M_(`FACE_TOO_FAR`,`Aproxime o rosto`),valid:!1,frameOk:!1,stepOk:!1,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A}};if(v>x)return{feedback:M_(`FACE_TOO_CLOSE`,`Afaste o rosto`),valid:!1,frameOk:!1,stepOk:!1,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A}};if(Math.abs(f-.5)>S||Math.abs(p-.5)>S)return{feedback:M_(`FACE_OFF_CENTER`,`Centralize seu rosto`),valid:!1,frameOk:!1,stepOk:!1,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A}};let N=e.mouthLeft,P=e.mouthRight,F=e.jawLeft,ee=e.jawRight,te=N&&P?{x:(N.x+P.x)/2,y:(N.y+P.y)/2}:null,ne=F&&ee?{x:(F.x+ee.x)/2,y:(F.y+ee.y)/2}:null,re=e.box?.height??null,ie=te&&ne&&typeof re==`number`&&re>1e-6?(ne.y-te.y)/re:null,ae=ie==null?null:g(ie,-1,1),I=typeof e.mouthJawLeftDistPx==`number`?e.mouthJawLeftDistPx:null,L=typeof e.mouthJawRightDistPx==`number`?e.mouthJawRightDistPx:null,oe=1e3,se=(I!=null&&L!=null?I>500&&I<oe&&L>500&&L<oe:!1)&&(ie==null?!1:ie>=-.5&&ie<=.5),R=typeof t?.lookForwardOkSince==`number`?t.lookForwardOkSince:null,z=se&&R!=null?Date.now()-R>=1e3:!1,ce=n?.current??null;if(!ce)return{feedback:M_(`READY`,`Pronto para capturar`),valid:!0,frameOk:!0,stepOk:!0,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A}};_(t?.poseProgressAccept??.65);let le=typeof e.mouthJawLeftDist==`number`?e.mouthJawLeftDist:null,ue=typeof e.mouthJawRightDist==`number`?e.mouthJawRightDist:null,de=typeof t?.mouthJawBaselineLeft==`number`?t.mouthJawBaselineLeft:null,fe=typeof t?.mouthJawBaselineRight==`number`?t.mouthJawBaselineRight:null,pe=le!=null&&ue!=null,me=de!=null&&fe!=null,he=pe&&me?le-de:null,ge=pe&&me?ue-fe:null,_e=t?.lookSideNearThr??.3,ve=t?.lookSideFarThr??1,ye=pe?a?ue:le:null,be=pe?a?le:ue:null,xe=ye!=null&&be!=null&&ye<_e&&be>ve,Se=ye!=null&&be!=null&&be<_e&&ye>ve,Ce=Math.max(1e-6,ve-_e),we=e=>_((ve-e)/Ce),Te=e=>_((e-_e)/Ce),Ee=ye!=null&&be!=null?Math.min(we(ye),Te(be)):0,De=ye!=null&&be!=null?Math.min(we(be),Te(ye)):0,Oe=ae??null,ke=typeof t?.lookUpDownFullScaleEps==`number`?t.lookUpDownFullScaleEps:.02,Ae=typeof t?.lookUpDownFullThr==`number`?g(t.lookUpDownFullThr,.1,1):1;if(Oe!=null&&Oe>0&&_((Oe-0)/Math.max(1e-6,Ae)),Oe!=null&&Oe<0&&_((-Oe-0)/Math.max(1e-6,Ae)),1-ke,1-ke,ce===`lookForward`){let n=e.jawTopL,r=e.jawTopR,a=e.leftEyeCenter,c=e.rightEyeCenter,l,u,d,f;n&&a&&r&&c&&(l=Math.hypot(n.x-a.x,n.y-a.y),u=Math.hypot(r.x-c.x,r.y-c.y),d=Math.abs(l-u),f=d/Math.max(l,u,1e-6));let p=ie==null?!1:ie>=-.5&&ie<=.5,m=typeof f==`number`?f<=.25:!1,h=ie==null?!1:ie>=-.6&&ie<=.6,g=typeof f==`number`?f<=.3:!1,_=p&&m,v=h&&g,b=typeof t?.lookForwardHoldMs==`number`?t.lookForwardHoldMs:1e3,x=typeof t?.lookForwardOkSince==`number`?t.lookForwardOkSince:null;v?_&&x==null&&(x=Date.now()):x=null;let S=_&&x!=null?Date.now()-x:0,T=_&&x!=null?S>=b:!1,E=``;return E=T?`Pronto para capturar`:v?`Mantenha...`:`Olhe para frente`,{feedback:M_(T?`READY`:`LOOK_FORWARD`,E),valid:T,frameOk:T,stepOk:T,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,jawTopL:n,jawTopR:r,leftEyeCenter:a,rightEyeCenter:c,jawEyeDistL:l,jawEyeDistR:u,jawEyeDistDiff:d,jawEyeDistRelDiff:f,jawEyeRelTol:.25,mouthAvg:te,jawMid:ne,faceH:re,mouthVsJawMidRaw:ie,yOk:p,distOk:m,lookForwardOkInstant:_,lookForwardHeld:T,lookForwardHoldMs:b,lookForwardHeldMs:S,lookForwardOkSince:x,currentStep:i,stepPassed:T}}}if(i===`lookUp`||i===`lookDown`){let e=ae,n=typeof t?.lookUpDownThreshold==`number`?g(Math.abs(t.lookUpDownThreshold),.02,.9):.06,r=i===`lookUp`?typeof e==`number`?e>=n:!1:typeof e==`number`?e<=-n:!1,a=typeof e==`number`?_(i===`lookUp`?(e-n)/Math.max(1e-6,.1-n):(-e-n)/Math.max(1e-6,.1-n)):0;return{feedback:r?M_(i===`lookUp`?`LOOK_UP`:`LOOK_DOWN`,`Mantenha...`):i===`lookUp`?M_(`LOOK_UP`,`Olhe para cima`):M_(`LOOK_DOWN`,`Olhe para baixo`),valid:r,frameOk:r,stepOk:r,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,cx:m,cy:h,centerTol:S,currentStep:i,stepPassed:r,mouthAvg:te,jawMid:ne,faceH:re,mouthVsJawMidRaw:ie,mouthVsJawMidClamped:ae,lookUpProgress:i===`lookUp`?a:0,lookDownProgress:i===`lookDown`?a:0,lookUpDownThreshold:n,poseProgressSource:`mouthJaw`}}}if(ce===`lookLeft`){let e=xe;return{feedback:M_(`LOOK_LEFT`,`Olhe para a esquerda`),valid:e,frameOk:!0,stepOk:e,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,cx:f,cy:p,centerTol:S,lookForwardOk:z,lookLeftProgress:Ee,lookRightProgress:De,lookLeftRule:`L<${_e.toFixed(2)} && R>${ve.toFixed(2)}`,lookRightRule:`R<${_e.toFixed(2)} && L>${ve.toFixed(2)}`,lookLeftActualTarget:`L:${(ye??0).toFixed(3)}/${_e.toFixed(2)} R:${(be??0).toFixed(3)}/${ve.toFixed(2)}`,mouthJawLeftDist:le??void 0,mouthJawRightDist:ue??void 0,mouthJawBaselineLeft:de??void 0,mouthJawBaselineRight:fe??void 0,mouthJawDeltaLeft:he??void 0,mouthJawDeltaRight:ge??void 0,mouthJawThr:void 0,mouthJawRatioNormLeft:void 0,mouthJawRatioNormRight:void 0,mouthJawRatioNowLeftOverRight:void 0,mouthJawRatioNowRightOverLeft:void 0,mouthJawRatioBaseLeftOverRight:void 0,mouthJawRatioBaseRightOverLeft:void 0}}}if(ce===`lookRight`){let e=Se;return{feedback:M_(`LOOK_RIGHT`,`Olhe para a direita`),valid:e,frameOk:!0,stepOk:e,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,cx:f,cy:p,centerTol:S,lookForwardOk:z,lookLeftProgress:Ee,lookRightProgress:De,lookLeftRule:`L<${_e.toFixed(2)} && R>${ve.toFixed(2)}`,lookRightRule:`R<${_e.toFixed(2)} && L>${ve.toFixed(2)}`,lookRightActualTarget:`R:${(be??0).toFixed(3)}/${_e.toFixed(2)} L:${(ye??0).toFixed(3)}/${ve.toFixed(2)}`,mouthJawLeftDist:le??void 0,mouthJawRightDist:ue??void 0,mouthJawBaselineLeft:de??void 0,mouthJawBaselineRight:fe??void 0,mouthJawDeltaLeft:he??void 0,mouthJawDeltaRight:ge??void 0,mouthJawThr:void 0,mouthJawRatioNormLeft:void 0,mouthJawRatioNormRight:void 0,mouthJawRatioNowLeftOverRight:void 0,mouthJawRatioNowRightOverLeft:void 0,mouthJawRatioBaseLeftOverRight:void 0,mouthJawRatioBaseRightOverLeft:void 0}}}if(ce===`blink`){let t=e.leftEyeOpenProb,n=e.rightEyeOpenProb,r=typeof t==`number`&&typeof n==`number`&&t<D&&n<D,i=!!r;return{feedback:M_(`BLINK`,`Pisque`),valid:i,frameOk:!0,stepOk:i,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,leftEyeOpenProb:typeof t==`number`?t:void 0,rightEyeOpenProb:typeof n==`number`?n:void 0,blinkClosedThreshold:D,blinkIsClosed:!!r}}}if(ce===`cheese`){let n=e.mouthPoints,r=Array.isArray(n)&&n.length>=8,i=0;if(r){let e=n.map(e=>e.x),t=n.map(e=>e.y);i=(Math.max(...e)-Math.min(...e))/Math.max(1e-6,Math.max(...t)-Math.min(...t))}let a=t?.cheeseUseBaseline!==!1,c=typeof t?.cheeseBaseline==`number`?t.cheeseBaseline:void 0,l=t?.cheeseThreshold??.05,u;u=a&&typeof c==`number`?c+l:l;let d=r&&i>=u;return{feedback:M_(`CHEESE`,`Sorria`),valid:d,frameOk:!0,stepOk:d,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,mouthSmileRatio:r?i:void 0,cheeseThreshold:l,cheeseBaseline:typeof c==`number`?c:void 0,cheeseTarget:u}}}if(ce===`openMouth`){let t=e.mouthPoints,n=Array.isArray(t)&&t.length>=8,r=0;if(n){let e=t.map(e=>e.x),n=t.map(e=>e.y),i=Math.max(...e)-Math.min(...e);r=Math.max(1e-6,Math.max(...n)-Math.min(...n))/Math.max(1e-6,i)}let i=e.mouthUpper,a=e.mouthLower,c=e.mouthOpenPx,l=e.mouthOpenNorm,u=typeof l==`number`&&i&&a?l:r,d=n&&i&&a&&u>=O;return{feedback:M_(`OPEN_MOUTH`,`Abra a boca`),valid:d,frameOk:!0,stepOk:d,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,mouthOpenRatio:n&&i&&a?u:void 0,openMouthThreshold:O,...i===void 0?{}:{mouthUpper:i},...a===void 0?{}:{mouthLower:a},...c===void 0?{}:{mouthOpenPx:c},...l===void 0?{}:{mouthOpenNorm:u}}}}if(ce===`mouthWidth`){let t=e.mouthPoints,n=Array.isArray(t)&&t.length>=8,r=0;if(n){let e=t.map(e=>e.x),n=Math.max(...e)-Math.min(...e);r=k>1e-6?n/k:0}let i=.55,a=n&&r>i;return{feedback:M_(`CHEESE`,`Sorria (abra a boca lateralmente)`),valid:a,frameOk:a,stepOk:a,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,mouthWidthRatio:n?r:void 0,smileThreshold:i}}}return{feedback:M_(`READY`,`Pronto para capturar`),valid:!0,frameOk:!0,stepOk:!0,debug:{strict:o,lfTol:s,forwardTol:M,lookSideTol:C,lookUpDownTol:w,ratio:y,eyeDist:k,noseDx:A,cx:f,cy:p,centerTol:S,lookForwardOk:z}}}function I_(e){let t=document.createElement(`canvas`),n=t.getContext(`2d`),r=null;t.style.position=`absolute`,t.style.left=`0`,t.style.top=`0`,t.style.width=`100%`,t.style.height=`100%`,t.style.pointerEvents=`none`,getComputedStyle(e).position===`static`&&(e.style.position=`relative`),e.appendChild(t);function i(e,t,n,r){e.beginPath(),e.moveTo(t,n-r*.78),e.bezierCurveTo(t+r*1.15,n-r*.78,t+r*.65,n+r*1.1,t,n+r*1.18),e.bezierCurveTo(t-r*.65,n+r*1.1,t-r*1.15,n-r*.78,t,n-r*.78),e.closePath()}function a(e,t,n){let r=new Path2D;return r.moveTo(e,t-n*.78),r.bezierCurveTo(e+n*1.15,t-n*.78,e+n*.65,t+n*1.1,e,t+n*1.18),r.bezierCurveTo(e-n*.65,t+n*1.1,e-n*1.15,t-n*.78,e,t-n*.78),r.closePath(),r}function o(e,t,n,r=80){let i={x:e,y:t-n*.78},a={x:e,y:t+n*1.18},o={x:e+n*1.15,y:t-n*.78},s={x:e+n*.65,y:t+n*1.1},c={x:e-n*.65,y:t+n*1.1},l={x:e-n*1.15,y:t-n*.78},u=(e,t,n,r,i)=>{let a=1-i,o=i*i,s=a*a,c=s*a,l=o*i;return{x:c*e.x+3*s*i*t.x+3*a*o*n.x+l*r.x,y:c*e.y+3*s*i*t.y+3*a*o*n.y+l*r.y}},d=[],f=Math.max(2,Math.floor(r/2)),p=Math.max(2,r-f);for(let e=0;e<=f;e++){let t=e/f;d.push(u(i,o,s,a,t))}for(let e=1;e<=p;e++){let t=e/p;d.push(u(a,c,l,i,t))}return d}function s(e,t,n,r){let i=Math.max(0,Math.min(1,r));if(i<=0)return;let a=o(t/2,n*.36,Math.min(t,n)*.46*x,80),s=a.length,c=Math.max(1,Math.floor(i*(s-1)));e.save(),e.globalCompositeOperation=`source-over`,e.lineWidth=5,e.lineCap=`round`,e.lineJoin=`round`,e.strokeStyle=`#2ee59d`,e.shadowColor=`#2ee59d`,e.shadowBlur=i>=.999?14:8,e.beginPath(),e.moveTo(a[0].x,a[0].y);for(let t=1;t<=c;t++)e.lineTo(a[t].x,a[t].y);e.stroke(),e.restore()}function c(e,t){if(!n)return;k(n,e,t),n.save();let a=e/2,o=t*.36,c=Math.min(e,t)*.46*x;i(n,a,o,c),n.globalCompositeOperation=`destination-out`,n.fillStyle=`#fff`,n.fill(),n.restore(),n.save(),n.globalCompositeOperation=`source-over`,n.lineWidth=4,n.strokeStyle=A(),n.shadowColor=A(),n.shadowBlur=10,i(n,a,o,c),n.stroke(),n.restore();let l=typeof r?.debug?.challengeHoldProgress==`number`?r.debug.challengeHoldProgress:0;l>0&&s(n,e,t,l)}function l(e,t){if(!n)return;n.save();let r=e/2,a=t*.36,o=Math.min(e,t)*.46*x;n.save(),i(n,r,a,o),n.clip(),n.strokeStyle=`#fff`,n.lineWidth=2.2,n.shadowColor=`transparent`,n.shadowBlur=0;let s=u.x*o*.45,c=u.y*o*.45;n.beginPath(),n.moveTo(r,a-o*.78),n.bezierCurveTo(r+s*.5,a-o*.25+c*.2,r+s*.5,a+o*.65+c*.2,r,a+o*1.18),n.stroke(),n.beginPath(),n.moveTo(r-o*.95,a),n.bezierCurveTo(r-o*.25,a+o*.1+c,r+o*.25,a+o*.1+c,r+o*.95,a),n.stroke(),n.restore(),n.restore()}let u={x:0,y:0},d={x:0,y:0},f=0,p=`idle`,m=0,h={x:0,y:0},g=1.25;function _(e,t){let n=0,r=0,i=e.challenge?.direction;!i&&e.hint?.type===`arrow`&&(i=e.hint.direction),i===`left`?n=-1:i===`right`?n=1:i===`up`?r=-1:i===`down`&&(r=1),(n!==h.x||r!==h.y)&&(p=`hold`,m=0,h.x=n,h.y=r),n!==0||r!==0?p===`hold`?(d.x=n*g,d.y=r*g,m+=t,m>.7&&(p=`boomerang`,m=0)):p===`boomerang`?(d.x=0,d.y=0,m+=t,m>.28&&(p=`hold`,m=0)):(d.x=0,d.y=0):(d.x=0,d.y=0,p=`idle`)}function b(e){let t=8.5;u.x+=(d.x-u.x)*Math.min(1,e*t),u.y+=(d.y-u.y)*Math.min(1,e*t)}let x=1,S=1;function C(e){let t=e.debug?.feedbackCode;S=e.challenge?.direction===`zoomIn`||t===`ZOOM_IN`?1.28:e.challenge?.direction===`zoomOut`||t===`ZOOM_OUT`?.72:1}function w(e){x+=(S-x)*Math.min(1,e*3.8),Math.abs(x-S)<.001&&(x=S)}let T={IDLE:`IDLE`,CAMERA_ON:`CAMERA_ON`,FACE_DETECTED:`FACE_DETECTED`,ALIGNED:`ALIGNED`,SUCCESS:`SUCCESS`,FAIL:`FAIL`},E=T.IDLE;function D(e){if(!e.video){E=T.IDLE;return}if(!e.box){E=T.CAMERA_ON;return}if(e.box&&!e.valid){E=T.FACE_DETECTED;return}if(e.box&&e.valid){if(E=T.ALIGNED,e.debug?.stepPassed===!0){E=T.SUCCESS;return}if(e.debug?.stepPassed===!1){E=T.FAIL;return}return}E=T.IDLE}function O(e,t,r,i){let o=a(r/2,i*.36,Math.min(r,i)*.46*x);return n?.isPointInPath(o,e,t)??!1}function k(e,t,n){e.save(),e.clearRect(0,0,t,n),e.globalAlpha=.7,e.fillStyle=`#222`,e.fillRect(0,0,t,n),e.globalAlpha=1,e.restore()}function A(){switch(E){case T.FACE_DETECTED:return`#FF9800`;case T.ALIGNED:return`#FFD44D`;case T.SUCCESS:return`#2ee59d`;default:return`#FFD44D`}}function j(i){r=i,D(i);let{w:a,h:o}=v(t,e,n||void 0);if(!n)return;let s=y(a,o,i.video,i.videoObjectFit,!i.mirrored),u=performance.now(),d=f?(u-f)/1e3:.016;d>.1&&(d=.016),f=u;let p=i.landmarkDraw?.eyes!==!1,m=i.landmarkDraw?.mouth!==!1,h=i.landmarkDraw?.nose!==!1,g=i.landmarkDraw?.jaw!==!1,T=i.landmarkDraw?.mouthJaw!==!1,k=i.landmarkDraw||{};_(i,d),b(d),C(i),w(d),(i.challenge?.direction===`zoomIn`||i.challenge?.direction===`zoomOut`)&&console.log(`challenge.direction:`,i.challenge.direction,`guideScale:`,x,`targetScale:`,S),c(a,o),l(a,o),i.message&&(n.save(),n.font=`600 1.1rem system-ui, sans-serif`,n.textAlign=`center`,n.fillStyle=`#fff`,n.shadowColor=`#222`,n.shadowBlur=8,n.fillText(i.message,a/2,o*.76),n.restore());let A=p||m||h||g||T,j=i.debug?.extra?.showCoxinhaCenterDot===!0;if(i.box&&A&&j){let e=i.box.x+i.box.width/2,t=i.box.y+i.box.height/2,r=s.mapPt({x:e,y:t});n.save(),n.beginPath(),n.arc(r.x,r.y,7,0,Math.PI*2),n.fillStyle=O(r.x,r.y,a,o)?`#4caf50`:`#ff5252`,n.globalAlpha=.7,n.fill(),n.restore()}let M=i.landmarks;if(M){if(p&&(M.leftEye||M.rightEye)&&(n.save(),n.strokeStyle=`#4fc3f7`,n.lineWidth=2,M.leftEye&&(n.beginPath(),M.leftEye.forEach((e,t)=>{let r=s.mapPt(e);t===0?n.moveTo(r.x,r.y):n.lineTo(r.x,r.y)}),n.closePath(),n.stroke()),M.rightEye&&(n.beginPath(),M.rightEye.forEach((e,t)=>{let r=s.mapPt(e);t===0?n.moveTo(r.x,r.y):n.lineTo(r.x,r.y)}),n.closePath(),n.stroke()),n.restore()),m&&M.mouthPoints&&(n.save(),n.strokeStyle=`#ffb300`,n.lineWidth=2,n.beginPath(),M.mouthPoints.forEach((e,t)=>{let r=s.mapPt(e);t===0?n.moveTo(r.x,r.y):n.lineTo(r.x,r.y)}),n.closePath(),n.stroke(),n.restore()),g&&M.jawPoints&&(n.save(),n.strokeStyle=`#81c784`,n.lineWidth=2,n.beginPath(),M.jawPoints.forEach((e,t)=>{let r=s.mapPt(e);t===0?n.moveTo(r.x,r.y):n.lineTo(r.x,r.y)}),n.stroke(),n.restore()),h&&M.nosePoints&&(n.save(),n.strokeStyle=`#ba68c8`,n.lineWidth=2,n.beginPath(),M.nosePoints.forEach((e,t)=>{let r=s.mapPt(e);t===0?n.moveTo(r.x,r.y):n.lineTo(r.x,r.y)}),n.stroke(),n.restore()),T&&M.mouthLeft&&M.jawLeft){n.save(),n.strokeStyle=`#e57373`,n.lineWidth=2,n.beginPath();let e=s.mapPt(M.mouthLeft),t=s.mapPt(M.jawLeft);n.moveTo(e.x,e.y),n.lineTo(t.x,t.y),n.stroke(),n.restore()}if(T&&M.mouthRight&&M.jawRight){n.save(),n.strokeStyle=`#e57373`,n.lineWidth=2,n.beginPath();let e=s.mapPt(M.mouthRight),t=s.mapPt(M.jawRight);n.moveTo(e.x,e.y),n.lineTo(t.x,t.y),n.stroke(),n.restore()}}if(k.cheese&&i.debug?.cheeseBaseline!=null&&(n.save(),n.font=`bold 1rem system-ui, sans-serif`,n.fillStyle=`#FFD44D`,n.shadowColor=`#222`,n.shadowBlur=6,n.fillText(`cheese baseline: ${i.debug.cheeseBaseline.toFixed(3)}`,a/2,o*.08),i.debug.cheeseTarget!=null&&n.fillText(`cheese target: ${i.debug.cheeseTarget.toFixed(3)}`,a/2,o*.13),n.restore()),i.debug&&i.debug.extra?.showOverlayTableCanvas){let e=Math.min(520,Math.round(a*.62)),t=[];t.push(`drawLandmarks: ${i.debug.drawLandmarks===!1?`OFF`:`ON`}`),t.push(`draw: eyes=${p?`ON`:`OFF`} | mouth=${m?`ON`:`OFF`} | jaw=${g?`ON`:`OFF`} | nose=${h?`ON`:`OFF`} | mouth↔jaw=${T?`ON`:`OFF`}`),t.push(`cheese panel: ${k.cheese?`ON`:`OFF`}`),t.push(``),t.push(`Overlay State: ${E}`),typeof i.debug.status==`string`&&t.push(`Status: ${i.debug.status}`),typeof i.debug.ready==`boolean`&&t.push(`Ready: ${i.debug.ready}`),typeof i.debug.feedbackCode==`string`&&t.push(`Feedback: ${i.debug.feedbackCode}`),typeof i.debug.challenge==`string`&&t.push(`Challenge: ${i.debug.challenge}`);let r=typeof i.debug.faces==`number`?i.debug.faces:void 0,s=typeof i.debug.eyeL==`number`?i.debug.eyeL:void 0,c=typeof i.debug.eyeR==`number`?i.debug.eyeR:void 0;(r!=null||s!=null||c!=null)&&t.push(`Debug: faces=${r??`-`} | eyeL=${s==null?`-`:s.toFixed(2)} | eyeR=${c==null?`-`:c.toFixed(2)}`);let l=typeof i.debug.blinkCount==`number`?i.debug.blinkCount:void 0,u=typeof i.debug.blinkClosedNow==`boolean`?i.debug.blinkClosedNow:void 0,d=typeof i.debug.blinkClosedThreshold==`number`?i.debug.blinkClosedThreshold:void 0;(l!=null||u!=null||d!=null)&&t.push(`Blink: count=${l??`-`} | closedNow=${u??`-`} | thr=${d==null?`-`:d.toFixed(2)}`);let f=i.debug.mouthVsJawMidRaw,_=i.debug.mouthVsJawMidClamped;(typeof _==`number`||typeof f==`number`)&&t.push(`mouthAvg vs jawMid: ${typeof _==`number`?_.toFixed(2):`-`} (raw ${typeof f==`number`?f.toFixed(3):`-`})`);let v=i.debug.faceH;if(typeof v==`number`&&t.push(`faceH: ${v.toFixed(3)}`),typeof i.debug.stepPassed==`boolean`&&t.push(`stepPassed(${i.debug.currentStep??`-`}) = ${i.debug.stepPassed}`),i.debug.debugDraw?.cheese!==!1){let e=i.debug.mouthSmileRatio,n=i.debug.cheeseBaseline,r=i.debug.cheeseTarget;(typeof e==`number`||typeof n==`number`||typeof r==`number`)&&t.push(`Cheese: ratio=${typeof e==`number`?e.toFixed(3):`-`} | base=${typeof n==`number`?n.toFixed(3):`-`} | target=${typeof r==`number`?r.toFixed(3):`-`}`)}t.length===0&&t.push(`Debug ativo (nenhum dado)`);let y=24+t.length*16,b=Math.max(8,o-y-88);n.save(),n.fillStyle=`rgba(0,0,0,0.72)`,n.strokeStyle=`#FFD44D`,n.lineWidth=2,n.beginPath(),typeof n.roundRect==`function`?n.roundRect(12,b,e,y,10):n.rect(12,b,e,y),n.fill(),n.stroke(),n.fillStyle=`rgba(255,255,255,0.92)`,n.font=`12px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,n.textAlign=`left`,n.textBaseline=`top`;for(let e=0;e<t.length;e++)n.fillText(t[e],24,b+12+e*16);n.restore()}}function M(){t.remove()}return{canvas:t,dispose:M,render:j}}function L_(e){getComputedStyle(e).position===`static`&&(e.style.position=`relative`)}function R_(e){let{container:t,labels:n,onOk:r,onRetake:i}=e;L_(t);let a=document.createElement(`div`);a.className=`alphavalid-userPreview`,a.style.position=`absolute`,a.style.inset=`0`,a.style.display=`none`,a.style.alignItems=`center`,a.style.justifyContent=`center`,a.style.flexDirection=`column`,a.style.gap=`10px`,a.style.background=`rgba(0,0,0,0.45)`,a.style.backdropFilter=`blur(2px)`,a.style.zIndex=`999999`,a.style.pointerEvents=`auto`,a.style.touchAction=`manipulation`;let o=document.createElement(`img`);o.className=`alphavalid-userPreview-img`,o.alt=`preview`,o.style.width=`88%`,o.style.maxWidth=`360px`,o.style.maxHeight=`70%`,o.style.objectFit=`contain`,o.style.borderRadius=`16px`,o.style.boxShadow=`0 10px 28px rgba(0,0,0,0.35)`;let s=document.createElement(`div`);s.className=`alphavalid-userPreview-meta`,s.style.color=`#fff`,s.style.fontWeight=`600`,s.style.textAlign=`center`,s.style.fontSize=`0.95rem`,s.style.padding=`0 16px`;let c=document.createElement(`div`);c.className=`alphavalid-userPreview-actions`,c.style.display=`flex`,c.style.gap=`10px`,c.style.marginTop=`6px`,c.style.pointerEvents=`auto`,c.style.zIndex=`1000000`;let l=document.createElement(`button`);l.type=`button`,l.className=`alphavalid-userPreview-retake`,l.textContent=n?.retake??`Tirar outra`,l.style.padding=`10px 14px`,l.style.borderRadius=`12px`,l.style.border=`1px solid rgba(255,255,255,0.35)`,l.style.background=`rgba(0,0,0,0.35)`,l.style.color=`#fff`,l.style.fontWeight=`700`,l.style.cursor=`pointer`,l.style.pointerEvents=`auto`,l.style.touchAction=`manipulation`;let u=document.createElement(`button`);return u.type=`button`,u.className=`alphavalid-userPreview-ok`,u.textContent=n?.ok??`OK`,u.style.padding=`10px 16px`,u.style.borderRadius=`12px`,u.style.border=`1px solid rgba(255,255,255,0.35)`,u.style.background=`#ffffff`,u.style.color=`#111`,u.style.fontWeight=`800`,u.style.cursor=`pointer`,u.style.pointerEvents=`auto`,u.style.touchAction=`manipulation`,l.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),i()}),u.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),c.appendChild(l),c.appendChild(u),a.appendChild(o),a.appendChild(s),a.appendChild(c),t.appendChild(a),{show:(e,t)=>{o.src=e,s.textContent=t??``,a.style.display=`flex`},hide:()=>{a.style.display=`none`,o.removeAttribute(`src`),s.textContent=``},dispose:()=>{a.remove()}}}function z_(e){return{ok:e.previewOkText,retake:e.previewRetakeText}}var B_=`/images/alphaloader.gif`;function V_(e,t={}){let n=t.src??B_,r=t.sizePx??120,i=t.minVisibleMs??900,a=null,o=0,s=null,c=()=>{getComputedStyle(e).position===`static`&&(e.style.position=`relative`)},l=()=>{if(a)return a;c(),a=document.createElement(`div`),a.className=`alphavalid-camera-loader`,a.style.position=`absolute`,a.style.inset=`0`,a.style.display=`flex`,a.style.alignItems=`center`,a.style.justifyContent=`center`,a.style.background=`transparent`,a.style.zIndex=`999`;let t=document.createElement(`img`);return t.alt=`Carregando...`,t.src=n,t.style.width=`${r}px`,t.style.height=`${r}px`,a.appendChild(t),e.appendChild(a),a};return{show:()=>{s!=null&&(window.clearTimeout(s),s=null),l(),o=Date.now(),a&&(a.style.display=`flex`)},hide:()=>{if(!a)return;let e=Date.now()-o,t=Math.max(0,i-e);if(t>0){s!=null&&window.clearTimeout(s),s=window.setTimeout(()=>{s=null,a&&(a.style.display=`none`)},t);return}a.style.display=`none`},dispose:()=>{s!=null&&(window.clearTimeout(s),s=null),a?.remove(),a=null}}}function H_(e){getComputedStyle(e).position===`static`&&(e.style.position=`relative`)}function U_(e){let{container:t,text:n,color:r,onClick:i}=e;H_(t);let a=document.createElement(`button`);return a.type=`button`,a.className=`alphavalid-captureBtn`,a.textContent=n??`Capturar imagem`,a.style.position=`absolute`,a.style.left=`50%`,a.style.bottom=`calc(env(safe-area-inset-bottom, 0px) + 24px)`,a.style.transform=`translateX(-50%)`,a.style.width=`88%`,a.style.maxWidth=`340px`,a.style.height=`56px`,a.style.borderRadius=`18px`,a.style.border=`none`,a.style.background=r??`#00bcd4`,a.style.color=`#fff`,a.style.fontWeight=`800`,a.style.fontSize=`1.05rem`,a.style.cursor=`pointer`,a.style.zIndex=`999998`,a.style.boxShadow=`0 10px 22px rgba(0,0,0,0.28)`,a.style.touchAction=`manipulation`,a.style[`-webkit-tap-highlight-color`]=`transparent`,a.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),!a.disabled&&i()}),t.appendChild(a),{show:()=>{a.style.display=`block`},hide:()=>{a.style.display=`none`},dispose:()=>{a.remove()},setEnabled:e=>{a.disabled=!e,a.style.opacity=e?`1`:`0.55`}}}function W_(e){if(!(typeof document>`u`)){if(!document.getElementById(`alphavalid-base-styles`)){let e=document.createElement(`style`);e.id=`alphavalid-base-styles`,e.textContent=`
|
|
3805
|
+
/* Reset basics for full-screen portrait mobile UX */
|
|
3806
|
+
html, body { height: 100%; min-height: 100svh; margin: 0; padding: 0; }
|
|
3807
|
+
body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
|
|
3808
|
+
|
|
3809
|
+
/* Root container for SDK camera. By default we assume mobile/portrait usage */
|
|
3810
|
+
.alphavalid-root {
|
|
3811
|
+
position: relative !important;
|
|
3812
|
+
width: 100vw !important;
|
|
3813
|
+
height: 100svh !important;
|
|
3814
|
+
max-width: none !important;
|
|
3815
|
+
margin: 0 !important;
|
|
3816
|
+
background: #000 !important;
|
|
3817
|
+
overflow: hidden !important;
|
|
3818
|
+
touch-action: manipulation !important;
|
|
3819
|
+
-webkit-user-select: none !important;
|
|
3820
|
+
user-select: none !important;
|
|
3821
|
+
}
|
|
3822
|
+
|
|
3823
|
+
/* Ensure video fills container */
|
|
3824
|
+
.alphavalid-root video {
|
|
3825
|
+
display: block !important;
|
|
3826
|
+
width: 100% !important;
|
|
3827
|
+
height: 100% !important;
|
|
3828
|
+
object-fit: cover !important;
|
|
3829
|
+
transform-origin: center !important;
|
|
3830
|
+
}
|
|
3831
|
+
|
|
3832
|
+
/* Make sure loader and preview cover the area */
|
|
3833
|
+
.alphavalid-camera-loader { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; z-index: 999; }
|
|
3834
|
+
.alphavalid-userPreview { position: absolute; inset: 0; display: none; align-items: center; justify-content: center; z-index: 9999; }
|
|
3835
|
+
|
|
3836
|
+
/* Capture button sensible defaults */
|
|
3837
|
+
.alphavalid-captureBtn { -webkit-tap-highlight-color: transparent; }
|
|
3838
|
+
|
|
3839
|
+
/* Mobile-friendly font sizing for messages on small screens */
|
|
3840
|
+
@media (max-width: 420px) {
|
|
3841
|
+
.alphavalid-userPreview .alphavalid-userPreview-meta { font-size: 0.95rem; }
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3844
|
+
`,document.head.appendChild(e)}if(e)try{e.classList.add(`alphavalid-root`)}catch{}}}var G_=l({setupModels:()=>K_});async function K_(){function e(){return q_.default.existsSync(`angular.json`)?`angular`:q_.default.existsSync(`vite.config.js`)||q_.default.existsSync(`vite.config.ts`)||q_.default.existsSync(`index.html`)||q_.default.existsSync(`public`)?`vite`:`unknown`}function t(){let t=e();return t===`angular`?J_.default.join(`src`,`assets`,`alphavalid-models`):t===`vite`?J_.default.join(`public`,`alphavalid-models`):J_.default.join(`alphavalid-models`)}let n=J_.default.join(__dirname,`../models`),r=J_.default.resolve(process.cwd(),t());if(!q_.default.existsSync(n))throw Error(`[AlphaValid] Pasta de models não encontrada: `+n);q_.default.mkdirSync(r,{recursive:!0});for(let e of q_.default.readdirSync(n))q_.default.copyFileSync(J_.default.join(n,e),J_.default.join(r,e));return`[AlphaValid] Models copiados para ${r}`}var q_,J_,Y_=s((()=>{q_=d(x()),J_=d(x())})),X_=[`/assets/alphavalid-models`,`/alphavalid-models`],Z_=`cameraContainer`;async function Q_(e){for(let t of[`face_landmark_68_tiny_model-weights_manifest.json`,`face_landmark_68_tiny_model-shard1.bin`,`tiny_face_detector_model-weights_manifest.json`,`tiny_face_detector_model-shard1.bin`])try{if(!(await fetch(`${e}/${t}`,{method:`HEAD`})).ok)throw Error()}catch{throw Error(`\n[AlphaValid] Models não encontrados.\n\nExecute automaticamente:\nnpx alphavalid-sdk setup\n\nOu configure manualmente:\nmodelsPath: '${e}'\n`)}return e}async function $_(){let{setupModels:e}=await Promise.resolve().then(()=>(Y_(),G_));return e()}e.AlphaValid=class{_camera=null;_overlay=null;_container=null;_faceDetector=j_();_loopTimer=null;_lastStatusValid=!1;_options=null;_status=`idle`;_challengeIndex=0;_challengeStartedAt=null;_challengeEnterAt=null;_challengeCompletedAt=null;_challengeBaselineSeen=!1;_blinkArmed=!1;_state=null;_stableSince=null;_lastStableCx=null;_lastStableCy=null;_lastStableArea=null;_autoCaptureFired=!1;_lastGoodStatus=null;_lastGoodAt=0;_lastStatusForCaptureGate=null;_lastLookForwardGateOk=null;_forcedHintMessage=null;_poseLatch={left:0,right:0,up:0,down:0,at:0};_lastPoseChallenge=null;_mouthJawBaseline=null;_faceLostAt=null;_lookForwardOkSince=null;_blinkCount=0;_blinkPrevClosed=!1;_cheeseBaseline=null;_cheeseBaselineSamples=0;_cheeseBaselineSum=0;_cheeseBaselineStartedAt=null;_challengeHoldSince=null;_challengeLastStepOk=!1;_challengeHoldProgress=0;_challengeUiProgress=0;_startOptions=null;_previewBlob=null;_previewActions=null;_cheeseWindow=[];_cheeseWindowStart=null;_openMouthWindow=[];_openMouthWindowStart=null;_lifecycle=`idle`;_loopActive=!1;_debug=!1;_isCapturing=!1;_userPreviewUi=null;_userPreviewUrl=null;_loader=null;_captureBtn=null;_disposeCaptureButton(){try{this._captureBtn?.dispose()}catch{}this._captureBtn=null}_syncCaptureButton(e){let t=this._options;if(!t||!this._container)return;let n=t.uiMode===`Mobile`,r=t.captureButton?.enabled!==!1,i=t.autoCapture?.enabled===!0;if(!(n&&r&&!i)){this._captureBtn&&this._disposeCaptureButton();return}this._captureBtn||=U_({container:this._container,text:t.captureButton?.text??`Capturar imagem`,color:t.captureButton?.color??`#00bcd4`,onClick:()=>{this.capture().catch(()=>{})}});let a=e??this._state;if(this._lifecycle===`preview`){this._captureBtn.hide();return}let o=a?.challenge?.enabled?a.challenge.completed===!0:!0;this._lifecycle===`running`&&o?this._captureBtn.show():this._captureBtn.hide();let s=a?.isReadyToCapture===!0&&(a?.challenge?.enabled?a.challenge.completed===!0:!0),c=this._options?.requireLookForwardForCapture===!0,l=this._lastStatusForCaptureGate??this._lastGoodStatus??{},u=c?this._isLookForwardForCapture(l,{requireLf:c}):!0;c&&s&&!u?this._forcedHintMessage=`olhe para a camera`:this._forcedHintMessage=null,this._captureBtn.setEnabled(s&&u)}_setLifecycle(e){this._debug&&console.log(`[AlphaValid] lifecycle ${this._lifecycle} → ${e}`),this._lifecycle=e}async _pause(){if(this._lifecycle===`running`){this._loopTimer!=null&&(window.clearTimeout(this._loopTimer),this._loopTimer=null);try{this._camera?.video?.pause()}catch{}this._loopActive=!1,this._setLifecycle(`paused`)}}async _retakeFromPreview(){this._debug&&console.log(`[AlphaValid] preview action: retake()`,{lifecycle:this._lifecycle,hasCamera:!!this._camera,hasOptions:!!this._options,hasStartOptions:!!this._startOptions}),this._previewBlob=null,this._previewActions=null,this._hideUserPreviewUi();let e=this._startOptions;if(!e){this._debug&&console.warn(`[AlphaValid] retake ignored: missing _startOptions (cannot restart)`);return}try{await this.stop(),await this.start(e)}catch(e){throw this._debug&&console.error(`[AlphaValid] retake failed`,e),e}}async _confirmFromPreview(){if(this._debug&&console.log(`[AlphaValid] preview action: confirm()`,{lifecycle:this._lifecycle,hasBlob:!!this._previewBlob}),this._lifecycle!==`preview`){this._debug&&console.warn(`[AlphaValid] confirm ignored: not in preview`,{lifecycle:this._lifecycle});return}let e=this._previewBlob;if(e){if(this._options?.userPreview&&this._options?.uiMode===`Mobile`)try{this._options?.onUserPreviewConfirm?.(e)}catch{}else this._options?.autoCapture?.onCapture?.(e),this._options?.onCapture?.(e);this._hideUserPreviewUi(),this._previewBlob=null,this._previewActions=null,await this.stop()}}_hideUserPreviewUi(){try{this._userPreviewUi?.hide()}catch{}if(this._userPreviewUrl){try{URL.revokeObjectURL(this._userPreviewUrl)}catch{}this._userPreviewUrl=null}}_disposeUserPreviewUi(){this._hideUserPreviewUi();try{this._userPreviewUi?.dispose()}catch{}this._userPreviewUi=null}async _showPreview(e){if(this._debug&&console.log(`[AlphaValid] entering preview`,{lifecycle:this._lifecycle,blobSize:e?.size}),this._lifecycle!==`paused`&&this._lifecycle!==`preview`){this._debug&&console.warn(`[AlphaValid] _showPreview ignored due to lifecycle`,{lifecycle:this._lifecycle});return}this._setLifecycle(`preview`),this._previewBlob=e,this._previewActions={retake:()=>{this._debug&&console.log(`[AlphaValid] preview action clicked: retake`),this._retakeFromPreview()},confirm:()=>{this._debug&&console.log(`[AlphaValid] preview action clicked: confirm`),this._confirmFromPreview()}};let t=this._options;if(t?.userPreview&&t?.uiMode===`Mobile`&&this._container&&t){if(this._userPreviewUi||=R_({container:this._container,labels:z_(t),onOk:()=>this._previewActions?.confirm(),onRetake:()=>this._previewActions?.retake()}),this._userPreviewUrl)try{URL.revokeObjectURL(this._userPreviewUrl)}catch{}this._userPreviewUrl=URL.createObjectURL(e);let n=`preview: ${(e.size/1024).toFixed(1)} KB · ${new Date().toLocaleTimeString()}`;this._userPreviewUi.show(this._userPreviewUrl,n);return}t?.onPreview?.(e,this._previewActions)}_setVideoVisibility(e){let t=this._camera?.video;if(t)try{e?(t.style.visibility=`visible`,t.style.opacity=`1`,t.style.pointerEvents=`auto`):(t.style.visibility=`hidden`,t.style.opacity=`0`,t.style.pointerEvents=`none`),t.style.transition||(t.style.transition=`opacity 160ms ease`)}catch{}}async start(e){if(this._lifecycle===`running`||this._lifecycle===`preview`)return;this._debug=typeof e.debug==`boolean`?e.debug:!!e.debug?.enabled;let t=e.container??document.getElementById(Z_);if(!t)throw Error(`[AlphaValid] Container nao encontrado. Informe options.container ou crie <div id="${Z_}"></div>.`);f(t,`options.container`);let n=e.liveness;if(e.livenessPreset){let t=e.livenessPreset,r={};t===`normal`||(t===`easy`?(r.strictness=.3,r.lookForwardTolerance=.85,r.lookForwardYawTol=.1,r.lookSideTol=.08,r.lookUpDownTol=.16,r.poseProgressAccept=.55):t===`strict`&&(r.strictness=.8,r.lookForwardTolerance=.6,r.lookForwardYawTol=.04,r.lookSideTol=.03,r.lookUpDownTol=.08,r.poseProgressAccept=.8,r.lookForwardHoldMs=1200,r.challengeMinHoldMs=220)),n={...r,...e.liveness}}let r={...e,container:t,liveness:n};this._startOptions=r,await this.stop(),this._blinkCount=0,this._blinkPrevClosed=!1,this._options={overlay:!0,uiMode:`Mobile`,guideCircleRatio:.72,detectionIntervalMs:50,modelsPath:`/alphavalid-models`,userPreview:!0,previewOkText:`OK`,previewRetakeText:`Tirar outra`,loader:{enabled:!0,src:`/images/alphaloader.gif`,sizePx:120,minVisibleMs:900},captureButton:{enabled:!0,text:`Capturar imagem`,color:`#00bcd4`},requireLookForwardForCapture:!0,...r};let i=this._options;this._container=t;let a=t;if(!a)throw Error(`[AlphaValid] Container nao encontrado apos inicializacao.`);try{W_(a)}catch{}i.loader?.enabled!==!1&&(this._loader?.dispose(),this._loader=V_(a,i.loader),this._loader.show()),this._disposeCaptureButton(),this._status=`initializing`,i.onStateChange?.({status:this._status,feedback:{code:`INITIALIZING`,message:`Inicializando câmera...`},message:`Inicializando câmera...`,isReadyToCapture:!1,challenge:{enabled:!1,index:0,total:0,completed:!1}});try{i.onFeedback?.({code:`INITIALIZING`,message:`Inicializando câmera...`}),this._camera=await m(a),this._setVideoVisibility(!1),i.uiMode!==`headless`&&i.overlay!==!1&&(i.uiMode===`Mobile`?this._overlay=I_(a):this._overlay=b(a,i.guideCircleRatio));let t=i.modelsPath;if(t)await Q_(t);else{for(let n of X_)try{await Q_(n),t=n,e.debug&&console.log(`[AlphaValid] Models encontrados em: ${n}`);break}catch{}if(!t)throw Error(`
|
|
3845
|
+
[AlphaValid] Models não encontrados.
|
|
3846
|
+
|
|
3847
|
+
Execute automaticamente:
|
|
3848
|
+
npx alphavalid-sdk setup
|
|
3849
|
+
|
|
3850
|
+
Ou configure manualmente:
|
|
3851
|
+
modelsPath: '/assets/alphavalid-models'
|
|
3852
|
+
`)}await this._faceDetector.load(t),this._loader?.hide(),this._setVideoVisibility(!0),this._syncCaptureButton(null),i.onReady?.(),this._status=`running`,this._setLifecycle(`running`),this.startDetectionLoop()}catch(e){this._loader?.hide(),this._disposeCaptureButton(),this._setVideoVisibility(!1),this._status=`error`;let t=e,n=t&&typeof t==`object`&&typeof t.code==`string`&&typeof t.message==`string`?t:{code:`CAMERA_UNKNOWN`,message:`Erro inesperado ao iniciar o SDK.`,cause:e};throw this._options?.onError?.(n),this._options?.onStateChange?.({status:this._status,feedback:{code:`FACE_NOT_FOUND`,message:`Centralize seu rosto`},message:`Centralize seu rosto`,isReadyToCapture:!1,challenge:{enabled:!1,index:0,total:0,completed:!1}}),await this.stop(),e}e.debug&&(console.log(`[AlphaValid] SDK iniciado`),console.log(`[AlphaValid] modelsPath:`,e.modelsPath))}async stop(){this._loopTimer!=null&&(window.clearTimeout(this._loopTimer),this._loopTimer=null),this._loopActive=!1,this._lastStatusValid=!1,this._overlay&&=(this._overlay.dispose(),null),this._camera&&=(this._setVideoVisibility(!1),this._camera.stop(),null),this._previewBlob=null,this._previewActions=null,this._disposeUserPreviewUi(),this._disposeCaptureButton(),this._loader&&=(this._loader.dispose(),null),this._container=null,this._options=null,this._challengeIndex=0,this._challengeStartedAt=null,this._challengeEnterAt=null,this._challengeCompletedAt=null,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._state=null,this._lifecycle===`idle`?this._status=`idle`:this._status=`stopped`,this._stableSince=null,this._lastStableCx=null,this._lastStableCy=null,this._lastStableArea=null,this._autoCaptureFired=!1,this._lastGoodStatus=null,this._lastGoodAt=0,this._faceLostAt=null,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._mouthJawBaseline=null,this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress=0,this._blinkCount=0,this._blinkPrevClosed=!1,this._cheeseBaseline=null,this._cheeseBaselineSamples=0,this._cheeseBaselineSum=0,this._cheeseBaselineStartedAt=null,this._setLifecycle(`stopped`)}get _isInPreview(){return this._lifecycle===`preview`}async capture(){if(this._lifecycle!==`running`)throw Error(`SDK is not running. Call start() first.`);if(this._isCapturing)throw Error(`Capture already in progress.`);this._isCapturing=!0;try{if(!this._camera)throw Error(`Camera not started. Call start() first.`);if(this._options?.requireLookForwardForCapture===!0){let e=this._lastStatusForCaptureGate??this._lastGoodStatus??{},t=this._isLookForwardForCapture(e);if(console.log(`[AlphaValid][capture][lookForwardGate]`,{ok:t,jawTopL:e?.jawTopL,jawTopR:e?.jawTopR,leftEyeCenter:e?.leftEyeCenter,rightEyeCenter:e?.rightEyeCenter,mouthVsJawMidRaw:e?.mouthVsJawMidRaw,poseSource:e?.poseSource,faces:e?.faces}),!t)throw Error(`LookForward gate blocked capture. User is not facing forward.`)}if(!this._lastStatusValid)throw Error(`Face not valid for capture yet. Wait for feedback "Pronto para capturar".`);if(this._isInPreview)throw Error(`Já existe uma captura em preview.`);let e=await h(this._camera.video,.9);return await this._pause(),(this._options?.userPreview&&this._options?.uiMode===`Mobile`||this._options?.onPreview)&&(this._syncCaptureButton({...this._state,isReadyToCapture:!1}),await this._showPreview(e)),e}finally{this._isCapturing=!1}}getState(){return this._state}resetChallenges(){this._challengeIndex=0,this._challengeStartedAt=null,this._challengeEnterAt=null,this._challengeCompletedAt=null,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._stableSince=null,this._autoCaptureFired=!1,this._mouthJawBaseline=null,this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress=0}getCurrentChallenge(){let e=this._options?.liveness?.challenges;return!e||e.length===0?null:e[this._challengeIndex]?.type??null}markStepCompletedIfNeeded(e,t){let n=this._options,r=n?.liveness?.challenges;if(!n||!r||r.length===0)return;let i=this.getCurrentChallenge();if(!i)return;let a=n.liveness?.challengeMinHoldMs??350,o=Date.now(),s=`${this._challengeIndex}:${i}`;this._uiStepKey!==s&&(this._uiStepKey=s,this._challengeUiProgress=0);let c=(i===`lookUp`||i===`lookDown`)&&e===!0,l=i!==`lookForward`,u=c?!0:e;if(i===`blink`){let e=t?.leftEyeOpenProb,n=t?.rightEyeOpenProb;if(typeof e!=`number`||typeof n!=`number`)return;let r=.9,i=e<r&&n<r;if(!this._blinkArmed){if(!(e>=r&&n>=r))return;this._blinkArmed=!0;return}if(!i)return;this._blinkCount+=1,l=!1,u=!0}if(i===`cheese`){let e=t?.mouthSmileRatio,n=this._options?.liveness?.cheeseThreshold??.08,r;if(this._options?.liveness?.cheeseUseBaseline!==!1&&this._cheeseBaseline!=null?r=this._cheeseBaseline+n:this._options?.liveness?.cheeseUseBaseline===!1&&(r=n),typeof e==`number`&&typeof r==`number`&&e>r){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._cheeseWindow=[],this._cheeseWindowStart=null;return}}if(i===`openMouth`){let e=t?.mouthOpenRatio;if(typeof e==`number`&&e>.5){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._openMouthWindow=[],this._openMouthWindowStart=null;return}}if(i===`mouthWidth`){let e=t?.mouthWidthRatio;window.mouthWidthRatioDebug=e,console.log(`[AlphaValid][mouthWidth][REALTIME] mouthWidthRatio:`,e,`| challengeIndex:`,this._challengeIndex,`| debug:`,t)}if((i===`cheese`||i===`openMouth`)&&!t?.stepPassed&&(u=!1),l){if(i===`lookLeft`||i===`lookRight`||i===`lookUp`||i===`lookDown`){let e=typeof t?.poseProgress==`number`?t.poseProgress:0,n=Math.max(0,Math.min(1,e));if(!(u&&n>=.98)){this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress+=(n-this._challengeUiProgress)*.22;return}this._challengeHoldSince||=o;let r=Math.max(0,o-this._challengeHoldSince);if(this._challengeHoldProgress=Math.max(0,Math.min(1,a>0?r/a:1)),this._challengeUiProgress+=(1-this._challengeUiProgress)*.22,r>=a){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress=0;return}this._challengeLastStepOk=!0;return}if(u){(!this._challengeHoldSince||!this._challengeLastStepOk)&&(this._challengeHoldSince=o);let e=Math.max(0,o-(this._challengeHoldSince??o)),t=Math.max(0,Math.min(1,a>0?e/a:1));if(this._challengeHoldProgress=t,this._challengeUiProgress+=(t-this._challengeUiProgress)*.25,e>=a){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress=0;return}this._challengeLastStepOk=!0}else this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress+=(0-this._challengeUiProgress)*.35;return}if(i===`lookForward`){if(this._state?.feedback?.code===`READY`){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1;return}if(!e){this._challengeEnterAt=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1;return}return}if(i===`openMouth`){let e=t?.mouthOpenRatio;if(typeof e==`number`&&e>.5){this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._openMouthWindow=[],this._openMouthWindowStart=null;return}}u&&(this._challengeIndex+=1,this._challengeStartedAt=o,this._challengeEnterAt=o,this._challengeCompletedAt=o,this._challengeBaselineSeen=!1,this._blinkArmed=!1,this._poseLatch={left:0,right:0,up:0,down:0,at:0},this._lookForwardOkSince=null,this._challengeHoldSince=null,this._challengeLastStepOk=!1)}mapChallengeToHint(e,t){if(e)return e===`lookLeft`?{type:`arrow`,direction:`left`,label:t}:e===`lookRight`?{type:`arrow`,direction:`right`,label:t}:e===`lookUp`?{type:`arrow`,direction:`up`,label:t}:e===`lookDown`?{type:`arrow`,direction:`down`,label:t}:{type:`pulse`,label:t}}isStableFrame(e){let t=e.box;if(!t)return!1;let n=e.centerX??t.x+t.width/2,r=t.y+t.height/2,i=e.area??t.width*t.height,a=.015;if(this._lastStableCx==null||this._lastStableCy==null||this._lastStableArea==null)return this._lastStableCx=n,this._lastStableCy=r,this._lastStableArea=i,!1;let o=Math.abs(n-this._lastStableCx),s=Math.abs(r-this._lastStableCy),c=Math.abs(i-this._lastStableArea),l=o<=a&&s<=a&&c<=.015,u=(e,t,n)=>e+(t-e)*n,d=l?.15:.35;return this._lastStableCx=u(this._lastStableCx,n,d),this._lastStableCy=u(this._lastStableCy,r,d),this._lastStableArea=u(this._lastStableArea,i,d),l}_isLookForwardForCapture(e,t){let n=e?.jawTopL,r=e?.jawTopR,i=e?.leftEyeCenter,a=e?.rightEyeCenter,o=typeof e?.mouthVsJawMidRaw==`number`?e.mouthVsJawMidRaw:null;if(o==null){let t=e?.mouthLeft,n=e?.mouthRight,r=e?.jawLeft,i=e?.jawRight,a=e?.box?.height;if(t&&n&&r&&i&&typeof a==`number`&&a>1e-6){let e=(t.y+n.y)/2;o=((r.y+i.y)/2-e)/a}}let s=t?.requireLf===!0;if(!n||!r||!i||!a)return!s;let c=Math.hypot(n.x-i.x,n.y-i.y),l=Math.hypot(r.x-a.x,r.y-a.y);return Math.abs(c-l)/Math.max(c,l,1e-6)<=.45&&(typeof o==`number`?o>=-.75&&o<=.75:!0)}startDetectionLoop(){if(this._lifecycle!==`running`||this._loopActive)return;this._loopActive=!0;let e=async()=>{if(!this._loopActive)return;if(this._lifecycle!==`running`){this._loopActive=!1;return}let t=this._startOptions;if(!t){this._loopActive=!1;return}try{let e=this._camera,n=this._options;if(!e||!n){this._loopActive=!1;return}if(this._lifecycle!==`running`){this._loopActive=!1;return}let r=n.liveness?.challenges,i=!!r&&r.length>0,a=r?.length??0,o=!i||this._challengeIndex>=a,s=this.getCurrentChallenge(),c=o?null:s,l=n?.requireLookForwardForCapture===!0,u=n.debug?.drawLandmarks===!0||c!=null||l,d=await this._faceDetector.detect(e.video,{withLandmarks:u});this._lastStatusForCaptureGate=d;let f=c===`lookLeft`||c===`lookRight`||c===`lookUp`||c===`lookDown`,p=n.liveness?.poseGraceMs??900,m=Math.max(p,1400),h=n.liveness?.faceLostGraceMs??900,g=Date.now();d.faces===1&&d.box?(this._lastGoodStatus=d,this._lastGoodAt=g,this._faceLostAt=null):(this._faceLostAt??=g,this._lastGoodStatus&&g-(this._faceLostAt??g)<=h||f&&this._lastGoodStatus&&g-this._lastGoodAt<=m?d=this._lastGoodStatus:f&&(this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._poseLatch={left:0,right:0,up:0,down:0,at:0}));let _=this._faceLostAt!=null&&g-this._faceLostAt<=h,v=F_(d,{...n.liveness,mouthJawBaselineLeft:this._mouthJawBaseline?.left,mouthJawBaselineRight:this._mouthJawBaseline?.right,cheeseBaseline:this._cheeseBaseline??void 0,lookForwardOkSince:this._lookForwardOkSince},n.liveness?.challenges?.length?{current:c}:void 0),y=.9,b=d.leftEyeOpenProb,x=d.rightEyeOpenProb,S=typeof b==`number`&&typeof x==`number`?b<y&&x<y:!1;if(S&&!this._blinkPrevClosed&&(this._blinkCount+=1),this._blinkPrevClosed=S,c===`lookForward`&&v?.debug?.lookForwardOkInstant===!0?this._lookForwardOkSince??=Date.now():this._lookForwardOkSince=null,c===`lookForward`){let e=d.mouthJawLeftDist,t=d.mouthJawRightDist,n=v?.debug?.lookForwardOk;if(typeof e==`number`&&typeof t==`number`&&n){let n=Date.now();if(!this._mouthJawBaseline)this._mouthJawBaseline={left:e,right:t,at:n};else{let r=.18;this._mouthJawBaseline.left=this._mouthJawBaseline.left+(e-this._mouthJawBaseline.left)*r,this._mouthJawBaseline.right=this._mouthJawBaseline.right+(t-this._mouthJawBaseline.right)*r,this._mouthJawBaseline.at=n}}}let C=Date.now();if(f){let e=v?.debug,t=typeof e?.lookLeftProgress==`number`?e.lookLeftProgress:0,n=typeof e?.lookRightProgress==`number`?e.lookRightProgress:0,r=typeof e?.lookUpProgress==`number`?e.lookUpProgress:0,i=typeof e?.lookDownProgress==`number`?e.lookDownProgress:0,a=(this._poseLatch.at?Math.max(0,C-this._poseLatch.at):0)*9e-4,o=(e,t)=>{let n=Math.max(0,e-a);return Math.max(0,Math.min(1,Math.max(n,t)))};this._poseLatch.left=o(this._poseLatch.left,t),this._poseLatch.right=o(this._poseLatch.right,n),this._poseLatch.up=o(this._poseLatch.up,r),this._poseLatch.down=o(this._poseLatch.down,i),this._poseLatch.at=C,v?.debug&&(v.debug.lookLeftProgress=this._poseLatch.left,v.debug.lookRightProgress=this._poseLatch.right,v.debug.lookUpProgress=this._poseLatch.up,v.debug.lookDownProgress=this._poseLatch.down)}else this._poseLatch={left:0,right:0,up:0,down:0,at:0};if(this.markStepCompletedIfNeeded(v.stepOk,{leftEyeOpenProb:d.leftEyeOpenProb,rightEyeOpenProb:d.rightEyeOpenProb,stepPassed:v.debug?.stepPassed,mouthOpenRatio:d.mouthOpenNorm,mouthWidthRatio:v.debug?.mouthWidthRatio,poseProgress:c===`lookLeft`?this._poseLatch.left:c===`lookRight`?this._poseLatch.right:c===`lookUp`?this._poseLatch.up:c===`lookDown`?this._poseLatch.down:0}),c===`zoomIn`||c===`zoomOut`){let e=v.debug?.zoomProgress,t=.55*(typeof e==`number`?Math.max(0,Math.min(1,e)):0);if(v.stepOk){let e=this._options?.liveness?.challengeMinHoldMs??350,n=Date.now();this._challengeHoldSince||=n;let r=Math.max(0,n-this._challengeHoldSince),i=Math.max(0,Math.min(1,e>0?r/e:1));this._challengeHoldProgress=i;let a=.55+.45*i;this._challengeUiProgress+=(Math.max(t,a)-this._challengeUiProgress)*.22}else this._challengeHoldSince=null,this._challengeLastStepOk=!1,this._challengeHoldProgress=0,this._challengeUiProgress+=(t-this._challengeUiProgress)*.22}let w=!i||this._challengeIndex>=a,T=t.autoCapture?.enabled===!0,E=t.autoCapture?.stableMs??650,D=v.frameOk&&w,O=t?.requireLookForwardForCapture===!0,k=this._lastStatusForCaptureGate??d,A=O?this._isLookForwardForCapture(k,{requireLf:O}):!0;this._lastLookForwardGateOk=A,A||(D=!1),O&&v.frameOk&&w&&console.log(`[AlphaValid][readyGate][lookForward]`,{lfOkForCapture:A,jawTopL:d?.jawTopL,jawTopR:d?.jawTopR,leftEyeCenter:d?.leftEyeCenter,rightEyeCenter:d?.rightEyeCenter,mouthVsJawMidRaw:d?.mouthVsJawMidRaw,poseSource:d?.poseSource}),T&&D?this.isStableFrame(d)?(this._stableSince??=Date.now(),Date.now()-this._stableSince<E&&(D=!1)):(this._stableSince=null,D=!1):this._stableSince=null,this._lastStatusValid=D,this._status=D?`ready`:`running`;let j;j=w?v.feedback.message:v.feedback.code===`READY`?`Siga o desafio`:v.feedback.message,O&&w&&this._lastLookForwardGateOk===!1&&(j=`olhe para a camera`,v.feedback={...v.feedback,code:`LOOK_FORWARD`,message:j});let M=t.liveness?.cheeseThreshold??.08;t.liveness?.cheeseUseBaseline!==!1&&this._cheeseBaseline!=null?this._cheeseBaseline+M:t.liveness?.cheeseUseBaseline;let N={status:this._status,feedback:{...v.feedback,message:j},message:j,isReadyToCapture:D,challenge:{enabled:i,index:this._challengeIndex,total:t.liveness?.challenges?.length??0,current:c??void 0,completed:w},debug:{faces:d.faces,centerX:d.centerX,box:d.box,eyeDist:d.eyeDist,yawProxy:d.yawProxy,leftEyeOpenProb:d.leftEyeOpenProb,rightEyeOpenProb:d.rightEyeOpenProb,blinkCount:this._blinkCount,blinkClosedNow:S,blinkClosedThreshold:y,mouthDebug:{mouthPoints:d.mouthPoints,mouthLeft:d.mouthLeft,mouthRight:d.mouthRight,mouthUpper:d.mouthUpper,mouthLower:d.mouthLower,mouthOpenPx:d.mouthOpenPx,mouthOpenNorm:d.mouthOpenNorm,mouthJawLeftDist:d.mouthJawLeftDist,mouthJawRightDist:d.mouthJawRightDist,mouthSmileRatio:v.debug?.mouthSmileRatio,mouthWidthRatio:v.debug?.mouthWidthRatio,mouthAvg:v.debug?.mouthAvg,mouthVsJawMidRaw:v.debug?.mouthVsJawMidRaw,mouthVsJawMidClamped:v.debug?.mouthVsJawMidClamped,cheeseBaseline:v.debug?.cheeseBaseline,cheeseTarget:v.debug?.cheeseTarget,mouthOpenRatio:v.debug?.mouthOpenRatio},debugDraw:{cheese:n.debug?.draw?.cheese??!0},mouthAvg:v.debug?.mouthAvg??null,jawMid:v.debug?.jawMid??null,faceH:v.debug?.faceH??null,mouthVsJawMidRaw:v.debug?.mouthVsJawMidRaw??null,mouthVsJawMidClamped:v.debug?.mouthVsJawMidClamped??null,currentStep:v.debug?.currentStep??c??null,stepPassed:v.debug?.stepPassed,challengeHoldProgress:this._challengeHoldProgress}};if(this._state=N,t.onStateChange?.(N),t.onFeedback?.(N.feedback),this._syncCaptureButton(N),T&&D&&!this._autoCaptureFired&&!this._isInPreview){this._autoCaptureFired=!0;try{let e=await this.capture();t.onPreview||t.autoCapture?.onCapture?.(e)}catch{this._autoCaptureFired=!1}}D||(this._autoCaptureFired=!1);let P=n.debug?.drawLandmarks===!0,F=n.debug?.draw,ee=(F?.eyes??!1)||(F?.mouth??!1)||(F?.nose??!1)||(F?.jaw??!1)||(F?.mouthJaw??!1),te=w?void 0:this.mapChallengeToHint(c,N.feedback.message),ne=typeof d.yawProxy==`number`?d.yawProxy:null,re=ne==null?Math.max(-1,Math.min(1,((d.centerX??.5)-.5)/.18)):Math.max(-1,Math.min(1,ne/.22)),ie=Math.max(-1,Math.min(1,((d.box?.y??0)+(d.box?.height??0)/2-.5)/.18)),ae=ne==null?`centerX`:`yawProxy`;if(c===`mouthWidth`){let e=N.debug?.mouthWidthRatio;typeof e==`number`&&console.log(`[AlphaValid][landmarks] mouthWidthRatio:`,e)}if(this._overlay){let t;c===`zoomIn`&&(t=`zoomIn`),c===`zoomOut`&&(t=`zoomOut`);let r=n.uiMode===`Mobile`,i=n?.debug?.extra??{},a=i?.showCoxinhaGuides===!0;i?.showCoxinhaProgress;let o=this._forcedHintMessage??N.feedback.message;this._overlay.render({message:o,box:d.box,valid:D,hint:te,challenge:t?{direction:t}:void 0,debug:{blinkClosedNow:S,blinkClosedThreshold:y,challengeHoldProgress:this._challengeUiProgress,mouthDebug:{mouthPoints:d.mouthPoints,mouthLeft:d.mouthLeft,mouthRight:d.mouthRight,mouthUpper:d.mouthUpper,mouthLower:d.mouthLower,mouthOpenPx:d.mouthOpenPx,mouthOpenNorm:d.mouthOpenNorm,mouthJawLeftDist:d.mouthJawLeftDist,mouthJawRightDist:d.mouthJawRightDist,mouthSmileRatio:N.debug?.mouthSmileRatio,mouthWidthRatio:N.debug?.mouthWidthRatio,mouthAvg:N.debug?.mouthAvg,mouthVsJawMidRaw:N.debug?.mouthVsJawMidRaw,mouthVsJawMidClamped:N.debug?.mouthVsJawMidClamped,cheeseBaseline:N.debug?.cheeseBaseline,cheeseTarget:N.debug?.cheeseTarget,mouthOpenRatio:N.debug?.mouthOpenRatio},debugDraw:{cheese:N.debug?.debugDraw?.cheese},mouthAvg:N.debug?.mouthAvg??null,jawMid:N.debug?.jawMid??null,faceH:N.debug?.faceH??null,mouthVsJawMidRaw:N.debug?.mouthVsJawMidRaw??null,mouthVsJawMidClamped:N.debug?.mouthVsJawMidClamped??null,currentStep:N.debug?.currentStep??N.challenge?.current??null,stepPassed:N.debug?.stepPassed,extra:n.debug?.extra},video:e.video,mirrored:!1,poseVector:r&&!a?void 0:{x:re,y:ie,label:ae},landmarks:(P||ee)&&!_?{leftEye:d.leftEyePoints,rightEye:d.rightEyePoints,leftEyeCenter:d.leftEyeCenter,rightEyeCenter:d.rightEyeCenter,noseTip:d.noseTip,nosePoints:d.nosePoints,mouthPoints:d.mouthPoints,mouthLeft:d.mouthLeft,mouthRight:d.mouthRight,jawLeft:d.jawLeft,jawRight:d.jawRight,mouthJawLeftDist:d.mouthJawLeftDist,mouthJawRightDist:d.mouthJawRightDist,jawPoints:d.jawPoints,jawCenter:d.jawCenter,mouthUpper:d.mouthUpper,mouthLower:d.mouthLower,mouthOpenPx:d.mouthOpenPx,mouthOpenNorm:d.mouthOpenNorm,jawTopL:d.jawTopL,jawTopR:d.jawTopR}:void 0,landmarkDraw:P?{eyes:!0,mouth:!0,nose:!0,jaw:!0,mouthJaw:!0,cheese:!0}:{eyes:F?.eyes!==!1,mouth:F?.mouth!==!1,nose:F?.nose!==!1,jaw:F?.jaw!==!1,mouthJaw:F?.mouthJaw!==!1,cheese:F?.cheese===!0}})}}catch(e){this._status=`error`;let n=e,r=n&&typeof n==`object`&&typeof n.code==`string`&&typeof n.message==`string`?n:{code:`CAMERA_UNKNOWN`,message:`Erro durante detecção/validação.`,cause:e};t.onError?.(r),t.onStateChange?.({status:this._status,feedback:{code:`FACE_NOT_FOUND`,message:`Centralize seu rosto`},message:`Centralize seu rosto`,isReadyToCapture:!1,challenge:this._state?.challenge})}finally{if(this._lifecycle!==`running`){this._loopActive=!1;return}let t=this._options?.detectionIntervalMs??50;this._loopTimer=window.setTimeout(e,t)}};e()}},e.setupModels=$_});
|