114 lines
349 KiB
JavaScript
114 lines
349 KiB
JavaScript
var faceapi=(()=>{var Xs=Object.defineProperty,Sv=Object.prototype.hasOwnProperty,S=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),lf=e=>Xs(e,"__esModule",{value:!0}),Oe=(e,t)=>{lf(e);for(var n in t)Xs(e,n,{get:t[n],enumerable:!0})},Tv=(e,t)=>{if(lf(e),typeof t=="object"||typeof t=="function")for(let n in t)!Sv.call(e,n)&&n!=="default"&&Xs(e,n,{get:()=>t[n],enumerable:!0});return e},Iv=e=>e&&e.__esModule?e:Tv(Xs({},"default",{value:e,enumerable:!0}),e);var Be=S(Av=>{Oe(Av,{__assign:()=>Zp,__asyncDelegator:()=>Wv,__asyncGenerator:()=>Uv,__asyncValues:()=>qv,__await:()=>hi,__awaiter:()=>Ov,__classPrivateFieldGet:()=>$v,__classPrivateFieldSet:()=>Hv,__createBinding:()=>Qp,__decorate:()=>Rv,__exportStar:()=>Dv,__extends:()=>Nv,__generator:()=>kv,__importDefault:()=>Gv,__importStar:()=>jv,__makeTemplateObject:()=>Bv,__metadata:()=>Ev,__param:()=>Cv,__read:()=>uf,__rest:()=>_v,__spread:()=>Fv,__spreadArrays:()=>Mv,__values:()=>el});var Xp=function(e,t){return Xp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},Xp(e,t)};function Nv(e,t){Xp(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n())}var Zp=function(){return Zp=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},Zp.apply(this,arguments)};function _v(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Rv(e,t,n,r){var i=arguments.length,o=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);return i>3&&o&&Object.defineProperty(t,n,o),o}function Cv(e,t){return function(n,r){t(n,r,e)}}function Ev(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function Ov(e,t,n,r){function i(o){return o instanceof n?o:new n(function(a){a(o)})}return new(n||(n=Promise))(function(o,a){function s(l){try{p(r.next(l))}catch(u){a(u)}}function c(l){try{p(r.throw(l))}catch(u){a(u)}}function p(l){l.done?o(l.value):i(l.value).then(s,c)}p((r=r.apply(e,t||[])).next())})}function kv(e,t){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(p){return function(l){return c([p,l])}}function c(p){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(o=p[0]&2?i.return:p[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,p[1])).done)return o;(i=0,o)&&(p=[p[0]&2,o.value]);switch(p[0]){case 0:case 1:o=p;break;case 4:return n.label++,{value:p[1],done:!1};case 5:n.label++,i=p[1],p=[0];continue;case 7:p=n.ops.pop(),n.trys.pop();continue;default:if(!(o=n.trys,o=o.length>0&&o[o.length-1])&&(p[0]===6||p[0]===2)){n=0;continue}if(p[0]===3&&(!o||p[1]>o[0]&&p[1]<o[3])){n.label=p[1];break}if(p[0]===6&&n.label<o[1]){n.label=o[1],o=p;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(p);break}o[2]&&n.ops.pop(),n.trys.pop();continue}p=t.call(e,n)}catch(l){p=[6,l],i=0}finally{r=o=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}var Qp=Object.create?function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]};function Dv(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Qp(t,e,n)}function el(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function uf(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,o=[],a;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(s){a={error:s}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return o}function Fv(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(uf(arguments[t]));return e}function Mv(){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 o=arguments[t],a=0,s=o.length;a<s;a++,i++)r[i]=o[a];return r}function hi(e){return this instanceof hi?(this.v=e,this):new hi(e)}function Uv(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(m){r[m]&&(i[m]=function(b){return new Promise(function(y,w){o.push([m,b,y,w])>1||s(m,b)})})}function s(m,b){try{c(r[m](b))}catch(y){u(o[0][3],y)}}function c(m){m.value instanceof hi?Promise.resolve(m.value.v).then(p,l):u(o[0][2],m)}function p(m){s("next",m)}function l(m){s("throw",m)}function u(m,b){(m(b),o.shift(),o.length)&&s(o[0][0],o[0][1])}}function Wv(e){var t,n;return t={},r("next"),r("throw",function(i){throw i}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(i,o){t[i]=e[i]?function(a){return(n=!n)?{value:hi(e[i](a)),done:i==="return"}:o?o(a):a}:o}}function qv(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof el=="function"?el(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=e[o]&&function(a){return new Promise(function(s,c){a=e[o](a),i(s,c,a.done,a.value)})}}function i(o,a,s,c){Promise.resolve(c).then(function(p){o({value:p,done:s})},a)}}function Bv(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var Pv=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};function jv(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&Qp(t,e,n);return Pv(t,e),t}function Gv(e){return e&&e.__esModule?e:{default:e}}function $v(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function Hv(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}});var df=S((hf,tl)=>{(function(e,t,n){function r(s){var c=this,p=a();c.next=function(){var l=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=l-(c.c=l|0)},c.c=1,c.s0=p(" "),c.s1=p(" "),c.s2=p(" "),c.s0-=p(s),c.s0<0&&(c.s0+=1),c.s1-=p(s),c.s1<0&&(c.s1+=1),c.s2-=p(s),c.s2<0&&(c.s2+=1),p=null}function i(s,c){return c.c=s.c,c.s0=s.s0,c.s1=s.s1,c.s2=s.s2,c}function o(s,c){var p=new r(s),l=c&&c.state,u=p.next;return u.int32=function(){return p.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,l&&(typeof l=="object"&&i(l,p),u.state=function(){return i(p,{})}),u}function a(){var s=4022871197,c=function(p){p=p.toString();for(var l=0;l<p.length;l++){s+=p.charCodeAt(l);var u=.02519603282416938*s;s=u>>>0,u-=s,u*=s,s=u>>>0,u-=s,s+=u*4294967296}return(s>>>0)*23283064365386963e-26};return c}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.alea=o})(hf,typeof tl=="object"&&tl,typeof define=="function"&&define)});var ff=S((mf,nl)=>{(function(e,t,n){function r(a){var s=this,c="";s.x=0,s.y=0,s.z=0,s.w=0,s.next=function(){var l=s.x^s.x<<11;return s.x=s.y,s.y=s.z,s.z=s.w,s.w^=s.w>>>19^l^l>>>8},a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,s.next()}function i(a,s){return s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w,s}function o(a,s){var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var u=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(u+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&i(p,c),l.state=function(){return i(c,{})}),l}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.xor128=o})(mf,typeof nl=="object"&&nl,typeof define=="function"&&define)});var bf=S((gf,rl)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.x^s.x>>>2;return s.x=s.y,s.y=s.z,s.z=s.w,s.w=s.v,(s.d=s.d+362437|0)+(s.v=s.v^s.v<<4^(l^l<<1))|0},s.x=0,s.y=0,s.z=0,s.w=0,s.v=0,a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,p==c.length&&(s.d=s.x<<10^s.x>>>4),s.next()}function i(a,s){return s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w,s.v=a.v,s.d=a.d,s}function o(a,s){var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var u=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(u+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&i(p,c),l.state=function(){return i(c,{})}),l}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.xorwow=o})(gf,typeof rl=="object"&&rl,typeof define=="function"&&define)});var yf=S((wf,il)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.x,l=s.i,u,m,b;return u=p[l],u^=u>>>7,m=u^u<<24,u=p[l+1&7],m^=u^u>>>10,u=p[l+3&7],m^=u^u>>>3,u=p[l+4&7],m^=u^u<<7,u=p[l+7&7],u=u^u<<13,m^=u^u<<9,p[l]=m,s.i=l+1&7,m};function c(p,l){var u,m,b=[];if(l===(l|0))m=b[0]=l;else for(l=""+l,u=0;u<l.length;++u)b[u&7]=b[u&7]<<15^l.charCodeAt(u)+b[u+1&7]<<13;for(;b.length<8;)b.push(0);for(u=0;u<8&&b[u]===0;++u);for(u==8?m=b[7]=-1:m=b[u],p.x=b,p.i=0,u=256;u>0;--u)p.next()}c(s,a)}function i(a,s){return s.x=a.x.slice(),s.i=a.i,s}function o(a,s){a==null&&(a=+new Date());var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var u=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(u+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.x&&i(p,c),l.state=function(){return i(c,{})}),l}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.xorshift7=o})(wf,typeof il=="object"&&il,typeof define=="function"&&define)});var Lf=S((xf,ol)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.w,l=s.X,u=s.i,m,b;return s.w=p=p+1640531527|0,b=l[u+34&127],m=l[u=u+1&127],b^=b<<13,m^=m<<17,b^=b>>>15,m^=m>>>12,b=l[u]=b^m,s.i=u,b+(p^p>>>16)|0};function c(p,l){var u,m,b,y,w,L=[],T=128;for(l===(l|0)?(m=l,l=null):(l=l+"\0",m=0,T=Math.max(T,l.length)),b=0,y=-32;y<T;++y)l&&(m^=l.charCodeAt((y+32)%l.length)),y===0&&(w=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,y>=0&&(w=w+1640531527|0,u=L[y&127]^=m+w,b=u==0?b+1:0);for(b>=128&&(L[(l&&l.length||0)&127]=-1),b=127,y=4*128;y>0;--y)m=L[b+34&127],u=L[b=b+1&127],m^=m<<13,u^=u<<17,m^=m>>>15,u^=u>>>12,L[b]=m^u;p.w=w,p.X=L,p.i=b}c(s,a)}function i(a,s){return s.i=a.i,s.w=a.w,s.X=a.X.slice(),s}function o(a,s){a==null&&(a=+new Date());var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var u=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(u+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.X&&i(p,c),l.state=function(){return i(c,{})}),l}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.xor4096=o})(xf,typeof ol=="object"&&ol,typeof define=="function"&&define)});var Sf=S((vf,sl)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.b,u=s.c,m=s.d,b=s.a;return l=l<<25^l>>>7^u,u=u-m|0,m=m<<24^m>>>8^b,b=b-l|0,s.b=l=l<<20^l>>>12^u,s.c=u=u-m|0,s.d=m<<16^u>>>16^b,s.a=b-l|0},s.a=0,s.b=0,s.c=2654435769|0,s.d=1367130551,a===Math.floor(a)?(s.a=a/4294967296|0,s.b=a|0):c+=a;for(var p=0;p<c.length+20;p++)s.b^=c.charCodeAt(p)|0,s.next()}function i(a,s){return s.a=a.a,s.b=a.b,s.c=a.c,s.d=a.d,s}function o(a,s){var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var u=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(u+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&i(p,c),l.state=function(){return i(c,{})}),l}t&&t.exports?t.exports=o:n&&n.amd?n(function(){return o}):this.tychei=o})(vf,typeof sl=="object"&&sl,typeof define=="function"&&define)});var Tf=S(()=>{});var If=S((Rk,Zs)=>{(function(e,t){var n=this,r=256,i=6,o=52,a="random",s=t.pow(r,i),c=t.pow(2,o),p=c*2,l=r-1,u;function m(_,N,C){var F=[];N=N==!0?{entropy:!0}:N||{};var E=L(w(N.entropy?[_,A(e)]:_==null?T():_,3),F),B=new b(F),q=function(){for(var P=B.g(i),te=s,ne=0;P<c;)P=(P+ne)*r,te*=r,ne=B.g(1);for(;P>=p;)P/=2,te/=2,ne>>>=1;return(P+ne)/te};return q.int32=function(){return B.g(4)|0},q.quick=function(){return B.g(4)/4294967296},q.double=q,L(A(B.S),e),(N.pass||C||function(P,te,ne,pe){return pe&&(pe.S&&y(pe,B),P.state=function(){return y(B,{})}),ne?(t[a]=P,te):P})(q,E,"global"in N?N.global:this==t,N.state)}t["seed"+a]=m;function b(_){var N,C=_.length,F=this,E=0,B=F.i=F.j=0,q=F.S=[];for(C||(_=[C++]);E<r;)q[E]=E++;for(E=0;E<r;E++)q[E]=q[B=l&B+_[E%C]+(N=q[E])],q[B]=N;(F.g=function(P){for(var te,ne=0,pe=F.i,Se=F.j,qe=F.S;P--;)te=qe[pe=l&pe+1],ne=ne*r+qe[l&(qe[pe]=qe[Se=l&Se+te])+(qe[Se]=te)];return F.i=pe,F.j=Se,ne})(r)}function y(_,N){return N.i=_.i,N.j=_.j,N.S=_.S.slice(),N}function w(_,N){var C=[],F=typeof _,E;if(N&&F=="object")for(E in _)try{C.push(w(_[E],N-1))}catch(B){}return C.length?C:F=="string"?_:_+"\0"}function L(_,N){for(var C=_+"",F,E=0;E<C.length;)N[l&E]=l&(F^=N[l&E]*19)+C.charCodeAt(E++);return A(N)}function T(){try{var _;return u&&(_=u.randomBytes)?_=_(r):(_=new Uint8Array(r),(n.crypto||n.msCrypto).getRandomValues(_)),A(_)}catch(F){var N=n.navigator,C=N&&N.plugins;return[+new Date(),n,C,n.screen,A(e)]}}function A(_){return String.fromCharCode.apply(0,_)}if(L(t.random(),e),typeof Zs=="object"&&Zs.exports){Zs.exports=m;try{u=Tf()}catch(_){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var Nf=S((Ck,Af)=>{var Yv=df(),zv=ff(),Vv=bf(),Kv=yf(),Jv=Lf(),Xv=Sf(),An=If();An.alea=Yv;An.xor128=zv;An.xorwow=Vv;An.xorshift7=Kv;An.xor4096=Jv;An.tychei=Xv;Af.exports=An});var ee=S(Zv=>{Oe(Zv,{Abs:()=>Mi,Acos:()=>Ui,Acosh:()=>Wi,AdadeltaOptimizer:()=>kn,AdagradOptimizer:()=>On,AdamOptimizer:()=>En,AdamaxOptimizer:()=>Cn,Add:()=>Jn,AddN:()=>qi,All:()=>Wu,Any:()=>qu,ArgMax:()=>Bi,ArgMin:()=>Pi,Asin:()=>ji,Asinh:()=>Gi,Atan:()=>$i,Atan2:()=>Yi,Atanh:()=>Hi,AvgPool:()=>zi,AvgPool3D:()=>Vi,AvgPool3DBackprop:()=>Pu,AvgPoolBackprop:()=>Bu,BatchMatMul:()=>Ki,BatchToSpaceND:()=>Ji,BroadcastTo:()=>Xi,Cast:()=>Xn,Ceil:()=>Zi,ClipByValue:()=>Qi,Complex:()=>ju,Concat:()=>eo,Conv2D:()=>to,Conv2DBackpropFilter:()=>Gu,Conv2DBackpropInput:()=>no,Conv3D:()=>ro,Conv3DBackpropFilterV2:()=>$u,Conv3DBackpropInputV2:()=>Hu,Cos:()=>io,Cosh:()=>oo,CropAndResize:()=>Yu,Cumsum:()=>so,DataStorage:()=>RS,DepthToSpace:()=>zu,DepthwiseConv2dNative:()=>ao,DepthwiseConv2dNativeBackpropFilter:()=>Vu,DepthwiseConv2dNativeBackpropInput:()=>Ku,Diag:()=>Ju,Dilation2D:()=>co,Dilation2DBackpropFilter:()=>Zu,Dilation2DBackpropInput:()=>Xu,Div:()=>po,ENV:()=>Mh,Elu:()=>lo,EluGrad:()=>Qu,Environment:()=>Fh,Equal:()=>eh,Erf:()=>uo,Exp:()=>ho,Expm1:()=>mo,FFT:()=>th,Fill:()=>nh,FlipLeftRight:()=>rh,Floor:()=>fo,FloorDiv:()=>go,FromPixels:()=>ra,FusedBatchNorm:()=>bo,FusedConv2D:()=>oa,FusedDepthwiseConv2D:()=>sa,GatherNd:()=>ih,GatherV2:()=>wo,Greater:()=>oh,GreaterEqual:()=>yo,IFFT:()=>sh,Identity:()=>xo,Imag:()=>ah,IsFinite:()=>Lo,IsInf:()=>vo,IsNan:()=>So,KernelBackend:()=>CS,LRN:()=>No,LRNBackprop:()=>mh,Less:()=>ch,LessEqual:()=>ph,LinSpace:()=>lh,Log:()=>To,Log1p:()=>Io,LogSoftmax:()=>Ao,LogicalAnd:()=>uh,LogicalNot:()=>hh,LogicalOr:()=>dh,Max:()=>_o,MaxPool:()=>Co,MaxPool3D:()=>Eo,MaxPool3DBackprop:()=>gh,MaxPoolBackprop:()=>fh,MaxPoolWithArgmax:()=>bh,Maximum:()=>Ro,Mean:()=>oS,Min:()=>Oo,Minimum:()=>ko,Mod:()=>Do,MomentumOptimizer:()=>Rn,Multiply:()=>Fo,Negate:()=>Mo,NonMaxSuppressionV3:()=>yh,NonMaxSuppressionV4:()=>xh,NonMaxSuppressionV5:()=>Lh,NotEqual:()=>wh,OneHot:()=>Wo,OnesLike:()=>Uo,Optimizer:()=>Ze,PadV2:()=>qo,Pool:()=>sS,Pow:()=>Bo,Prelu:()=>Po,Prod:()=>vh,RMSPropOptimizer:()=>_n,Range:()=>Sh,Rank:()=>al,Real:()=>Th,Reciprocal:()=>jo,Reduction:()=>ue,Relu:()=>Go,Relu6:()=>zo,Reshape:()=>$o,ResizeBilinear:()=>Yo,ResizeBilinearGrad:()=>Ah,ResizeNearestNeighbor:()=>Ho,ResizeNearestNeighborGrad:()=>Ih,Reverse:()=>Vo,RotateWithOffset:()=>Oh,Round:()=>Ko,Rsqrt:()=>Jo,SGDOptimizer:()=>$t,ScatterNd:()=>Nh,SelectV2:()=>Xo,Selu:()=>Zo,Sigmoid:()=>rs,Sign:()=>ns,Sin:()=>es,Sinh:()=>ts,Slice:()=>Qo,Softmax:()=>ps,Softplus:()=>is,SpaceToBatchND:()=>as,SparseToDense:()=>Rh,SplitV:()=>cs,Sqrt:()=>os,Square:()=>_h,SquaredDifference:()=>ls,Step:()=>ys,StridedSlice:()=>Ch,Sub:()=>us,Sum:()=>ss,Tan:()=>hs,Tanh:()=>ds,Tensor:()=>de,TensorBuffer:()=>yr,Tile:()=>ms,TopK:()=>Eh,Transpose:()=>fs,Unpack:()=>gs,UnsortedSegmentSum:()=>bs,Variable:()=>Nn,ZerosLike:()=>ws,_FusedMatMul:()=>ia,abs:()=>_e,acos:()=>Mu,acosh:()=>Fu,add:()=>O,addN:()=>Du,addStrict:()=>eg,all:()=>ku,any:()=>Ou,argMax:()=>Eu,argMin:()=>Cu,asin:()=>Ru,asinh:()=>_u,atan:()=>Nu,atan2:()=>Au,atanh:()=>Iu,avgPool:()=>Di,avgPool3d:()=>Tu,backend:()=>AS,backend_util:()=>dg,basicLSTMCell:()=>Su,batchNorm:()=>Jt,batchNorm2d:()=>vu,batchNorm3d:()=>Lu,batchNorm4d:()=>xu,batchToSpaceND:()=>Kn,booleanMaskAsync:()=>Qf,broadcastTo:()=>Ir,browser:()=>Zf,buffer:()=>ke,cast:()=>R,ceil:()=>yu,clipByValue:()=>wu,clone:()=>At,complex:()=>Ge,concat:()=>re,concat1d:()=>bu,concat2d:()=>gu,concat3d:()=>fu,concat4d:()=>mu,conv1d:()=>du,conv2d:()=>It,conv2dTranspose:()=>hu,conv3d:()=>uu,conv3dTranspose:()=>lu,cos:()=>Vn,cosh:()=>ki,cosineWindow:()=>Lr,cumsum:()=>Oi,customGrad:()=>$e,deprecationWarn:()=>ge,depthToSpace:()=>pu,depthwiseConv2d:()=>zn,device_util:()=>ug,diag:()=>cu,dilation2d:()=>au,disableDeprecationWarnings:()=>dS,dispose:()=>be,disposeVariables:()=>mS,div:()=>M,divNoNan:()=>su,divStrict:()=>tg,dot:()=>ou,dropout:()=>Hf,elu:()=>Ei,enableDebugMode:()=>hS,enableProdMode:()=>uS,enclosingPowerOfTwo:()=>Qs,engine:()=>fS,env:()=>se,equal:()=>Kt,equalStrict:()=>Yf,erf:()=>iu,exp:()=>Ne,expandDims:()=>Ke,expm1:()=>ru,eye:()=>Ci,fft:()=>Yn,fill:()=>Hn,findBackend:()=>SS,findBackendFactory:()=>TS,floor:()=>$n,floorDiv:()=>Ri,fused:()=>nu,gather:()=>Gn,gatherND:()=>$f,gather_util:()=>Gf,getBackend:()=>LS,getGradient:()=>ta,getKernel:()=>Fi,getKernelsForBackend:()=>na,grad:()=>aS,grads:()=>cS,greater:()=>Ve,greaterEqual:()=>ct,greaterEqualStrict:()=>zf,greaterStrict:()=>Vf,ifft:()=>cn,imag:()=>Vt,image:()=>Wf,inTopKAsync:()=>jf,io:()=>lg,irfft:()=>_i,isFinite:()=>tu,isInf:()=>eu,isNaN:()=>Ql,keep:()=>Dh,kernel_impls:()=>hg,leakyRelu:()=>Zl,less:()=>jn,lessEqual:()=>at,lessEqualStrict:()=>Kf,lessStrict:()=>Jf,linalg:()=>qf,linspace:()=>Xl,localResponseNormalization:()=>Jl,log:()=>gt,log1p:()=>Ni,logSigmoid:()=>Kl,logSoftmax:()=>Vl,logSumExp:()=>Ai,logicalAnd:()=>ft,logicalNot:()=>Pn,logicalOr:()=>Ii,logicalXor:()=>zl,losses:()=>Bf,matMul:()=>K,math:()=>pg,max:()=>st,maxPool:()=>Ti,maxPool3d:()=>Yl,maxPoolWithArgmax:()=>Hl,maximum:()=>Tt,maximumStrict:()=>ng,mean:()=>an,memory:()=>gS,min:()=>sn,minimum:()=>Bn,minimumStrict:()=>rg,mod:()=>Si,modStrict:()=>ig,moments:()=>$l,movingAverage:()=>Pf,mul:()=>v,mulStrict:()=>og,multiRNNCell:()=>Gl,multinomial:()=>jl,neg:()=>Q,nextFrame:()=>_S,norm:()=>Tr,notEqual:()=>qn,notEqualStrict:()=>Xf,oneHot:()=>Sr,ones:()=>mt,onesLike:()=>ea,op:()=>d,outerProduct:()=>Pl,pad:()=>ot,pad1d:()=>Bl,pad2d:()=>ql,pad3d:()=>Wl,pad4d:()=>Ul,pool:()=>Ml,pow:()=>je,powStrict:()=>sg,prelu:()=>vi,print:()=>Fl,prod:()=>Dl,profile:()=>bS,rand:()=>kl,randomGamma:()=>Ol,randomNormal:()=>El,randomUniform:()=>Li,range:()=>vr,ready:()=>xS,real:()=>kt,reciprocal:()=>Cl,registerBackend:()=>IS,registerGradient:()=>Uu,registerKernel:()=>nS,relu:()=>zt,relu6:()=>xi,removeBackend:()=>vS,reshape:()=>x,reverse:()=>Pe,reverse1d:()=>Rl,reverse2d:()=>_l,reverse3d:()=>Nl,reverse4d:()=>Al,rfft:()=>Wn,round:()=>Il,rsqrt:()=>yi,scalar:()=>k,scatterND:()=>Ff,scatter_util:()=>Df,selu:()=>Tl,separableConv2d:()=>Sl,serialization:()=>Ef,setBackend:()=>yS,setPlatform:()=>NS,setdiff1dAsync:()=>vl,sigmoid:()=>St,sign:()=>Ll,signal:()=>Uf,sin:()=>wi,sinh:()=>bi,slice:()=>Y,slice1d:()=>xl,slice2d:()=>yl,slice3d:()=>wl,slice4d:()=>bl,slice_util:()=>kf,softmax:()=>gl,softplus:()=>gi,spaceToBatchND:()=>Un,sparseToDense:()=>Of,spectral:()=>Mf,split:()=>Ot,sqrt:()=>le,square:()=>G,squaredDifference:()=>Mn,squaredDifferenceStrict:()=>ag,squeeze:()=>Fn,stack:()=>dt,step:()=>vt,stridedSlice:()=>fl,sub:()=>D,subStrict:()=>cg,sum:()=>U,sumOutType:()=>eS,tan:()=>ml,tanh:()=>xr,tensor:()=>Qe,tensor1d:()=>ht,tensor2d:()=>Yt,tensor3d:()=>fi,tensor4d:()=>dl,tensor5d:()=>hl,tensor6d:()=>ul,tensor_util:()=>Cf,test_util:()=>Rf,tidy:()=>ce,tile:()=>Ht,time:()=>wS,topk:()=>ll,train:()=>tS,transpose:()=>X,truncatedNormal:()=>pl,unregisterGradient:()=>iS,unregisterKernel:()=>rS,unsortedSegmentSum:()=>mi,unstack:()=>Dn,upcastType:()=>wr,util:()=>_f,valueAndGrad:()=>pS,valueAndGrads:()=>lS,variable:()=>cl,variableGrads:()=>kh,version_core:()=>Qv,where:()=>Ae,whereAsync:()=>di,zeros:()=>Ue,zerosLike:()=>W});});var Uh=S(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.drawContour=void 0;function ES(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:r,y:i},o)=>{const a=t[o];e.moveTo(a.x,a.y),e.lineTo(r,i)}),n){const 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()}aa.drawContour=ES});var Ar=S(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.Dimensions=void 0;const mg=me();class fg{constructor(e,t){if(!mg.isValidNumber(e)||!mg.isValidNumber(t))throw new 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}get width(){return this._width}get height(){return this._height}reverse(){return new fg(1/this.width,1/this.height)}}ca.Dimensions=fg});var me=S(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.isValidProbablitiy=oe.isValidNumber=oe.range=oe.getCenterPoint=oe.computeReshapedDimensions=oe.isDimensions=oe.round=oe.isEven=oe.isFloat=oe.isTensor4D=oe.isTensor3D=oe.isTensor2D=oe.isTensor1D=oe.isTensor=void 0;const OS=ee(),gg=pt(),kS=Ar();function xs(e,t){return e instanceof OS.Tensor&&e.shape.length===t}oe.isTensor=xs;function DS(e){return xs(e,1)}oe.isTensor1D=DS;function FS(e){return xs(e,2)}oe.isTensor2D=FS;function MS(e){return xs(e,3)}oe.isTensor3D=MS;function US(e){return xs(e,4)}oe.isTensor4D=US;function WS(e){return e%1!==0}oe.isFloat=WS;function qS(e){return e%2===0}oe.isEven=qS;function BS(e,t=2){const n=Math.pow(10,t);return Math.floor(e*n)/n}oe.round=BS;function PS(e){return e&&e.width&&e.height}oe.isDimensions=PS;function jS({width:e,height:t},n){const r=n/Math.max(t,e);return new kS.Dimensions(Math.round(e*r),Math.round(t*r))}oe.computeReshapedDimensions=jS;function GS(e){return e.reduce((t,n)=>t.add(n),new gg.Point(0,0)).div(new gg.Point(e.length,e.length))}oe.getCenterPoint=GS;function $S(e,t,n){return Array(e).fill(0).map((r,i)=>t+i*n)}oe.range=$S;function bg(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}oe.isValidNumber=bg;function HS(e){return bg(e)&&0<=e&&e<=1}oe.isValidProbablitiy=HS});var la=S(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.Point=void 0;class Zn{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new Zn(this.x+e.x,this.y+e.y)}sub(e){return new Zn(this.x-e.x,this.y-e.y)}mul(e){return new Zn(this.x*e.x,this.y*e.y)}div(e){return new Zn(this.x/e.x,this.y/e.y)}abs(){return new Zn(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new Zn(Math.floor(this.x),Math.floor(this.y))}}pa.Point=Zn});var Qn=S(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.Box=void 0;const Ls=me(),ha=la();class Nt{constructor(e,t=!0){const n=e||{},r=[n.left,n.top,n.right,n.bottom].every(Ls.isValidNumber),i=[n.x,n.y,n.width,n.height].every(Ls.isValidNumber);if(!i&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(n)}`);const[o,a,s,c]=i?[n.x,n.y,n.width,n.height]:[n.left,n.top,n.right-n.left,n.bottom-n.top];Nt.assertIsValidBox({x:o,y:a,width:s,height:c},"Box.constructor",t),this._x=o,this._y=a,this._width=s,this._height=c}static isRect(e){return!!e&&[e.x,e.y,e.width,e.height].every(Ls.isValidNumber)}static assertIsValidBox(e,t,n=!1){if(!Nt.isRect(e))throw new Error(`${t} - invalid box: ${JSON.stringify(e)}, expected object with properties x, y, width, height`);if(!n&&(e.width<0||e.height<0))throw new Error(`${t} - width (${e.width}) and height (${e.height}) must be positive numbers`)}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new ha.Point(this.left,this.top)}get topRight(){return new ha.Point(this.right,this.top)}get bottomLeft(){return new ha.Point(this.left,this.bottom)}get bottomRight(){return new ha.Point(this.right,this.bottom)}round(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(i=>Math.round(i));return new Nt({x:e,y:t,width:n,height:r})}floor(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(i=>Math.floor(i));return new Nt({x:e,y:t,width:n,height:r})}toSquare(){let{x:e,y:t,width:n,height:r}=this;const i=Math.abs(n-r);return n<r&&(e-=i/2,n+=i),r<n&&(t-=i/2,r+=i),new Nt({x:e,y:t,width:n,height:r})}rescale(e){const t=Ls.isDimensions(e)?e.width:e,n=Ls.isDimensions(e)?e.height:e;return new Nt({x:this.x*t,y:this.y*n,width:this.width*t,height:this.height*n})}pad(e,t){let[n,r,i,o]=[this.x-e/2,this.y-t/2,this.width+e,this.height+t];return new Nt({x:n,y:r,width:i,height:o})}clipAtImageBorders(e,t){const{x:n,y:r,right:i,bottom:o}=this,a=Math.max(n,0),s=Math.max(r,0),c=i-a,p=o-s,l=Math.min(c,e-a),u=Math.min(p,t-s);return new Nt({x:a,y:s,width:l,height:u}).floor()}shift(e,t){const{width:n,height:r}=this,i=this.x+e,o=this.y+t;return new Nt({x:i,y:o,width:n,height:r})}padAtBorders(e,t){const n=this.width+1,r=this.height+1;let i=1,o=1,a=n,s=r,c=this.left,p=this.top,l=this.right,u=this.bottom;return l>t&&(a=-l+t+n,l=t),u>e&&(s=-u+e+r,u=e),c<1&&(s=2-c,c=1),p<1&&(s=2-p,p=1),{dy:o,edy:s,dx:i,edx:a,y:p,ey:u,x:c,ex:l,w:n,h:r}}calibrate(e){return new Nt({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()}}ua.Box=Nt});var Wh=S(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.BoundingBox=void 0;const YS=Qn();class zS extends YS.Box{constructor(e,t,n,r,i=!1){super({left:e,top:t,right:n,bottom:r},i)}}da.BoundingBox=zS});var fa=S(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.ObjectDetection=void 0;const wg=Qn(),VS=Ar();class yg{constructor(e,t,n,r,i){this._imageDims=new VS.Dimensions(i.width,i.height),this._score=e,this._classScore=t,this._className=n,this._box=new wg.Box(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new wg.Box(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new yg(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}ma.ObjectDetection=yg});var Xt=S(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.FaceDetection=void 0;const KS=fa();class xg extends KS.ObjectDetection{constructor(e,t,n){super(e,e,"",t,n)}forSize(e,t){const{score:n,relativeBox:r,imageDims:i}=super.forSize(e,t);return new xg(n,r,i)}}ga.FaceDetection=xg});var qh=S(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.iou=void 0;function JS(e,t,n=!0){const r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),i=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),o=r*i;return n?o/(e.area+t.area-o):o/Math.min(e.area,t.area)}ba.iou=JS});var Lg=S(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.minBbox=void 0;const XS=pt();function ZS(e){const t=e.map(s=>s.x),n=e.map(s=>s.y),r=t.reduce((s,c)=>c<s?c:s,Infinity),i=n.reduce((s,c)=>c<s?c:s,Infinity),o=t.reduce((s,c)=>s<c?c:s,0),a=n.reduce((s,c)=>s<c?c:s,0);return new XS.BoundingBox(r,i,o,a)}wa.minBbox=ZS});var Bh=S(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.nonMaxSuppression=void 0;const QS=qh();function eT(e,t,n,r=!0){let i=t.map((a,s)=>({score:a,boxIndex:s})).sort((a,s)=>a.score-s.score).map(a=>a.boxIndex);const o=[];for(;i.length>0;){const a=i.pop();o.push(a);const s=i,c=[];for(let p=0;p<s.length;p++){const l=s[p],u=e[a],m=e[l];c.push(QS.iou(u,m,r))}i=i.filter((p,l)=>c[l]<=n)}return o}ya.nonMaxSuppression=eT});var Ph=S(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.normalize=void 0;const Nr=ee();function tT(e,t){return Nr.tidy(()=>{const[n,r,i]=t,o=Nr.fill([...e.shape.slice(0,3),1],n),a=Nr.fill([...e.shape.slice(0,3),1],r),s=Nr.fill([...e.shape.slice(0,3),1],i),c=Nr.concat([o,a,s],3);return Nr.sub(e,c)})}xa.normalize=tT});var Gh=S(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.padToSquare=void 0;const jh=ee();function nT(e,t=!1){return jh.tidy(()=>{const[n,r]=e.shape.slice(1);if(n===r)return e;const i=Math.abs(n-r),o=Math.round(i*(t?.5:1)),a=n>r?2:1,s=m=>{const b=e.shape.slice();return b[a]=m,jh.fill(b,0)},c=s(o),p=i-c.shape[a],l=t&&p?s(p):null,u=[l,e,c].filter(m=>!!m).map(m=>m.toFloat());return jh.concat(u,a)})}La.padToSquare=nT});var vg=S(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.shuffleArray=void 0;function rT(e){const t=e.slice();for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1)),i=t[n];t[n]=t[r],t[r]=i}return t}va.shuffleArray=rT});var pn=S(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.inverseSigmoid=bt.sigmoid=void 0;const _r=Be();_r.__exportStar(qh(),bt);_r.__exportStar(Lg(),bt);_r.__exportStar(Bh(),bt);_r.__exportStar(Ph(),bt);_r.__exportStar(Gh(),bt);_r.__exportStar(vg(),bt);function iT(e){return 1/(1+Math.exp(-e))}bt.sigmoid=iT;function oT(e){return Math.log(e/(1-e))}bt.inverseSigmoid=oT});var $h=S(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.Rect=void 0;const sT=Qn();class aT extends sT.Box{constructor(e,t,n,r,i=!1){super({x:e,y:t,width:n,height:r},i)}}Sa.Rect=aT});var er=S(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.FaceLandmarks=void 0;const cT=pn(),pT=me(),lT=Qn(),uT=Ar(),hT=Xt(),vs=la(),dT=$h(),mT=.5,fT=.43,gT=.45;class bT{constructor(e,t,n=new vs.Point(0,0)){const{width:r,height:i}=t;this._imgDims=new uT.Dimensions(r,i),this._shift=n,this._positions=e.map(o=>o.mul(new vs.Point(r,i)).add(n))}get shift(){return new vs.Point(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new vs.Point(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new vs.Point(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const i=e instanceof hT.FaceDetection?e.box.floor():new lT.Box(e);return this.shiftBy(i.x,i.y).align(null,t)}const{useDlibAlignment:n,minBoxPadding:r}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return n?this.alignDlib():this.alignMinBbox(r)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,n,r]=e,i=l=>r.sub(l).magnitude(),o=(i(t)+i(n))/2,a=Math.floor(o/gT),s=pT.getCenterPoint(e),c=Math.floor(Math.max(0,s.x-mT*a)),p=Math.floor(Math.max(0,s.y-fT*a));return new dT.Rect(c,p,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+p))}alignMinBbox(e){const t=cT.minBbox(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}Ta.FaceLandmarks=bT});var Sg=S(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.FaceLandmarks5=void 0;const wT=me(),yT=er();class xT extends yT.FaceLandmarks{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],wT.getCenterPoint([e[3],e[4]])]}}Ia.FaceLandmarks5=xT});var Na=S(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.FaceLandmarks68=void 0;const LT=me(),vT=er();class ST extends vT.FaceLandmarks{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(LT.getCenterPoint)}}Aa.FaceLandmarks68=ST});var Hh=S(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.FaceMatch=void 0;const TT=me();class IT{constructor(e,t){this._label=e,this._distance=t}get label(){return this._label}get distance(){return this._distance}toString(e=!0){return`${this.label}${e?` (${TT.round(this.distance)})`:""}`}}_a.FaceMatch=IT});var Yh=S(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.LabeledBox=void 0;const AT=me(),Tg=Qn();class NT extends Tg.Box{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(Tg.Box.assertIsValidBox(e,t),!AT.isValidNumber(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}Ra.LabeledBox=NT});var zh=S(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.LabeledFaceDescriptors=void 0;class Ig{constructor(e,t){if(!(typeof e=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(t)||t.some(n=>!(n instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=e,this._descriptors=t}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(e=>Array.from(e))}}static fromJSON(e){const t=e.descriptors.map(n=>new Float32Array(n));return new Ig(e.label,t)}}Ca.LabeledFaceDescriptors=Ig});var _g=S(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.PredictedBox=void 0;const Ag=me(),Ng=Yh();class _T extends Ng.LabeledBox{constructor(e,t,n,r){super(e,t);this._score=n,this._classScore=r}static assertIsValidPredictedBox(e,t){if(Ng.LabeledBox.assertIsValidLabeledBox(e,t),!Ag.isValidProbablitiy(e.score)||!Ag.isValidProbablitiy(e.classScore))throw new Error(`${t} - expected properties score (${e.score}) and (${e.classScore}) to be a number between [0, 1]`)}get score(){return this._score}get classScore(){return this._classScore}}Ea.PredictedBox=_T});var pt=S(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});const et=Be();et.__exportStar(Wh(),He);et.__exportStar(Qn(),He);et.__exportStar(Ar(),He);et.__exportStar(Xt(),He);et.__exportStar(er(),He);et.__exportStar(Sg(),He);et.__exportStar(Na(),He);et.__exportStar(Hh(),He);et.__exportStar(Yh(),He);et.__exportStar(zh(),He);et.__exportStar(fa(),He);et.__exportStar(la(),He);et.__exportStar(_g(),He);et.__exportStar($h(),He)});var tr=S(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.extendWithFaceDetection=Rr.isWithFaceDetection=void 0;const RT=Xt();function CT(e){return e.detection instanceof RT.FaceDetection}Rr.isWithFaceDetection=CT;function ET(e,t){const n={detection:t};return Object.assign({},e,n)}Rr.extendWithFaceDetection=ET});var Rg=S(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.createBrowserEnv=void 0;function OT(){const e=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},t=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:t}}Oa.createBrowserEnv=OT});var Vh=S(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.createFileSystem=void 0;function kT(e){let t="";if(!e)try{e=require("fs")}catch(r){t=r.toString()}const n=e?function(r){return new Promise((i,o)=>{e.readFile(r,function(a,s){return a?o(a):i(s)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:n}}ka.createFileSystem=kT});var Cg=S(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.createNodejsEnv=void 0;const DT=Vh();function FT(){const e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=function(){if(e)return new e();throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},r=function(){if(t)return new t();throw new Error("createImageElement - missing Image implementation for nodejs environment")},i=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},o=DT.createFileSystem();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:r,fetch:i,...o}}Da.createNodejsEnv=FT});var Eg=S(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.isBrowser=void 0;function MT(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}Fa.isBrowser=MT});var kg=S((Ma,Og)=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.isNodejs=void 0;function UT(){return typeof global=="object"&&!0&&typeof Og!="undefined"&&typeof process!="undefined"&&!!process.version}Ma.isNodejs=UT});var Fg=S(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0})});var Ye=S(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.env=void 0;const WT=Be(),Mg=Rg(),qT=Vh(),Ug=Cg(),Wg=Eg(),qg=kg();let Re;function BT(){if(!Re)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Re}function Kh(e){Re=e}function Jh(){if(Wg.isBrowser())return Kh(Mg.createBrowserEnv());if(qg.isNodejs())return Kh(Ug.createNodejsEnv())}function PT(e){if(Re||Jh(),!Re)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Re.Canvas,Image:n=Re.Image}=e;Re.Canvas=t,Re.Image=n,Re.createCanvasElement=e.createCanvasElement||(()=>new t()),Re.createImageElement=e.createImageElement||(()=>new n()),Re.ImageData=e.ImageData||Re.ImageData,Re.Video=e.Video||Re.Video,Re.fetch=e.fetch||Re.fetch,Re.readFile=e.readFile||Re.readFile}Ss.env={getEnv:BT,setEnv:Kh,initialize:Jh,createBrowserEnv:Mg.createBrowserEnv,createFileSystem:qT.createFileSystem,createNodejsEnv:Ug.createNodejsEnv,monkeyPatch:PT,isBrowser:Wg.isBrowser,isNodejs:qg.isNodejs};Jh();WT.__exportStar(Fg(),Ss)});var Ts=S(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.resolveInput=void 0;const jT=Ye();function GT(e){return!jT.env.isNodejs()&&typeof e=="string"?document.getElementById(e):e}Ua.resolveInput=GT});var ln=S(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.getContext2dOrThrow=void 0;const $T=Ye(),HT=Ts();function YT(e){const{Canvas:t,CanvasRenderingContext2D:n}=$T.env.getEnv();if(e instanceof n)return e;const r=HT.resolveInput(e);if(!(r instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const i=r.getContext("2d");if(!i)throw new Error("resolveContext2d - canvas 2d context is null");return i}Wa.getContext2dOrThrow=YT});var qa=S(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.DrawTextField=Zt.DrawTextFieldOptions=Zt.AnchorPosition=void 0;const zT=ln(),VT=Ts();var Cr;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Cr=Zt.AnchorPosition||(Zt.AnchorPosition={}));class Bg{constructor(e={}){const{anchorPosition:t,backgroundColor:n,fontColor:r,fontSize:i,fontStyle:o,padding:a}=e;this.anchorPosition=t||Cr.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=o||"Georgia",this.padding=a||4}}Zt.DrawTextFieldOptions=Bg;class Pg{constructor(e,t,n={}){this.text=typeof e=="string"?[e]:e instanceof Pg?e.text:e,this.anchor=t,this.options=new Bg(n)}measureWidth(e){const{padding:t}=this.options;return this.text.map(n=>e.measureText(n).width).reduce((n,r)=>n<r?r:n,0)+2*t}measureHeight(){const{fontSize:e,padding:t}=this.options;return this.text.length*e+2*t}getUpperLeft(e,t){const{anchorPosition:n}=this.options,r=n===Cr.BOTTOM_RIGHT||n===Cr.TOP_RIGHT,i=n===Cr.BOTTOM_LEFT||n===Cr.BOTTOM_RIGHT,o=this.measureWidth(e),a=this.measureHeight(),s=r?this.anchor.x-o:this.anchor.x,c=i?this.anchor.y-a:this.anchor.y;if(t){const{width:p,height:l}=t,u=Math.max(Math.min(s,p-o),0),m=Math.max(Math.min(c,l-a),0);return{x:u,y:m}}return{x:s,y:c}}draw(e){const t=VT.resolveInput(e),n=zT.getContext2dOrThrow(t),{backgroundColor:r,fontColor:i,fontSize:o,fontStyle:a,padding:s}=this.options;n.font=`${o}px ${a}`;const c=this.measureWidth(n),p=this.measureHeight();n.fillStyle=r;const l=this.getUpperLeft(n,t);n.fillRect(l.x,l.y,c,p),n.fillStyle=i,this.text.forEach((u,m)=>{const b=s+l.x,y=s+l.y+(m+1)*o;n.fillText(u,b,y)})}}Zt.DrawTextField=Pg});var Zh=S(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.DrawBox=Er.DrawBoxOptions=void 0;const KT=pt(),JT=ln(),Xh=qa();class jg{constructor(e={}){const{boxColor:t,lineWidth:n,label:r,drawLabelOptions:i}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=r;const o={anchorPosition:Xh.AnchorPosition.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Xh.DrawTextFieldOptions(Object.assign({},o,i))}}Er.DrawBoxOptions=jg;class XT{constructor(e,t={}){this.box=new KT.Box(e),this.options=new jg(t)}draw(e){const t=JT.getContext2dOrThrow(e),{boxColor:n,lineWidth:r}=this.options,{x:i,y:o,width:a,height:s}=this.box;t.strokeStyle=n,t.lineWidth=r,t.strokeRect(i,o,a,s);const{label:c}=this.options;c&&new Xh.DrawTextField([c],{x:i-r/2,y:o},this.options.drawLabelOptions).draw(e)}}Er.DrawBox=XT});var Hg=S(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.drawDetections=void 0;const ZT=pt(),Gg=Xt(),$g=tr(),QT=me(),eI=Zh();function tI(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const i=r instanceof Gg.FaceDetection?r.score:$g.isWithFaceDetection(r)?r.detection.score:void 0,o=r instanceof Gg.FaceDetection?r.box:$g.isWithFaceDetection(r)?r.detection.box:new ZT.Box(r),a=i?`${QT.round(i)}`:void 0;new eI.DrawBox(o,{label:a}).draw(e)})}Ba.drawDetections=tI});var ja=S(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.isMediaLoaded=void 0;const nI=Ye();function rI(e){const{Image:t,Video:n}=nI.env.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}Pa.isMediaLoaded=rI});var Qh=S(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.awaitMediaLoaded=void 0;const iI=Ye(),oI=ja();function sI(e){return new Promise((t,n)=>{if(e instanceof iI.env.getEnv().Canvas||oI.isMediaLoaded(e))return t();function r(o){if(!o.currentTarget)return;o.currentTarget.removeEventListener("load",r),o.currentTarget.removeEventListener("error",i),t(o)}function i(o){if(!o.currentTarget)return;o.currentTarget.removeEventListener("load",r),o.currentTarget.removeEventListener("error",i),n(o)}e.addEventListener("load",r),e.addEventListener("error",i)})}Ga.awaitMediaLoaded=sI});var ed=S($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.bufferToImage=void 0;const aI=Ye();function cI(e){return new Promise((t,n)=>{if(!(e instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");const r=new FileReader();r.onload=()=>{if(typeof r.result!="string")return n("bufferToImage - expected reader.result to be a string, in onload");const i=aI.env.getEnv().createImageElement();i.onload=()=>t(i),i.onerror=n,i.src=r.result},r.onerror=n,r.readAsDataURL(e)})}$a.bufferToImage=cI});var Is=S(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.getMediaDimensions=void 0;const td=Ar(),pI=Ye();function lI(e){const{Image:t,Video:n}=pI.env.getEnv();return e instanceof t?new td.Dimensions(e.naturalWidth,e.naturalHeight):e instanceof n?new td.Dimensions(e.videoWidth,e.videoHeight):new td.Dimensions(e.width,e.height)}Ha.getMediaDimensions=lI});var As=S(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.createCanvasFromMedia=Or.createCanvas=void 0;const Yg=Ye(),zg=ln(),uI=Is(),hI=ja();function Vg({width:e,height:t}){const{createCanvasElement:n}=Yg.env.getEnv(),r=n();return r.width=e,r.height=t,r}Or.createCanvas=Vg;function dI(e,t){const{ImageData:n}=Yg.env.getEnv();if(!(e instanceof n)&&!hI.isMediaLoaded(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:r,height:i}=t||uI.getMediaDimensions(e),o=Vg({width:r,height:i});return e instanceof n?zg.getContext2dOrThrow(o).putImageData(e,0,0):zg.getContext2dOrThrow(o).drawImage(e,0,0,r,i),o}Or.createCanvasFromMedia=dI});var nd=S(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.imageTensorToCanvas=void 0;const Kg=ee(),mI=Ye(),fI=me();async function gI(e,t){const n=t||mI.env.getEnv().createCanvasElement(),[r,i,o]=e.shape.slice(fI.isTensor4D(e)?1:0),a=Kg.tidy(()=>e.as3D(r,i,o).toInt());return await Kg.browser.toPixels(a,n),a.dispose(),n}Ya.imageTensorToCanvas=gI});var rd=S(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.isMediaElement=void 0;const bI=Ye();function wI(e){const{Image:t,Canvas:n,Video:r}=bI.env.getEnv();return e instanceof t||e instanceof n||e instanceof r}za.isMediaElement=wI});var id=S(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.imageToSquare=void 0;const yI=Ye(),Jg=As(),xI=ln(),LI=Is();function vI(e,t,n=!1){const{Image:r,Canvas:i}=yI.env.getEnv();if(!(e instanceof r||e instanceof i))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const o=LI.getMediaDimensions(e),a=t/Math.max(o.height,o.width),s=a*o.width,c=a*o.height,p=Jg.createCanvas({width:t,height:t}),l=e instanceof i?e:Jg.createCanvasFromMedia(e),u=Math.abs(s-c)/2,m=n&&s<c?u:0,b=n&&c<s?u:0;return xI.getContext2dOrThrow(p).drawImage(l,m,b,s,c),p}Va.imageToSquare=vI});var od=S(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.NetInput=void 0;const Ns=ee(),Xg=Ye(),SI=Gh(),kr=me(),TI=As(),II=id();class AI{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new 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((n,r)=>{if(kr.isTensor3D(n)){this._imageTensors[r]=n,this._inputDimensions[r]=n.shape;return}if(kr.isTensor4D(n)){const o=n.shape[0];if(o!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${o} passed, but not supported in input array`);this._imageTensors[r]=n,this._inputDimensions[r]=n.shape.slice(1);return}const i=n instanceof Xg.env.getEnv().Canvas?n:TI.createCanvasFromMedia(n);this._canvases[r]=i,this._inputDimensions[r]=[i.height,i.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return kr.range(this.batchSize,0,1).map((e,t)=>this.getReshapedInputDimensions(t))}getInput(e){return this.canvases[e]||this.imageTensors[e]}getInputDimensions(e){return this._inputDimensions[e]}getInputHeight(e){return this._inputDimensions[e][0]}getInputWidth(e){return this._inputDimensions[e][1]}getReshapedInputDimensions(e){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const t=this.getInputWidth(e),n=this.getInputHeight(e);return kr.computeReshapedDimensions({width:t,height:n},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,Ns.tidy(()=>{const n=kr.range(this.batchSize,0,1).map(i=>{const o=this.getInput(i);if(o instanceof Ns.Tensor){let a=kr.isTensor4D(o)?o:o.expandDims();return a=SI.padToSquare(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Ns.image.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(o instanceof Xg.env.getEnv().Canvas)return Ns.browser.fromPixels(II.imageToSquare(o,e,t));throw new Error(`toBatchTensor - at batchIdx ${i}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${o}`)}),r=Ns.stack(n.map(i=>i.toFloat())).as4D(this.batchSize,e,e,3);return r})}}Ka.NetInput=AI});var ad=S(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.toNetInput=void 0;const sd=me(),NI=Qh(),Zg=rd(),Qg=od(),_I=Ts();async function RI(e){if(e instanceof Qg.NetInput)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");const n=i=>Array.isArray(e)?` at input index ${i}:`:"",r=t.map(_I.resolveInput);return r.forEach((i,o)=>{if(!Zg.isMediaElement(i)&&!sd.isTensor3D(i)&&!sd.isTensor4D(i))throw typeof t[o]=="string"?new Error(`toNetInput -${n(o)} string passed, but could not resolve HTMLElement for element id ${t[o]}`):new Error(`toNetInput -${n(o)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(sd.isTensor4D(i)){const a=i.shape[0];if(a!==1)throw new Error(`toNetInput -${n(o)} tf.Tensor4D with batchSize ${a} passed, but not supported in input array`)}}),await Promise.all(r.map(i=>Zg.isMediaElement(i)&&NI.awaitMediaLoaded(i))),new Qg.NetInput(r,Array.isArray(e))}Ja.toNetInput=RI});var tb=S(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.extractFaces=void 0;const CI=Xt(),EI=Ye(),OI=As(),eb=ln(),kI=nd(),DI=ad();async function FI(e,t){const{Canvas:n}=EI.env.getEnv();let r=e;if(!(e instanceof n)){const a=await DI.toNetInput(e);if(a.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const s=a.getInput(0);r=s instanceof n?s:await kI.imageTensorToCanvas(s)}const i=eb.getContext2dOrThrow(r),o=t.map(a=>a instanceof CI.FaceDetection?a.forSize(r.width,r.height).box.floor():a).map(a=>a.clipAtImageBorders(r.width,r.height));return o.map(({x:a,y:s,width:c,height:p})=>{const l=OI.createCanvas({width:c,height:p});return eb.getContext2dOrThrow(l).putImageData(i.getImageData(a,s,c,p),0,0),l})}Xa.extractFaces=FI});var rb=S(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.extractFaceTensors=void 0;const nb=ee(),MI=Xt(),Qa=me();async function UI(e,t){if(!Qa.isTensor3D(e)&&!Qa.isTensor4D(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Qa.isTensor4D(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return nb.tidy(()=>{const[n,r,i]=e.shape.slice(Qa.isTensor4D(e)?1:0),o=t.map(s=>s instanceof MI.FaceDetection?s.forSize(r,n).box:s).map(s=>s.clipAtImageBorders(r,n)),a=o.map(({x:s,y:c,width:p,height:l})=>nb.slice3d(e.as3D(n,r,i),[c,s,0],[l,p,i]));return a})}Za.extractFaceTensors=UI});var _s=S(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.fetchOrThrow=void 0;const WI=Ye();async function qI(e,t){const n=WI.env.getEnv().fetch,r=await n(e,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}ec.fetchOrThrow=qI});var ib=S(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.fetchImage=void 0;const BI=ed(),PI=_s();async function jI(e){const t=await PI.fetchOrThrow(e),n=await t.blob();if(!n.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${n.type}, for url: ${t.url}`);return BI.bufferToImage(n)}tc.fetchImage=jI});var cd=S(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.fetchJson=void 0;const GI=_s();async function $I(e){return(await GI.fetchOrThrow(e)).json()}nc.fetchJson=$I});var ob=S(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.fetchNetWeights=void 0;const HI=_s();async function YI(e){return new Float32Array(await(await HI.fetchOrThrow(e)).arrayBuffer())}rc.fetchNetWeights=YI});var oc=S(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.getModelUris=void 0;function zI(e,t){const n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};const r=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(r,"");const i=e.split("/").filter(s=>s),o=e.endsWith(".json")?i[i.length-1]:n;let a=r+(e.endsWith(".json")?i.slice(0,i.length-1):i).join("/");return a=e.startsWith("/")?`/${a}`:a,{modelBaseUri:a,manifestUri:a==="/"?`/${o}`:`${a}/${o}`}}ic.getModelUris=zI});var sb=S(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.loadWeightMap=void 0;const VI=ee(),KI=oc(),JI=cd();async function XI(e,t){const{manifestUri:n,modelBaseUri:r}=KI.getModelUris(e,t),i=await JI.fetchJson(n);return VI.io.loadWeights(i,r)}sc.loadWeightMap=XI});var ab=S(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.matchDimensions=void 0;const ZI=Is();function QI(e,t,n=!1){const{width:r,height:i}=n?ZI.getMediaDimensions(t):t;return e.width=r,e.height=i,{width:r,height:i}}ac.matchDimensions=QI});var pb=S(cb=>{"use strict";Object.defineProperty(cb,"__esModule",{value:!0})});var tt=S(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});const Te=Be();Te.__exportStar(Qh(),we);Te.__exportStar(ed(),we);Te.__exportStar(As(),we);Te.__exportStar(tb(),we);Te.__exportStar(rb(),we);Te.__exportStar(ib(),we);Te.__exportStar(cd(),we);Te.__exportStar(ob(),we);Te.__exportStar(_s(),we);Te.__exportStar(ln(),we);Te.__exportStar(Is(),we);Te.__exportStar(nd(),we);Te.__exportStar(id(),we);Te.__exportStar(rd(),we);Te.__exportStar(ja(),we);Te.__exportStar(sb(),we);Te.__exportStar(ab(),we);Te.__exportStar(od(),we);Te.__exportStar(Ts(),we);Te.__exportStar(ad(),we);Te.__exportStar(pb(),we)});var Qt=S(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.NeuralNetwork=void 0;const Rs=ee(),eA=oc(),tA=tt(),nA=Ye();class rA{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){const{obj:t,objProp:n}=this.traversePropertyPath(e);return t[n]}reassignParamFromPath(e,t){const{obj:n,objProp:r}=this.traversePropertyPath(e);n[r].dispose(),n[r]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof Rs.Variable)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof Rs.Variable))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{const n=Rs.tensor(t.dataSync());t.dispose(),this.reassignParamFromPath(e,n)})}dispose(e=!0){this.getParamList().forEach(t=>{if(e&&t.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${t.path}`);t.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:e})=>Array.from(e.dataSync())).reduce((e,t)=>e.concat(t)))}async load(e){if(e instanceof Float32Array){this.extractWeights(e);return}await this.loadFromUri(e)}async loadFromUri(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const t=await tA.loadWeightMap(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=nA.env.getEnv(),{manifestUri:n,modelBaseUri:r}=eA.getModelUris(e,this.getDefaultModelName()),i=c=>Promise.all(c.map(p=>t(p).then(l=>l.buffer))),o=Rs.io.weightsLoaderFactory(i),a=JSON.parse((await t(n)).toString()),s=await o(a,r);this.loadFromWeightMap(s)}loadFromWeightMap(e){const{paramMappings:t,params:n}=this.extractParamsFromWeigthMap(e);this._paramMappings=t,this._params=n}extractWeights(e){const{paramMappings:t,params:n}=this.extractParams(e);this._paramMappings=t,this._params=n}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const t=e.split("/").reduce((i,o)=>{if(!i.nextObj.hasOwnProperty(o))throw new Error(`traversePropertyPath - object does not have property ${o}, for path ${e}`);return{obj:i.nextObj,objProp:o,nextObj:i.nextObj[o]}},{nextObj:this.params}),{obj:n,objProp:r}=t;if(!n||!r||!(n[r]instanceof Rs.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:n,objProp:r}}}cc.NeuralNetwork=rA});var ld=S(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.depthwiseSeparableConv=void 0;const pd=ee();function iA(e,t,n){return pd.tidy(()=>{let r=pd.separableConv2d(e,t.depthwise_filter,t.pointwise_filter,n,"same");return r=pd.add(r,t.bias),r})}pc.depthwiseSeparableConv=iA});var ud=S(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.denseBlock4=Dr.denseBlock3=void 0;const xe=ee(),nr=ld();function oA(e,t,n=!1){return xe.tidy(()=>{const r=xe.relu(n?xe.add(xe.conv2d(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):nr.depthwiseSeparableConv(e,t.conv0,[2,2])),i=nr.depthwiseSeparableConv(r,t.conv1,[1,1]),o=xe.relu(xe.add(r,i)),a=nr.depthwiseSeparableConv(o,t.conv2,[1,1]);return xe.relu(xe.add(r,xe.add(i,a)))})}Dr.denseBlock3=oA;function sA(e,t,n=!1,r=!0){return xe.tidy(()=>{const i=xe.relu(n?xe.add(xe.conv2d(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):nr.depthwiseSeparableConv(e,t.conv0,r?[2,2]:[1,1])),o=nr.depthwiseSeparableConv(i,t.conv1,[1,1]),a=xe.relu(xe.add(i,o)),s=nr.depthwiseSeparableConv(a,t.conv2,[1,1]),c=xe.relu(xe.add(i,xe.add(o,s))),p=nr.depthwiseSeparableConv(c,t.conv3,[1,1]);return xe.relu(xe.add(i,xe.add(o,xe.add(s,p))))})}Dr.denseBlock4=sA});var lb=S(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.convLayer=void 0;const uc=ee();function aA(e,t,n="same",r=!1){return uc.tidy(()=>{const i=uc.add(uc.conv2d(e,t.filters,[1,1],n),t.bias);return r?uc.relu(i):i})}lc.convLayer=aA});var hd=S(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.disposeUnusedWeightTensors=void 0;function cA(e,t){Object.keys(e).forEach(n=>{t.some(r=>r.originalPath===n)||e[n].dispose()})}hc.disposeUnusedWeightTensors=cA});var hb=S(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.extractConvParamsFactory=void 0;const ub=ee();function pA(e,t){return function(n,r,i,o){const a=ub.tensor4d(e(n*r*i*i),[i,i,n,r]),s=ub.tensor1d(e(r));return t.push({paramPath:`${o}/filters`},{paramPath:`${o}/bias`}),{filters:a,bias:s}}}dc.extractConvParamsFactory=pA});var mb=S(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.extractFCParamsFactory=void 0;const db=ee();function lA(e,t){return function(n,r,i){const o=db.tensor2d(e(n*r),[n,r]),a=db.tensor1d(e(r));return t.push({paramPath:`${i}/weights`},{paramPath:`${i}/bias`}),{weights:o,bias:a}}}mc.extractFCParamsFactory=lA});var dd=S(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.SeparableConvParams=void 0;class uA{constructor(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}}fc.SeparableConvParams=uA});var gc=S(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.loadSeparableConvParamsFactory=Fr.extractSeparableConvParamsFactory=void 0;const md=ee(),fb=dd();function hA(e,t){return function(n,r,i){const o=md.tensor4d(e(3*3*n),[3,3,n,1]),a=md.tensor4d(e(n*r),[1,1,n,r]),s=md.tensor1d(e(r));return t.push({paramPath:`${i}/depthwise_filter`},{paramPath:`${i}/pointwise_filter`},{paramPath:`${i}/bias`}),new fb.SeparableConvParams(o,a,s)}}Fr.extractSeparableConvParamsFactory=hA;function dA(e){return function(t){const n=e(`${t}/depthwise_filter`,4),r=e(`${t}/pointwise_filter`,4),i=e(`${t}/bias`,1);return new fb.SeparableConvParams(n,r,i)}}Fr.loadSeparableConvParamsFactory=dA});var fd=S(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.extractWeightEntryFactory=void 0;const mA=me();function fA(e,t){return function(n,r,i){const o=e[n];if(!mA.isTensor(o,r))throw new Error(`expected weightMap[${n}] to be a Tensor${r}D, instead have ${o}`);return t.push({originalPath:n,paramPath:i||n}),o}}bc.extractWeightEntryFactory=fA});var gd=S(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.extractWeightsFactory=void 0;function gA(e){let t=e;function n(i){const o=t.slice(0,i);return t=t.slice(i),o}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}wc.extractWeightsFactory=gA});var De=S(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});const Dt=Be();Dt.__exportStar(lb(),wt);Dt.__exportStar(ld(),wt);Dt.__exportStar(hd(),wt);Dt.__exportStar(hb(),wt);Dt.__exportStar(mb(),wt);Dt.__exportStar(gc(),wt);Dt.__exportStar(fd(),wt);Dt.__exportStar(gd(),wt);Dt.__exportStar(oc(),wt);Dt.__exportStar(dd(),wt)});var bd=S(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.extractorsFactory=void 0;const gb=De();function bA(e,t){const n=gb.extractConvParamsFactory(e,t),r=gb.extractSeparableConvParamsFactory(e,t);function i(a,s,c,p=!1){const l=p?n(a,s,3,`${c}/conv0`):r(a,s,`${c}/conv0`),u=r(s,s,`${c}/conv1`),m=r(s,s,`${c}/conv2`);return{conv0:l,conv1:u,conv2:m}}function o(a,s,c,p=!1){const{conv0:l,conv1:u,conv2:m}=i(a,s,c,p),b=r(s,s,`${c}/conv3`);return{conv0:l,conv1:u,conv2:m,conv3:b}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:o}}yc.extractorsFactory=bA});var bb=S(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.extractParams=void 0;const wA=De(),yA=bd();function xA(e){const t=[],{extractWeights:n,getRemainingWeights:r}=wA.extractWeightsFactory(e),{extractDenseBlock4Params:i}=yA.extractorsFactory(n,t),o=i(3,32,"dense0",!0),a=i(32,64,"dense1"),s=i(64,128,"dense2"),c=i(128,256,"dense3");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:o,dense1:a,dense2:s,dense3:c}}}xc.extractParams=xA});var wd=S(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.loadConvParamsFactory=void 0;function LA(e){return function(t){const n=e(`${t}/filters`,4),r=e(`${t}/bias`,1);return{filters:n,bias:r}}}Lc.loadConvParamsFactory=LA});var yd=S(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.loadParamsFactory=void 0;const wb=De(),vA=wd();function SA(e,t){const n=wb.extractWeightEntryFactory(e,t),r=vA.loadConvParamsFactory(n),i=wb.loadSeparableConvParamsFactory(n);function o(s,c=!1){const p=c?r(`${s}/conv0`):i(`${s}/conv0`),l=i(`${s}/conv1`),u=i(`${s}/conv2`);return{conv0:p,conv1:l,conv2:u}}function a(s,c=!1){const p=c?r(`${s}/conv0`):i(`${s}/conv0`),l=i(`${s}/conv1`),u=i(`${s}/conv2`),m=i(`${s}/conv3`);return{conv0:p,conv1:l,conv2:u,conv3:m}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:a}}vc.loadParamsFactory=SA});var yb=S(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.extractParamsFromWeigthMap=void 0;const TA=De(),IA=yd();function AA(e){const t=[],{extractDenseBlock4Params:n}=IA.loadParamsFactory(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return TA.disposeUnusedWeightTensors(e,t),{params:r,paramMappings:t}}Sc.extractParamsFromWeigthMap=AA});var Ld=S(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.FaceFeatureExtractor=void 0;const xd=ee(),NA=tt(),_A=Qt(),RA=pn(),Ic=ud(),CA=bb(),EA=yb();class OA extends _A.NeuralNetwork{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return xd.tidy(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],i=RA.normalize(n,r).div(xd.scalar(255));let o=Ic.denseBlock4(i,t.dense0,!0);return o=Ic.denseBlock4(o,t.dense1),o=Ic.denseBlock4(o,t.dense2),o=Ic.denseBlock4(o,t.dense3),o=xd.avgPool(o,[7,7],[2,2],"valid"),o})}async forward(e){return this.forwardInput(await NA.toNetInput(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return EA.extractParamsFromWeigthMap(e)}extractParams(e){return CA.extractParams(e)}}Tc.FaceFeatureExtractor=OA});var Sd=S(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.fullyConnectedLayer=void 0;const vd=ee();function kA(e,t){return vd.tidy(()=>vd.add(vd.matMul(e,t.weights),t.bias))}Ac.fullyConnectedLayer=kA});var Lb=S(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.extractParams=void 0;const xb=De();function DA(e,t,n){const r=[],{extractWeights:i,getRemainingWeights:o}=xb.extractWeightsFactory(e),a=xb.extractFCParamsFactory(i,r),s=a(t,n,"fc");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:r,params:{fc:s}}}Nc.extractParams=DA});var Sb=S(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.extractParamsFromWeigthMap=void 0;const vb=De();function FA(e){const t=[],n=vb.extractWeightEntryFactory(e,t);function r(o){const a=n(`${o}/weights`,2),s=n(`${o}/bias`,1);return{weights:a,bias:s}}const i={fc:r("fc")};return vb.disposeUnusedWeightTensors(e,t),{params:i,paramMappings:t}}_c.extractParamsFromWeigthMap=FA});var Td=S(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.seperateWeightMaps=void 0;function MA(e){const t={},n={};return Object.keys(e).forEach(r=>{const i=r.startsWith("fc")?n:t;i[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}Rc.seperateWeightMaps=MA});var Id=S(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.FaceProcessor=void 0;const UA=ee(),WA=Sd(),qA=tt(),BA=Qt(),PA=Lb(),jA=Sb(),GA=Td();class $A extends BA.NeuralNetwork{constructor(e,t){super(e);this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return UA.tidy(()=>{const n=e instanceof qA.NetInput?this.faceFeatureExtractor.forwardInput(e):e;return WA.fullyConnectedLayer(n.as2D(n.shape[0],-1),t.fc)})}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:n}=this.extractClassifierParams(e);this._params=t,this._paramMappings=n}extractClassifierParams(e){return PA.extractParams(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=GA.seperateWeightMaps(e);return this.faceFeatureExtractor.loadFromWeightMap(t),jA.extractParamsFromWeigthMap(n)}extractParams(e){const t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,i=e.slice(0,e.length-r),o=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(o)}}Cc.FaceProcessor=$A});var Ec=S(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.FaceExpressions=un.FACE_EXPRESSION_LABELS=void 0;un.FACE_EXPRESSION_LABELS=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class HA{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);un.FACE_EXPRESSION_LABELS.forEach((t,n)=>{this[t]=e[n]})}asSortedArray(){return un.FACE_EXPRESSION_LABELS.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}un.FaceExpressions=HA});var Nd=S(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.FaceExpressionNet=void 0;const Ad=ee(),Tb=tt(),YA=Ld(),zA=Id(),VA=Ec();class KA extends zA.FaceProcessor{constructor(e=new YA.FaceFeatureExtractor()){super("FaceExpressionNet",e)}forwardInput(e){return Ad.tidy(()=>Ad.softmax(this.runNet(e)))}async forward(e){return this.forwardInput(await Tb.toNetInput(e))}async predictExpressions(e){const t=await Tb.toNetInput(e),n=await this.forwardInput(t),r=await Promise.all(Ad.unstack(n).map(async o=>{const a=await o.data();return o.dispose(),a}));n.dispose();const i=r.map(o=>new VA.FaceExpressions(o));return t.isBatchInput?i:i[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}Oc.FaceExpressionNet=KA});var _d=S(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});const Ib=Be();Ib.__exportStar(Nd(),kc);Ib.__exportStar(Ec(),kc)});var Dc=S(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.extendWithFaceExpressions=Mr.isWithFaceExpressions=void 0;const JA=Ec();function XA(e){return e.expressions instanceof JA.FaceExpressions}Mr.isWithFaceExpressions=XA;function ZA(e,t){const n={expressions:t};return Object.assign({},e,n)}Mr.extendWithFaceExpressions=ZA});var Ab=S(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.drawFaceExpressions=void 0;const QA=pt(),eN=_d(),tN=tr(),nN=Dc(),rN=me(),iN=qa();function oN(e,t,n=.1,r){const i=Array.isArray(t)?t:[t];i.forEach(o=>{const a=o instanceof eN.FaceExpressions?o:nN.isWithFaceExpressions(o)?o.expressions:void 0;if(!a)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const s=a.asSortedArray(),c=s.filter(u=>u.probability>n),p=tN.isWithFaceDetection(o)?o.detection.box.bottomLeft:r||new QA.Point(0,0),l=new iN.DrawTextField(c.map(u=>`${u.expression} (${rN.round(u.probability)})`),p);l.draw(e)})}Fc.drawFaceExpressions=oN});var Wr=S(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendWithFaceLandmarks=Ur.isWithFaceLandmarks=void 0;const Nb=Xt(),_b=er(),sN=tr();function aN(e){return sN.isWithFaceDetection(e)&&e.landmarks instanceof _b.FaceLandmarks&&e.unshiftedLandmarks instanceof _b.FaceLandmarks&&e.alignedRect instanceof Nb.FaceDetection}Ur.isWithFaceLandmarks=aN;function cN(e,t){const{box:n}=e.detection,r=t.shiftBy(n.x,n.y),i=r.align(),{imageDims:o}=e.detection,a=new Nb.FaceDetection(e.detection.score,i.rescale(o.reverse()),o),s={landmarks:r,unshiftedLandmarks:t,alignedRect:a};return Object.assign({},e,s)}Ur.extendWithFaceLandmarks=cN});var Eb=S(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.drawFaceLandmarks=hn.DrawFaceLandmarks=hn.DrawFaceLandmarksOptions=void 0;const pN=er(),lN=Na(),uN=ln(),hN=Wr(),rr=Uh();class Rb{constructor(e={}){const{drawLines:t=!0,drawPoints:n=!0,lineWidth:r,lineColor:i,pointSize:o,pointColor:a}=e;this.drawLines=t,this.drawPoints=n,this.lineWidth=r||1,this.pointSize=o||2,this.lineColor=i||"rgba(0, 255, 255, 1)",this.pointColor=a||"rgba(255, 0, 255, 1)"}}hn.DrawFaceLandmarksOptions=Rb;class Cb{constructor(e,t={}){this.faceLandmarks=e,this.options=new Rb(t)}draw(e){const t=uN.getContext2dOrThrow(e),{drawLines:n,drawPoints:r,lineWidth:i,lineColor:o,pointSize:a,pointColor:s}=this.options;if(n&&this.faceLandmarks instanceof lN.FaceLandmarks68&&(t.strokeStyle=o,t.lineWidth=i,rr.drawContour(t,this.faceLandmarks.getJawOutline()),rr.drawContour(t,this.faceLandmarks.getLeftEyeBrow()),rr.drawContour(t,this.faceLandmarks.getRightEyeBrow()),rr.drawContour(t,this.faceLandmarks.getNose()),rr.drawContour(t,this.faceLandmarks.getLeftEye(),!0),rr.drawContour(t,this.faceLandmarks.getRightEye(),!0),rr.drawContour(t,this.faceLandmarks.getMouth(),!0)),r){t.strokeStyle=s,t.fillStyle=s;const c=p=>{t.beginPath(),t.arc(p.x,p.y,a,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(c)}}}hn.DrawFaceLandmarks=Cb;function dN(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const i=r instanceof pN.FaceLandmarks?r:hN.isWithFaceLandmarks(r)?r.landmarks:void 0;if(!i)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Cb(i).draw(e)})}hn.drawFaceLandmarks=dN});var Ob=S(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});const qr=Be();qr.__exportStar(Uh(),dn);qr.__exportStar(Hg(),dn);qr.__exportStar(Ab(),dn);qr.__exportStar(Zh(),dn);qr.__exportStar(Eb(),dn);qr.__exportStar(qa(),dn)});var kb=S(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.extractParams=void 0;const Rd=De(),mN=me();function fN(e,t){const n=Rd.extractConvParamsFactory(e,t),r=Rd.extractSeparableConvParamsFactory(e,t);function i(a,s,c){const p=r(a,s,`${c}/separable_conv0`),l=r(s,s,`${c}/separable_conv1`),u=n(a,s,1,`${c}/expansion_conv`);return{separable_conv0:p,separable_conv1:l,expansion_conv:u}}function o(a,s){const c=r(a,a,`${s}/separable_conv0`),p=r(a,a,`${s}/separable_conv1`),l=r(a,a,`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:i,extractMainBlockParams:o}}function gN(e,t){const n=[],{extractWeights:r,getRemainingWeights:i}=Rd.extractWeightsFactory(e),{extractConvParams:o,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:c}=fN(r,n),p=o(3,32,3,"entry_flow/conv_in"),l=s(32,64,"entry_flow/reduction_block_0"),u=s(64,128,"entry_flow/reduction_block_1"),m={conv_in:p,reduction_block_0:l,reduction_block_1:u},b={};mN.range(t,0,1).forEach(T=>{b[`main_block_${T}`]=c(128,`middle_flow/main_block_${T}`)});const y=s(128,256,"exit_flow/reduction_block"),w=a(256,512,"exit_flow/separable_conv"),L={reduction_block:y,separable_conv:w};if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:n,params:{entry_flow:m,middle_flow:b,exit_flow:L}}}Mc.extractParams=gN});var Db=S(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.extractParamsFromWeigthMap=void 0;const Cd=De(),bN=wd(),wN=me();function yN(e,t){const n=Cd.extractWeightEntryFactory(e,t),r=bN.loadConvParamsFactory(n),i=Cd.loadSeparableConvParamsFactory(n);function o(s){const c=i(`${s}/separable_conv0`),p=i(`${s}/separable_conv1`),l=r(`${s}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:l}}function a(s){const c=i(`${s}/separable_conv0`),p=i(`${s}/separable_conv1`),l=i(`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:r,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:a}}function xN(e,t){const n=[],{extractConvParams:r,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:a}=yN(e,n),s=r("entry_flow/conv_in"),c=o("entry_flow/reduction_block_0"),p=o("entry_flow/reduction_block_1"),l={conv_in:s,reduction_block_0:c,reduction_block_1:p},u={};wN.range(t,0,1).forEach(w=>{u[`main_block_${w}`]=a(`middle_flow/main_block_${w}`)});const m=o("exit_flow/reduction_block"),b=i("exit_flow/separable_conv"),y={reduction_block:m,separable_conv:b};return Cd.disposeUnusedWeightTensors(e,n),{params:{entry_flow:l,middle_flow:u,exit_flow:y},paramMappings:n}}Uc.extractParamsFromWeigthMap=xN});var Mb=S(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.TinyXception=void 0;const nt=ee(),Br=De(),LN=tt(),vN=Qt(),SN=pn(),TN=me(),IN=kb(),AN=Db();function Fb(e,t,n){return nt.add(nt.conv2d(e,t.filters,n,"same"),t.bias)}function Ed(e,t,n=!0){let r=n?nt.relu(e):e;return r=Br.depthwiseSeparableConv(r,t.separable_conv0,[1,1]),r=Br.depthwiseSeparableConv(nt.relu(r),t.separable_conv1,[1,1]),r=nt.maxPool(r,[3,3],[2,2],"same"),r=nt.add(r,Fb(e,t.expansion_conv,[2,2])),r}function NN(e,t){let n=Br.depthwiseSeparableConv(nt.relu(e),t.separable_conv0,[1,1]);return n=Br.depthwiseSeparableConv(nt.relu(n),t.separable_conv1,[1,1]),n=Br.depthwiseSeparableConv(nt.relu(n),t.separable_conv2,[1,1]),n=nt.add(n,e),n}class _N extends vN.NeuralNetwork{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return nt.tidy(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],i=SN.normalize(n,r).div(nt.scalar(256));let o=nt.relu(Fb(i,t.entry_flow.conv_in,[2,2]));return o=Ed(o,t.entry_flow.reduction_block_0,!1),o=Ed(o,t.entry_flow.reduction_block_1),TN.range(this._numMainBlocks,0,1).forEach(a=>{o=NN(o,t.middle_flow[`main_block_${a}`])}),o=Ed(o,t.exit_flow.reduction_block),o=nt.relu(Br.depthwiseSeparableConv(o,t.exit_flow.separable_conv,[1,1])),o})}async forward(e){return this.forwardInput(await LN.toNetInput(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return AN.extractParamsFromWeigthMap(e,this._numMainBlocks)}extractParams(e){return IN.extractParams(e,this._numMainBlocks)}}Wc.TinyXception=_N});var Wb=S(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.extractParams=void 0;const Ub=De();function RN(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ub.extractWeightsFactory(e),i=Ub.extractFCParamsFactory(n,t),o=i(512,1,"fc/age"),a=i(512,2,"fc/gender");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{fc:{age:o,gender:a}}}}qc.extractParams=RN});var Bb=S(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.extractParamsFromWeigthMap=void 0;const qb=De();function CN(e){const t=[],n=qb.extractWeightEntryFactory(e,t);function r(o){const a=n(`${o}/weights`,2),s=n(`${o}/bias`,1);return{weights:a,bias:s}}const i={fc:{age:r("fc/age"),gender:r("fc/gender")}};return qb.disposeUnusedWeightTensors(e,t),{params:i,paramMappings:t}}Bc.extractParamsFromWeigthMap=CN});var Pc=S(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.Gender=void 0;var EN;(function(e){e.FEMALE="female",e.MALE="male"})(EN=Cs.Gender||(Cs.Gender={}))});var kd=S(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.AgeGenderNet=void 0;const Pr=ee(),Pb=Sd(),ON=Td(),kN=Mb(),DN=Wb(),FN=Bb(),jb=Pc(),MN=Qt(),Od=tt();class UN extends MN.NeuralNetwork{constructor(e=new kN.TinyXception(2)){super("AgeGenderNet");this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return Pr.tidy(()=>{const n=e instanceof Od.NetInput?this.faceFeatureExtractor.forwardInput(e):e,r=Pr.avgPool(n,[7,7],[2,2],"valid").as2D(n.shape[0],-1),i=Pb.fullyConnectedLayer(r,t.fc.age).as1D(),o=Pb.fullyConnectedLayer(r,t.fc.gender);return{age:i,gender:o}})}forwardInput(e){return Pr.tidy(()=>{const{age:t,gender:n}=this.runNet(e);return{age:t,gender:Pr.softmax(n)}})}async forward(e){return this.forwardInput(await Od.toNetInput(e))}async predictAgeAndGender(e){const t=await Od.toNetInput(e),n=await this.forwardInput(t),r=Pr.unstack(n.age),i=Pr.unstack(n.gender),o=r.map((s,c)=>({ageTensor:s,genderTensor:i[c]})),a=await Promise.all(o.map(async({ageTensor:s,genderTensor:c})=>{const p=(await s.data())[0],l=(await c.data())[0],u=l>.5,m=u?jb.Gender.MALE:jb.Gender.FEMALE,b=u?l:1-l;return s.dispose(),c.dispose(),{age:p,gender:m,genderProbability:b}}));return n.age.dispose(),n.gender.dispose(),t.isBatchInput?a:a[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:n}=this.extractClassifierParams(e);this._params=t,this._paramMappings=n}extractClassifierParams(e){return DN.extractParams(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=ON.seperateWeightMaps(e);return this.faceFeatureExtractor.loadFromWeightMap(t),FN.extractParamsFromWeigthMap(n)}extractParams(e){const t=512*1+1+(512*2+2),n=e.slice(0,e.length-t),r=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(r)}}jc.AgeGenderNet=UN});var $b=S(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});const Gb=Be();Gb.__exportStar(kd(),Gc);Gb.__exportStar(Pc(),Gc)});var Dd=S($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.FaceLandmark68NetBase=void 0;const Ft=ee(),WN=pt(),qN=Na(),Hb=tt(),BN=Id(),Yb=me();class PN extends BN.FaceProcessor{postProcess(e,t,n){const r=n.map(({width:o,height:a})=>{const s=t/Math.max(a,o);return{width:o*s,height:a*s}}),i=r.length;return Ft.tidy(()=>{const o=(l,u)=>Ft.stack([Ft.fill([68],l),Ft.fill([68],u)],1).as2D(1,136).as1D(),a=(l,u)=>{const{width:m,height:b}=r[l];return u(m,b)?Math.abs(m-b)/2:0},s=l=>a(l,(u,m)=>u<m),c=l=>a(l,(u,m)=>m<u),p=e.mul(Ft.fill([i,136],t)).sub(Ft.stack(Array.from(Array(i),(l,u)=>o(s(u),c(u))))).div(Ft.stack(Array.from(Array(i),(l,u)=>o(r[u].width,r[u].height))));return p})}forwardInput(e){return Ft.tidy(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([n,r])=>({height:n,width:r})))})}async forward(e){return this.forwardInput(await Hb.toNetInput(e))}async detectLandmarks(e){const t=await Hb.toNetInput(e),n=Ft.tidy(()=>Ft.unstack(this.forwardInput(t))),r=await Promise.all(n.map(async(i,o)=>{const a=Array.from(await i.data()),s=a.filter((p,l)=>Yb.isEven(l)),c=a.filter((p,l)=>!Yb.isEven(l));return new qN.FaceLandmarks68(Array(68).fill(0).map((p,l)=>new WN.Point(s[l],c[l])),{height:t.getInputHeight(o),width:t.getInputWidth(o)})}));return n.forEach(i=>i.dispose()),t.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}}$c.FaceLandmark68NetBase=PN});var Yc=S(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.FaceLandmark68Net=void 0;const jN=Ld(),GN=Dd();class $N extends GN.FaceLandmark68NetBase{constructor(e=new jN.FaceFeatureExtractor()){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}Hc.FaceLandmark68Net=$N});var zb=S(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.extractParamsFromWeigthMapTiny=void 0;const HN=De(),YN=yd();function zN(e){const t=[],{extractDenseBlock3Params:n}=YN.loadParamsFactory(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return HN.disposeUnusedWeightTensors(e,t),{params:r,paramMappings:t}}zc.extractParamsFromWeigthMapTiny=zN});var Vb=S(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.extractParamsTiny=void 0;const VN=De(),KN=bd();function JN(e){const t=[],{extractWeights:n,getRemainingWeights:r}=VN.extractWeightsFactory(e),{extractDenseBlock3Params:i}=KN.extractorsFactory(n,t),o=i(3,32,"dense0",!0),a=i(32,64,"dense1"),s=i(64,128,"dense2");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:o,dense1:a,dense2:s}}}Vc.extractParamsTiny=JN});var Kb=S(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.TinyFaceFeatureExtractor=void 0;const Fd=ee(),XN=tt(),ZN=Qt(),QN=pn(),Md=ud(),e2=zb(),t2=Vb();class n2 extends ZN.NeuralNetwork{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Fd.tidy(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],i=QN.normalize(n,r).div(Fd.scalar(255));let o=Md.denseBlock3(i,t.dense0,!0);return o=Md.denseBlock3(o,t.dense1),o=Md.denseBlock3(o,t.dense2),o=Fd.avgPool(o,[14,14],[2,2],"valid"),o})}async forward(e){return this.forwardInput(await XN.toNetInput(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return e2.extractParamsFromWeigthMapTiny(e)}extractParams(e){return t2.extractParamsTiny(e)}}Kc.TinyFaceFeatureExtractor=n2});var Ud=S(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.FaceLandmark68TinyNet=void 0;const r2=Kb(),i2=Dd();class o2 extends i2.FaceLandmark68NetBase{constructor(e=new r2.TinyFaceFeatureExtractor()){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}Jc.FaceLandmark68TinyNet=o2});var Xb=S(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.FaceLandmarkNet=void 0;const Jb=Be(),s2=Yc();Jb.__exportStar(Yc(),jr);Jb.__exportStar(Ud(),jr);class a2 extends s2.FaceLandmark68Net{}jr.FaceLandmarkNet=a2});var Qb=S(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.scale=void 0;const Zb=ee();function c2(e,t){return Zb.add(Zb.mul(e,t.weights),t.biases)}Xc.scale=c2});var Bd=S(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.convDown=mn.convNoRelu=mn.conv=void 0;const Wd=ee(),p2=Qb();function qd(e,t,n,r,i="same"){const{filters:o,bias:a}=t.conv;let s=Wd.conv2d(e,o,n,i);return s=Wd.add(s,a),s=p2.scale(s,t.scale),r?Wd.relu(s):s}function l2(e,t){return qd(e,t,[1,1],!0)}mn.conv=l2;function u2(e,t){return qd(e,t,[1,1],!1)}mn.convNoRelu=u2;function h2(e,t){return qd(e,t,[2,2],!0,"valid")}mn.convDown=h2});var ew=S(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.extractParams=void 0;const en=ee(),d2=De(),m2=me();function f2(e,t){function n(s,c,p){const l=e(s),u=l.length/(c*p*p);if(m2.isFloat(u))throw new Error(`depth has to be an integer: ${u}, weights.length: ${l.length}, numFilters: ${c}, filterSize: ${p}`);return en.tidy(()=>en.transpose(en.tensor4d(l,[c,u,p,p]),[2,3,1,0]))}function r(s,c,p,l){const u=n(s,c,p),m=en.tensor1d(e(c));return t.push({paramPath:`${l}/filters`},{paramPath:`${l}/bias`}),{filters:u,bias:m}}function i(s,c){const p=en.tensor1d(e(s)),l=en.tensor1d(e(s));return t.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:p,biases:l}}function o(s,c,p,l){const u=r(s,c,p,`${l}/conv`),m=i(c,`${l}/scale`);return{conv:u,scale:m}}function a(s,c,p,l,u=!1){const m=o((u?.5:1)*s,c,p,`${l}/conv1`),b=o(s,c,p,`${l}/conv2`);return{conv1:m,conv2:b}}return{extractConvLayerParams:o,extractResidualLayerParams:a}}function g2(e){const{extractWeights:t,getRemainingWeights:n}=d2.extractWeightsFactory(e),r=[],{extractConvLayerParams:i,extractResidualLayerParams:o}=f2(t,r),a=i(4704,32,7,"conv32_down"),s=o(9216,32,3,"conv32_1"),c=o(9216,32,3,"conv32_2"),p=o(9216,32,3,"conv32_3"),l=o(36864,64,3,"conv64_down",!0),u=o(36864,64,3,"conv64_1"),m=o(36864,64,3,"conv64_2"),b=o(36864,64,3,"conv64_3"),y=o(147456,128,3,"conv128_down",!0),w=o(147456,128,3,"conv128_1"),L=o(147456,128,3,"conv128_2"),T=o(589824,256,3,"conv256_down",!0),A=o(589824,256,3,"conv256_1"),_=o(589824,256,3,"conv256_2"),N=o(589824,256,3,"conv256_down_out"),C=en.tidy(()=>en.transpose(en.tensor2d(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);const F={conv32_down:a,conv32_1:s,conv32_2:c,conv32_3:p,conv64_down:l,conv64_1:u,conv64_2:m,conv64_3:b,conv128_down:y,conv128_1:w,conv128_2:L,conv256_down:T,conv256_1:A,conv256_2:_,conv256_down_out:N,fc:C};return{params:F,paramMappings:r}}Zc.extractParams=g2});var nw=S(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.extractParamsFromWeigthMap=void 0;const tw=De(),b2=me();function w2(e,t){const n=tw.extractWeightEntryFactory(e,t);function r(a){const s=n(`${a}/scale/weights`,1),c=n(`${a}/scale/biases`,1);return{weights:s,biases:c}}function i(a){const s=n(`${a}/conv/filters`,4),c=n(`${a}/conv/bias`,1),p=r(a);return{conv:{filters:s,bias:c},scale:p}}function o(a){return{conv1:i(`${a}/conv1`),conv2:i(`${a}/conv2`)}}return{extractConvLayerParams:i,extractResidualLayerParams:o}}function y2(e){const t=[],{extractConvLayerParams:n,extractResidualLayerParams:r}=w2(e,t),i=n("conv32_down"),o=r("conv32_1"),a=r("conv32_2"),s=r("conv32_3"),c=r("conv64_down"),p=r("conv64_1"),l=r("conv64_2"),u=r("conv64_3"),m=r("conv128_down"),b=r("conv128_1"),y=r("conv128_2"),w=r("conv256_down"),L=r("conv256_1"),T=r("conv256_2"),A=r("conv256_down_out"),_=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!b2.isTensor2D(_))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${_}`);const N={conv32_down:i,conv32_1:o,conv32_2:a,conv32_3:s,conv64_down:c,conv64_1:p,conv64_2:l,conv64_3:u,conv128_down:m,conv128_1:b,conv128_2:y,conv256_down:w,conv256_1:L,conv256_2:T,conv256_down_out:A,fc:_};return tw.disposeUnusedWeightTensors(e,t),{params:N,paramMappings:t}}Qc.extractParamsFromWeigthMap=y2});var rw=S(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.residualDown=Gr.residual=void 0;const _t=ee(),ep=Bd();function x2(e,t){let n=ep.conv(e,t.conv1);return n=ep.convNoRelu(n,t.conv2),n=_t.add(n,e),n=_t.relu(n),n}Gr.residual=x2;function L2(e,t){let n=ep.convDown(e,t.conv1);n=ep.convNoRelu(n,t.conv2);let r=_t.avgPool(e,2,2,"valid");const i=_t.zeros(r.shape),o=r.shape[3]!==n.shape[3],a=r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2];if(a){const s=[...n.shape];s[1]=1;const c=_t.zeros(s);n=_t.concat([n,c],1);const p=[...n.shape];p[2]=1;const l=_t.zeros(p);n=_t.concat([n,l],2)}return r=o?_t.concat([r,i],3):r,n=_t.add(r,n),n=_t.relu(n),n}Gr.residualDown=L2});var np=S(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.FaceRecognitionNet=void 0;const $r=ee(),iw=tt(),v2=Qt(),S2=pn(),T2=Bd(),I2=ew(),A2=nw(),rt=rw();class N2 extends v2.NeuralNetwork{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return $r.tidy(()=>{const n=e.toBatchTensor(150,!0).toFloat(),r=[122.782,117.001,104.298],i=S2.normalize(n,r).div($r.scalar(256));let o=T2.convDown(i,t.conv32_down);o=$r.maxPool(o,3,2,"valid"),o=rt.residual(o,t.conv32_1),o=rt.residual(o,t.conv32_2),o=rt.residual(o,t.conv32_3),o=rt.residualDown(o,t.conv64_down),o=rt.residual(o,t.conv64_1),o=rt.residual(o,t.conv64_2),o=rt.residual(o,t.conv64_3),o=rt.residualDown(o,t.conv128_down),o=rt.residual(o,t.conv128_1),o=rt.residual(o,t.conv128_2),o=rt.residualDown(o,t.conv256_down),o=rt.residual(o,t.conv256_1),o=rt.residual(o,t.conv256_2),o=rt.residualDown(o,t.conv256_down_out);const a=o.mean([1,2]),s=$r.matMul(a,t.fc);return s})}async forward(e){return this.forwardInput(await iw.toNetInput(e))}async computeFaceDescriptor(e){const t=await iw.toNetInput(e),n=$r.tidy(()=>$r.unstack(this.forwardInput(t))),r=await Promise.all(n.map(i=>i.data()));return n.forEach(i=>i.dispose()),t.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return A2.extractParamsFromWeigthMap(e)}extractParams(e){return I2.extractParams(e)}}tp.FaceRecognitionNet=N2});var ow=S(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.createFaceRecognitionNet=void 0;const _2=Be(),R2=np();_2.__exportStar(np(),Es);function C2(e){const t=new R2.FaceRecognitionNet();return t.extractWeights(e),t}Es.createFaceRecognitionNet=C2});var Pd=S(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});rp.extendWithFaceDescriptor=void 0;function E2(e,t){const n={descriptor:t};return Object.assign({},e,n)}rp.extendWithFaceDescriptor=E2});var jd=S(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.extendWithAge=Hr.isWithAge=void 0;function O2(e){return typeof e.age=="number"}Hr.isWithAge=O2;function k2(e,t){const n={age:t};return Object.assign({},e,n)}Hr.extendWithAge=k2});var Gd=S(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.extendWithGender=Yr.isWithGender=void 0;const sw=Pc(),D2=me();function F2(e){return(e.gender===sw.Gender.MALE||e.gender===sw.Gender.FEMALE)&&D2.isValidProbablitiy(e.genderProbability)}Yr.isWithGender=F2;function M2(e,t,n){const r={gender:t,genderProbability:n};return Object.assign({},e,r)}Yr.extendWithGender=M2});var aw=S(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});const zr=Be();zr.__exportStar(Pd(),fn);zr.__exportStar(tr(),fn);zr.__exportStar(Dc(),fn);zr.__exportStar(Wr(),fn);zr.__exportStar(jd(),fn);zr.__exportStar(Gd(),fn)});var ir=S(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.ComposableTask=void 0;class U2{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}ip.ComposableTask=U2});var op=S(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.extractSingleFaceAndComputeResult=Vr.extractAllFacesAndComputeResults=void 0;const cw=ee(),pw=tt(),W2=Wr();async function lw(e,t,n,r,i=({alignedRect:o})=>o){const o=e.map(c=>W2.isWithFaceLandmarks(c)?i(c):c.detection),a=r||(t instanceof cw.Tensor?await pw.extractFaceTensors(t,o):await pw.extractFaces(t,o)),s=await n(a);return a.forEach(c=>c instanceof cw.Tensor&&c.dispose()),s}Vr.extractAllFacesAndComputeResults=lw;async function q2(e,t,n,r,i){return lw([e],t,async o=>n(o[0]),r,i)}Vr.extractSingleFaceAndComputeResult=q2});var $d=S(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});sp.validateConfig=void 0;const ap=e=>typeof e=="number";function B2(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!ap(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new 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(t=>typeof t=="string"))throw new 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(t=>t||{}).every(t=>ap(t.x)&&ap(t.y)))throw new 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(ap)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}sp.validateConfig=B2});var pp=S(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});cp.leaky=void 0;const Kr=ee();function P2(e){return Kr.tidy(()=>{const t=Kr.mul(e,Kr.scalar(.10000000149011612));return Kr.add(Kr.relu(Kr.sub(e,t)),t)})}cp.leaky=P2});var uw=S(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});lp.convWithBatchNorm=void 0;const Jr=ee(),j2=pp();function G2(e,t){return Jr.tidy(()=>{let n=Jr.pad(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Jr.conv2d(n,t.conv.filters,[1,1],"valid"),n=Jr.sub(n,t.bn.sub),n=Jr.mul(n,t.bn.truediv),n=Jr.add(n,t.conv.bias),j2.leaky(n)})}lp.convWithBatchNorm=G2});var hw=S(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});up.depthwiseSeparableConv=void 0;const hp=ee(),$2=pp();function H2(e,t){return hp.tidy(()=>{let n=hp.pad(e,[[0,0],[1,1],[1,1],[0,0]]);return n=hp.separableConv2d(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=hp.add(n,t.bias),$2.leaky(n)})}up.depthwiseSeparableConv=H2});var mw=S(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});dp.extractParams=void 0;const dw=ee(),Y2=De(),z2=gc(),V2=gd();function K2(e,t){const n=Y2.extractConvParamsFactory(e,t);function r(a,s){const c=dw.tensor1d(e(a)),p=dw.tensor1d(e(a));return t.push({paramPath:`${s}/sub`},{paramPath:`${s}/truediv`}),{sub:c,truediv:p}}function i(a,s,c){const p=n(a,s,3,`${c}/conv`),l=r(s,`${c}/bn`);return{conv:p,bn:l}}const o=z2.extractSeparableConvParamsFactory(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:o}}function J2(e,t,n,r){const{extractWeights:i,getRemainingWeights:o}=V2.extractWeightsFactory(e),a=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:p}=K2(i,a);let l;if(t.withSeparableConvs){const[u,m,b,y,w,L,T,A,_]=r,N=t.isFirstLayerConv2d?s(u,m,3,"conv0"):p(u,m,"conv0"),C=p(m,b,"conv1"),F=p(b,y,"conv2"),E=p(y,w,"conv3"),B=p(w,L,"conv4"),q=p(L,T,"conv5"),P=A?p(T,A,"conv6"):void 0,te=_?p(A,_,"conv7"):void 0,ne=s(_||A||T,5*n,1,"conv8");l={conv0:N,conv1:C,conv2:F,conv3:E,conv4:B,conv5:q,conv6:P,conv7:te,conv8:ne}}else{const[u,m,b,y,w,L,T,A,_]=r,N=c(u,m,"conv0"),C=c(m,b,"conv1"),F=c(b,y,"conv2"),E=c(y,w,"conv3"),B=c(w,L,"conv4"),q=c(L,T,"conv5"),P=c(T,A,"conv6"),te=c(A,_,"conv7"),ne=s(_,5*n,1,"conv8");l={conv0:N,conv1:C,conv2:F,conv3:E,conv4:B,conv5:q,conv6:P,conv7:te,conv8:ne}}if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{params:l,paramMappings:a}}dp.extractParams=J2});var fw=S(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.extractParamsFromWeigthMap=void 0;const X2=hd(),Z2=gc(),Q2=fd();function e_(e,t){const n=Q2.extractWeightEntryFactory(e,t);function r(s){const c=n(`${s}/sub`,1),p=n(`${s}/truediv`,1);return{sub:c,truediv:p}}function i(s){const c=n(`${s}/filters`,4),p=n(`${s}/bias`,1);return{filters:c,bias:p}}function o(s){const c=i(`${s}/conv`),p=r(`${s}/bn`);return{conv:c,bn:p}}const a=Z2.loadSeparableConvParamsFactory(n);return{extractConvParams:i,extractConvWithBatchNormParams:o,extractSeparableConvParams:a}}function t_(e,t){const n=[],{extractConvParams:r,extractConvWithBatchNormParams:i,extractSeparableConvParams:o}=e_(e,n);let a;if(t.withSeparableConvs){const s=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?r("conv0"):o("conv0"),conv1:o("conv1"),conv2:o("conv2"),conv3:o("conv3"),conv4:o("conv4"),conv5:o("conv5"),conv6:s>7?o("conv6"):void 0,conv7:s>8?o("conv7"):void 0,conv8:r("conv8")}}else a={conv0:i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:i("conv6"),conv7:i("conv7"),conv8:r("conv8")};return X2.disposeUnusedWeightTensors(e,n),{params:a,paramMappings:n}}mp.extractParamsFromWeigthMap=t_});var Hd=S(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.TinyYolov2Options=or.TinyYolov2SizeType=void 0;var n_;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(n_=or.TinyYolov2SizeType||(or.TinyYolov2SizeType={}));class r_{constructor({inputSize:e,scoreThreshold:t}={}){if(this._name="TinyYolov2Options",this._inputSize=e||416,this._scoreThreshold=t||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}}or.TinyYolov2Options=r_});var Kd=S(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});fp.TinyYolov2Base=void 0;const Ce=ee(),i_=Wh(),o_=fa(),Yd=De(),gw=tt(),s_=Qt(),zd=pn(),a_=Bh(),c_=Ph(),p_=$d(),gn=uw(),bn=hw(),l_=mw(),u_=fw(),h_=pp(),d_=Hd();class Vd extends s_.NeuralNetwork{constructor(e){super("TinyYolov2");p_.validateConfig(e),this._config=e}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(e,t){let n=gn.convWithBatchNorm(e,t.conv0);return n=Ce.maxPool(n,[2,2],[2,2],"same"),n=gn.convWithBatchNorm(n,t.conv1),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=gn.convWithBatchNorm(n,t.conv2),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=gn.convWithBatchNorm(n,t.conv3),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=gn.convWithBatchNorm(n,t.conv4),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=gn.convWithBatchNorm(n,t.conv5),n=Ce.maxPool(n,[2,2],[1,1],"same"),n=gn.convWithBatchNorm(n,t.conv6),n=gn.convWithBatchNorm(n,t.conv7),Yd.convLayer(n,t.conv8,"valid",!1)}runMobilenet(e,t){let n=this.config.isFirstLayerConv2d?h_.leaky(Yd.convLayer(e,t.conv0,"valid",!1)):bn.depthwiseSeparableConv(e,t.conv0);return n=Ce.maxPool(n,[2,2],[2,2],"same"),n=bn.depthwiseSeparableConv(n,t.conv1),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=bn.depthwiseSeparableConv(n,t.conv2),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=bn.depthwiseSeparableConv(n,t.conv3),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=bn.depthwiseSeparableConv(n,t.conv4),n=Ce.maxPool(n,[2,2],[2,2],"same"),n=bn.depthwiseSeparableConv(n,t.conv5),n=Ce.maxPool(n,[2,2],[1,1],"same"),n=t.conv6?bn.depthwiseSeparableConv(n,t.conv6):n,n=t.conv7?bn.depthwiseSeparableConv(n,t.conv7):n,Yd.convLayer(n,t.conv8,"valid",!1)}forwardInput(e,t){const{params:n}=this;if(!n)throw new Error("TinyYolov2 - load model before inference");return Ce.tidy(()=>{let r=e.toBatchTensor(t,!1).toFloat();return r=this.config.meanRgb?c_.normalize(r,this.config.meanRgb):r,r=r.div(Ce.scalar(256)),this.config.withSeparableConvs?this.runMobilenet(r,n):this.runTinyYolov2(r,n)})}async forward(e,t){return await this.forwardInput(await gw.toNetInput(e),t)}async detect(e,t={}){const{inputSize:n,scoreThreshold:r}=new d_.TinyYolov2Options(t),i=await gw.toNetInput(e),o=await this.forwardInput(i,n),a=Ce.tidy(()=>Ce.unstack(o)[0].expandDims()),s={width:i.getInputWidth(0),height:i.getInputHeight(0)},c=await this.extractBoxes(a,i.getReshapedInputDimensions(0),r);o.dispose(),a.dispose();const p=c.map(w=>w.box),l=c.map(w=>w.score),u=c.map(w=>w.classScore),m=c.map(w=>this.config.classes[w.label]),b=a_.nonMaxSuppression(p.map(w=>w.rescale(n)),l,this.config.iouThreshold,!0),y=b.map(w=>new o_.ObjectDetection(l[w],u[w],m[w],p[w],s));return y}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return u_.extractParamsFromWeigthMap(e,this.config)}extractParams(e){const t=this.config.filterSizes||Vd.DEFAULT_FILTER_SIZES,n=t?t.length:void 0;if(n!==7&&n!==8&&n!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${n} filterSizes in config`);return l_.extractParams(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,n){const{width:r,height:i}=t,o=Math.max(r,i),a=o/r,s=o/i,c=e.shape[1],p=this.config.anchors.length,[l,u,m]=Ce.tidy(()=>{const L=e.reshape([c,c,p,this.boxEncodingSize]),T=L.slice([0,0,0,0],[c,c,p,4]),A=L.slice([0,0,0,4],[c,c,p,1]),_=this.withClassScores?Ce.softmax(L.slice([0,0,0,5],[c,c,p,this.config.classes.length]),3):Ce.scalar(0);return[T,A,_]}),b=[],y=await u.array(),w=await l.array();for(let L=0;L<c;L++)for(let T=0;T<c;T++)for(let A=0;A<p;A++){const _=zd.sigmoid(y[L][T][A][0]);if(!n||_>n){const N=(T+zd.sigmoid(w[L][T][A][0]))/c*a,C=(L+zd.sigmoid(w[L][T][A][1]))/c*s,F=Math.exp(w[L][T][A][2])*this.config.anchors[A].x/c*a,E=Math.exp(w[L][T][A][3])*this.config.anchors[A].y/c*s,B=N-F/2,q=C-E/2,P={row:L,col:T,anchor:A},{classScore:te,label:ne}=this.withClassScores?await this.extractPredictedClass(m,P):{classScore:1,label:0};b.push({box:new i_.BoundingBox(B,q,B+F,q+E),score:_,classScore:_*te,label:ne,...P})}}return l.dispose(),u.dispose(),m.dispose(),b}async extractPredictedClass(e,t){const{row:n,col:r,anchor:i}=t,o=await e.array();return Array(this.config.classes.length).fill(0).map((a,s)=>o[n][r][i][s]).map((a,s)=>({classScore:a,label:s})).reduce((a,s)=>a.classScore>s.classScore?a:s)}}fp.TinyYolov2Base=Vd;Vd.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024]});var bw=S(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.MEAN_RGB=wn.BOX_ANCHORS=wn.IOU_THRESHOLD=void 0;const Os=pt();wn.IOU_THRESHOLD=.4;wn.BOX_ANCHORS=[new Os.Point(1.603231,2.094468),new Os.Point(6.041143,7.080126),new Os.Point(2.882459,3.518061),new Os.Point(4.266906,5.178857),new Os.Point(9.041765,10.66308)];wn.MEAN_RGB=[117.001,114.697,97.404]});var bp=S(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});gp.TinyFaceDetector=void 0;const m_=pt(),f_=Kd(),Jd=bw();class g_ extends f_.TinyYolov2Base{constructor(){const e={withSeparableConvs:!0,iouThreshold:Jd.IOU_THRESHOLD,classes:["face"],anchors:Jd.BOX_ANCHORS,meanRgb:Jd.MEAN_RGB,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new m_.FaceDetection(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}gp.TinyFaceDetector=g_});var ww=S(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.DEFAULT_MODEL_NAME_SEPARABLE_CONV=it.DEFAULT_MODEL_NAME=it.MEAN_RGB_SEPARABLE=it.BOX_ANCHORS_SEPARABLE=it.BOX_ANCHORS=it.IOU_THRESHOLD=void 0;const Mt=pt();it.IOU_THRESHOLD=.4;it.BOX_ANCHORS=[new Mt.Point(.738768,.874946),new Mt.Point(2.42204,2.65704),new Mt.Point(4.30971,7.04493),new Mt.Point(10.246,4.59428),new Mt.Point(12.6868,11.8741)];it.BOX_ANCHORS_SEPARABLE=[new Mt.Point(1.603231,2.094468),new Mt.Point(6.041143,7.080126),new Mt.Point(2.882459,3.518061),new Mt.Point(4.266906,5.178857),new Mt.Point(9.041765,10.66308)];it.MEAN_RGB_SEPARABLE=[117.001,114.697,97.404];it.DEFAULT_MODEL_NAME="tiny_yolov2_model";it.DEFAULT_MODEL_NAME_SEPARABLE_CONV="tiny_yolov2_separable_conv_model"});var yw=S(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.TinyYolov2=void 0;const b_=pt(),Xr=ww(),w_=Kd();class y_ extends w_.TinyYolov2Base{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:Xr.IOU_THRESHOLD,classes:["face"]},e?{anchors:Xr.BOX_ANCHORS_SEPARABLE,meanRgb:Xr.MEAN_RGB_SEPARABLE}:{anchors:Xr.BOX_ANCHORS,withClassScores:!0});super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new b_.FaceDetection(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?Xr.DEFAULT_MODEL_NAME_SEPARABLE_CONV:Xr.DEFAULT_MODEL_NAME}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}wp.TinyYolov2=y_});var Lw=S(xw=>{"use strict";Object.defineProperty(xw,"__esModule",{value:!0})});var yp=S(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.createTinyYolov2=tn.TinyYolov2=void 0;const Xd=Be(),vw=yw();Object.defineProperty(tn,"TinyYolov2",{enumerable:!0,get:function(){return vw.TinyYolov2}});Xd.__exportStar(Hd(),tn);Xd.__exportStar($d(),tn);Xd.__exportStar(Lw(),tn);function x_(e,t=!0){const n=new vw.TinyYolov2(t);return n.extractWeights(e),n}tn.createTinyYolov2=x_});var sr=S(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.detectLandmarks=j.locateFaces=j.loadFaceDetectionModel=j.loadAgeGenderModel=j.loadFaceExpressionModel=j.loadFaceRecognitionModel=j.loadFaceLandmarkTinyModel=j.loadFaceLandmarkModel=j.loadTinyYolov2Model=j.loadTinyFaceDetectorModel=j.predictAgeAndGender=j.recognizeFaceExpressions=j.computeFaceDescriptor=j.detectFaceLandmarksTiny=j.detectFaceLandmarks=j.tinyFaceDetector=j.nets=void 0;const L_=kd(),v_=Nd(),S_=Yc(),T_=Ud(),I_=np(),Sw=bp(),A_=yp();j.nets={tinyFaceDetector:new Sw.TinyFaceDetector(),tinyYolov2:new A_.TinyYolov2(),faceLandmark68Net:new S_.FaceLandmark68Net(),faceLandmark68TinyNet:new T_.FaceLandmark68TinyNet(),faceRecognitionNet:new I_.FaceRecognitionNet(),faceExpressionNet:new v_.FaceExpressionNet(),ageGenderNet:new L_.AgeGenderNet()};j.tinyFaceDetector=(e,t)=>j.nets.tinyFaceDetector.locateFaces(e,t);j.detectFaceLandmarks=e=>j.nets.faceLandmark68Net.detectLandmarks(e);j.detectFaceLandmarksTiny=e=>j.nets.faceLandmark68TinyNet.detectLandmarks(e);j.computeFaceDescriptor=e=>j.nets.faceRecognitionNet.computeFaceDescriptor(e);j.recognizeFaceExpressions=e=>j.nets.faceExpressionNet.predictExpressions(e);j.predictAgeAndGender=e=>j.nets.ageGenderNet.predictAgeAndGender(e);j.loadTinyFaceDetectorModel=e=>j.nets.tinyFaceDetector.load(e);j.loadTinyYolov2Model=e=>j.nets.tinyYolov2.load(e);j.loadFaceLandmarkModel=e=>j.nets.faceLandmark68Net.load(e);j.loadFaceLandmarkTinyModel=e=>j.nets.faceLandmark68TinyNet.load(e);j.loadFaceRecognitionModel=e=>j.nets.faceRecognitionNet.load(e);j.loadFaceExpressionModel=e=>j.nets.faceExpressionNet.load(e);j.loadAgeGenderModel=e=>j.nets.ageGenderNet.load(e);j.loadFaceDetectionModel=j.loadTinyFaceDetectorModel;j.locateFaces=Sw.TinyFaceDetector;j.detectLandmarks=j.detectFaceLandmarks});var Fs=S(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.PredictSingleFaceExpressionsWithFaceAlignmentTask=yt.PredictAllFaceExpressionsWithFaceAlignmentTask=yt.PredictSingleFaceExpressionsTask=yt.PredictAllFaceExpressionsTask=yt.PredictFaceExpressionsTaskBase=void 0;const Tw=Dc(),N_=ir(),Iw=ks(),Aw=op(),Nw=sr(),xp=Ds();class Zd extends N_.ComposableTask{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}yt.PredictFaceExpressionsTaskBase=Zd;class _w extends Zd{async run(){const e=await this.parentTask,t=await Aw.extractAllFacesAndComputeResults(e,this.input,async n=>await Promise.all(n.map(r=>Nw.nets.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return e.map((n,r)=>Tw.extendWithFaceExpressions(n,t[r]))}withAgeAndGender(){return new xp.PredictAllAgeAndGenderTask(this,this.input)}}yt.PredictAllFaceExpressionsTask=_w;class Rw extends Zd{async run(){const e=await this.parentTask;if(!e)return;const t=await Aw.extractSingleFaceAndComputeResult(e,this.input,n=>Nw.nets.faceExpressionNet.predictExpressions(n),this.extractedFaces);return Tw.extendWithFaceExpressions(e,t)}withAgeAndGender(){return new xp.PredictSingleAgeAndGenderTask(this,this.input)}}yt.PredictSingleFaceExpressionsTask=Rw;class __ extends _w{withAgeAndGender(){return new xp.PredictAllAgeAndGenderWithFaceAlignmentTask(this,this.input)}withFaceDescriptors(){return new Iw.ComputeAllFaceDescriptorsTask(this,this.input)}}yt.PredictAllFaceExpressionsWithFaceAlignmentTask=__;class R_ extends Rw{withAgeAndGender(){return new xp.PredictSingleAgeAndGenderWithFaceAlignmentTask(this,this.input)}withFaceDescriptor(){return new Iw.ComputeSingleFaceDescriptorTask(this,this.input)}}yt.PredictSingleFaceExpressionsWithFaceAlignmentTask=R_});var Ds=S(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.PredictSingleAgeAndGenderWithFaceAlignmentTask=xt.PredictAllAgeAndGenderWithFaceAlignmentTask=xt.PredictSingleAgeAndGenderTask=xt.PredictAllAgeAndGenderTask=xt.PredictAgeAndGenderTaskBase=void 0;const Cw=jd(),Ew=Gd(),C_=ir(),Ow=ks(),kw=op(),Dw=sr(),Lp=Fs();class Qd extends C_.ComposableTask{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}xt.PredictAgeAndGenderTaskBase=Qd;class Fw extends Qd{async run(){const e=await this.parentTask,t=await kw.extractAllFacesAndComputeResults(e,this.input,async n=>await Promise.all(n.map(r=>Dw.nets.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return e.map((n,r)=>{const{age:i,gender:o,genderProbability:a}=t[r];return Cw.extendWithAge(Ew.extendWithGender(n,o,a),i)})}withFaceExpressions(){return new Lp.PredictAllFaceExpressionsTask(this,this.input)}}xt.PredictAllAgeAndGenderTask=Fw;class Mw extends Qd{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:n,genderProbability:r}=await kw.extractSingleFaceAndComputeResult(e,this.input,i=>Dw.nets.ageGenderNet.predictAgeAndGender(i),this.extractedFaces);return Cw.extendWithAge(Ew.extendWithGender(e,n,r),t)}withFaceExpressions(){return new Lp.PredictSingleFaceExpressionsTask(this,this.input)}}xt.PredictSingleAgeAndGenderTask=Mw;class E_ extends Fw{withFaceExpressions(){return new Lp.PredictAllFaceExpressionsWithFaceAlignmentTask(this,this.input)}withFaceDescriptors(){return new Ow.ComputeAllFaceDescriptorsTask(this,this.input)}}xt.PredictAllAgeAndGenderWithFaceAlignmentTask=E_;class O_ extends Mw{withFaceExpressions(){return new Lp.PredictSingleFaceExpressionsWithFaceAlignmentTask(this,this.input)}withFaceDescriptor(){return new Ow.ComputeSingleFaceDescriptorTask(this,this.input)}}xt.PredictSingleAgeAndGenderWithFaceAlignmentTask=O_});var ks=S(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.ComputeSingleFaceDescriptorTask=yn.ComputeAllFaceDescriptorsTask=yn.ComputeFaceDescriptorsTaskBase=void 0;const Uw=Pd(),k_=ir(),Ww=op(),qw=sr(),Bw=Ds(),Pw=Fs();class em extends k_.ComposableTask{constructor(e,t){super();this.parentTask=e,this.input=t}}yn.ComputeFaceDescriptorsTaskBase=em;class D_ extends em{async run(){const e=await this.parentTask,t=await Ww.extractAllFacesAndComputeResults(e,this.input,n=>Promise.all(n.map(r=>qw.nets.faceRecognitionNet.computeFaceDescriptor(r))),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return t.map((n,r)=>Uw.extendWithFaceDescriptor(e[r],n))}withFaceExpressions(){return new Pw.PredictAllFaceExpressionsWithFaceAlignmentTask(this,this.input)}withAgeAndGender(){return new Bw.PredictAllAgeAndGenderWithFaceAlignmentTask(this,this.input)}}yn.ComputeAllFaceDescriptorsTask=D_;class F_ extends em{async run(){const e=await this.parentTask;if(!e)return;const t=await Ww.extractSingleFaceAndComputeResult(e,this.input,n=>qw.nets.faceRecognitionNet.computeFaceDescriptor(n),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return Uw.extendWithFaceDescriptor(e,t)}withFaceExpressions(){return new Pw.PredictSingleFaceExpressionsWithFaceAlignmentTask(this,this.input)}withAgeAndGender(){return new Bw.PredictSingleAgeAndGenderWithFaceAlignmentTask(this,this.input)}}yn.ComputeSingleFaceDescriptorTask=F_});var Sp=S(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.TinyFaceDetectorOptions=void 0;const M_=yp();class U_ extends M_.TinyYolov2Options{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}vp.TinyFaceDetectorOptions=U_});var nm=S(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.DetectSingleFaceLandmarksTask=xn.DetectAllFaceLandmarksTask=xn.DetectFaceLandmarksTaskBase=void 0;const Tp=ee(),Ip=tt(),jw=Wr(),W_=ir(),Gw=ks(),$w=sr(),Hw=Ds(),Yw=Fs();class tm extends W_.ComposableTask{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?$w.nets.faceLandmark68TinyNet:$w.nets.faceLandmark68Net}}xn.DetectFaceLandmarksTaskBase=tm;class q_ extends tm{async run(){const e=await this.parentTask,t=e.map(i=>i.detection),n=this.input instanceof Tp.Tensor?await Ip.extractFaceTensors(this.input,t):await Ip.extractFaces(this.input,t),r=await Promise.all(n.map(i=>this.landmarkNet.detectLandmarks(i)));return n.forEach(i=>i instanceof Tp.Tensor&&i.dispose()),e.map((i,o)=>jw.extendWithFaceLandmarks(i,r[o]))}withFaceExpressions(){return new Yw.PredictAllFaceExpressionsWithFaceAlignmentTask(this,this.input)}withAgeAndGender(){return new Hw.PredictAllAgeAndGenderWithFaceAlignmentTask(this,this.input)}withFaceDescriptors(){return new Gw.ComputeAllFaceDescriptorsTask(this,this.input)}}xn.DetectAllFaceLandmarksTask=q_;class B_ extends tm{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,n=this.input instanceof Tp.Tensor?await Ip.extractFaceTensors(this.input,[t]):await Ip.extractFaces(this.input,[t]),r=await this.landmarkNet.detectLandmarks(n[0]);return n.forEach(i=>i instanceof Tp.Tensor&&i.dispose()),jw.extendWithFaceLandmarks(e,r)}withFaceExpressions(){return new Yw.PredictSingleFaceExpressionsWithFaceAlignmentTask(this,this.input)}withAgeAndGender(){return new Hw.PredictSingleAgeAndGenderWithFaceAlignmentTask(this,this.input)}withFaceDescriptor(){return new Gw.ComputeSingleFaceDescriptorTask(this,this.input)}}xn.DetectSingleFaceLandmarksTask=B_});var im=S(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.DetectSingleFaceTask=Ln.DetectAllFacesTask=Ln.DetectFacesTaskBase=void 0;const zw=tr(),Vw=Sp(),P_=ir(),Kw=nm(),j_=sr(),Jw=Ds(),Xw=Fs();class rm extends P_.ComposableTask{constructor(e,t=new Vw.TinyFaceDetectorOptions()){super();this.input=e,this.options=t}}Ln.DetectFacesTaskBase=rm;class Zw extends rm{async run(){const{input:e,options:t}=this,n=t instanceof Vw.TinyFaceDetectorOptions?r=>j_.nets.tinyFaceDetector.locateFaces(r,t):null;if(!n)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return n(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(n=>zw.extendWithFaceDetection({},n)))})}withFaceLandmarks(e=!1){return new Kw.DetectAllFaceLandmarksTask(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Xw.PredictAllFaceExpressionsTask(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Jw.PredictAllAgeAndGenderTask(this.runAndExtendWithFaceDetections(),this.input)}}Ln.DetectAllFacesTask=Zw;class G_ extends rm{async run(){const e=await new Zw(this.input,this.options);let t=e[0];return e.forEach(n=>{n.score>t.score&&(t=n)}),t}runAndExtendWithFaceDetection(){return new Promise(async e=>{const t=await this.run();return e(t?zw.extendWithFaceDetection({},t):void 0)})}withFaceLandmarks(e=!1){return new Kw.DetectSingleFaceLandmarksTask(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Xw.PredictSingleFaceExpressionsTask(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Jw.PredictSingleAgeAndGenderTask(this.runAndExtendWithFaceDetection(),this.input)}}Ln.DetectSingleFaceTask=G_});var ty=S(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.detectAllFaces=Zr.detectSingleFace=void 0;const Qw=im(),ey=Sp();function $_(e,t=new ey.TinyFaceDetectorOptions()){return new Qw.DetectSingleFaceTask(e,t)}Zr.detectSingleFace=$_;function H_(e,t=new ey.TinyFaceDetectorOptions()){return new Qw.DetectAllFacesTask(e,t)}Zr.detectAllFaces=H_});var om=S(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.euclideanDistance=void 0;function Y_(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map((i,o)=>i-r[o]).reduce((i,o)=>i+Math.pow(o,2),0))}Ap.euclideanDistance=Y_});var iy=S(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});Np.FaceMatcher=void 0;const ny=Hh(),_p=zh(),z_=om();class ry{constructor(e,t=.6){this._distanceThreshold=t;const n=Array.isArray(e)?e:[e];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1;const i=()=>`person ${r++}`;this._labeledDescriptors=n.map(o=>{if(o instanceof _p.LabeledFaceDescriptors)return o;if(o instanceof Float32Array)return new _p.LabeledFaceDescriptors(i(),[o]);if(o.descriptor&&o.descriptor instanceof Float32Array)return new _p.LabeledFaceDescriptors(i(),[o.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(e,t){return t.map(n=>z_.euclideanDistance(n,e)).reduce((n,r)=>n+r,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:n})=>new ny.FaceMatch(n,this.computeMeanDistance(e,t))).reduce((t,n)=>t.distance<n.distance?t:n)}findBestMatch(e){const t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new ny.FaceMatch("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(n=>_p.LabeledFaceDescriptors.fromJSON(n));return new ry(t,e.distanceThreshold)}}Np.FaceMatcher=ry});var sy=S(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0})});var ay=S(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});const vn=Be();vn.__exportStar(ir(),Ut);vn.__exportStar(ks(),Ut);vn.__exportStar(ty(),Ut);vn.__exportStar(im(),Ut);vn.__exportStar(nm(),Ut);vn.__exportStar(iy(),Ut);vn.__exportStar(sr(),Ut);vn.__exportStar(sy(),Ut)});var py=S(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.createTinyFaceDetector=void 0;const cy=Be(),V_=bp();cy.__exportStar(bp(),Qr);cy.__exportStar(Sp(),Qr);function K_(e){const t=new V_.TinyFaceDetector();return t.extractWeights(e),t}Qr.createTinyFaceDetector=K_});var hy=S(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});Rp.resizeResults=void 0;const J_=pt(),X_=Xt(),Z_=er(),sm=tr(),ly=Wr();function uy(e,t){const{width:n,height:r}=new J_.Dimensions(t.width,t.height);if(n<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:r})}`);if(Array.isArray(e))return e.map(i=>uy(i,{width:n,height:r}));if(ly.isWithFaceLandmarks(e)){const i=e.detection.forSize(n,r),o=e.unshiftedLandmarks.forSize(i.box.width,i.box.height);return ly.extendWithFaceLandmarks(sm.extendWithFaceDetection(e,i),o)}return sm.isWithFaceDetection(e)?sm.extendWithFaceDetection(e,e.detection.forSize(n,r)):e instanceof Z_.FaceLandmarks||e instanceof X_.FaceDetection?e.forSize(n,r):e}Rp.resizeResults=uy});var dy=S(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.tf=ye.utils=ye.draw=void 0;const Je=Be(),Q_=ee();ye.tf=Q_;const e0=Ob();ye.draw=e0;const t0=me();ye.utils=t0;Je.__exportStar($b(),ye);Je.__exportStar(pt(),ye);Je.__exportStar(tt(),ye);Je.__exportStar(Ye(),ye);Je.__exportStar(_d(),ye);Je.__exportStar(Xb(),ye);Je.__exportStar(ow(),ye);Je.__exportStar(aw(),ye);Je.__exportStar(ay(),ye);Je.__exportStar(pn(),ye);Je.__exportStar(py(),ye);Je.__exportStar(yp(),ye);Je.__exportStar(om(),ye);Je.__exportStar(Qt(),ye);Je.__exportStar(hy(),ye)});const my="tfjsflags";class Fh{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(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}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){const r=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${r}.`),this.set(e,r)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(t instanceof Promise)throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new 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)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=n0(this.global.location.search);if(my in e){const t=e[my].split(",");t.forEach(n=>{const[r,i]=n.split(":");this.urlFlags[r]=r0(r,i)})}}}function n0(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>(i0(t,r[0],r[1]),r.join("="))),t}function i0(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function r0(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function se(){return Mh}let Mh=null;function fy(e){Mh=e}let am;function cm(){if(am==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");am=e}return am}function o0(){const e=cm();return e._tfGlobals==null&&(e._tfGlobals=new Map()),e._tfGlobals}function pm(e,t){const n=o0();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const Mi="Abs",Ui="Acos",Wi="Acosh",Jn="Add",qi="AddN",Wu="All",qu="Any",Bi="ArgMax",Pi="ArgMin",ji="Asin",Gi="Asinh",$i="Atan",Hi="Atanh",Yi="Atan2",zi="AvgPool",Bu="AvgPoolBackprop",Vi="AvgPool3D",Pu="AvgPool3DBackprop",Ki="BatchMatMul",Ji="BatchToSpaceND",Xi="BroadcastTo",Xn="Cast",Zi="Ceil",Qi="ClipByValue",ju="Complex",eo="Concat",to="Conv2D",Gu="Conv2DBackpropFilter",no="Conv2DBackpropInput",ro="Conv3D",$u="Conv3DBackpropFilterV2",Hu="Conv3DBackpropInputV2",io="Cos",oo="Cosh",so="Cumsum",Yu="CropAndResize",zu="DepthToSpace",ao="DepthwiseConv2dNative",Vu="DepthwiseConv2dNativeBackpropFilter",Ku="DepthwiseConv2dNativeBackpropInput",Ju="Diag",co="Dilation2D",Xu="Dilation2DBackpropInput",Zu="Dilation2DBackpropFilter",po="Div",lo="Elu",Qu="EluGrad",uo="Erf",eh="Equal",ho="Exp",mo="Expm1",th="FFT",nh="Fill",rh="FlipLeftRight",fo="Floor",go="FloorDiv",bo="FusedBatchNorm",wo="GatherV2",ih="GatherNd",oh="Greater",yo="GreaterEqual",xo="Identity",sh="IFFT",ah="Imag",Lo="IsFinite",vo="IsInf",So="IsNan",ch="Less",ph="LessEqual",lh="LinSpace",To="Log",Io="Log1p",uh="LogicalAnd",hh="LogicalNot",dh="LogicalOr",Ao="LogSoftmax",No="LRN",mh="LRNBackprop",_o="Max",Ro="Maximum",Co="MaxPool",fh="MaxPoolBackprop",Eo="MaxPool3D",gh="MaxPool3DBackprop",bh="MaxPoolWithArgmax",oS="Mean",Oo="Min",ko="Minimum",Do="Mod",Fo="Multiply",Mo="Negate",wh="NotEqual",yh="NonMaxSuppressionV3",xh="NonMaxSuppressionV4",Lh="NonMaxSuppressionV5",Uo="OnesLike",Wo="OneHot",qo="PadV2",sS="Pool",Bo="Pow",Po="Prelu",vh="Prod",Sh="Range",Th="Real",jo="Reciprocal",Go="Relu",$o="Reshape",Ho="ResizeNearestNeighbor",Ih="ResizeNearestNeighborGrad",Yo="ResizeBilinear",Ah="ResizeBilinearGrad",zo="Relu6",Vo="Reverse",Ko="Round",Jo="Rsqrt",Nh="ScatterNd",Xo="SelectV2",Zo="Selu",Qo="Slice",es="Sin",ts="Sinh",ns="Sign",rs="Sigmoid",is="Softplus",os="Sqrt",ss="Sum",as="SpaceToBatchND",cs="SplitV",ps="Softmax",ls="SquaredDifference",_h="Square",us="Sub",Rh="SparseToDense",Ch="StridedSlice",hs="Tan",ds="Tanh",ms="Tile",Eh="TopK",fs="Transpose",gs="Unpack",bs="UnsortedSegmentSum",ws="ZerosLike",ys="Step",ra="FromPixels",Oh="RotateWithOffset",ia="_FusedMatMul",oa="FusedConv2D",sa="FusedDepthwiseConv2D";const ei=pm("kernelRegistry",()=>new Map()),Ms=pm("gradRegistry",()=>new Map());function Fi(e,t){const n=lm(e,t);return ei.get(n)}function ta(e){return Ms.get(e)}function na(e){const t=ei.entries(),n=[];for(;;){const{done:r,value:i}=t.next();if(r)break;const[o,a]=i,[s]=o.split("_");s===e&&n.push(a)}return n}function nS(e){const{kernelName:t,backendName:n}=e,r=lm(t,n);ei.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),ei.set(r,e)}function Uu(e){const{kernelName:t}=e;Ms.has(t)&&(se().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Ms.set(t,e)}function rS(e,t){const n=lm(e,t);if(!ei.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ei.delete(n)}function iS(e){if(!Ms.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Ms.delete(e)}function lm(e,t){return`${t}_${e}`}const _f={};Oe(_f,{arraysEqual:()=>Le,assert:()=>f,assertNonNegativeIntegerDimensions:()=>qs,assertNonNull:()=>lt,assertShapesMatch:()=>$,bytesFromStringArray:()=>bm,bytesPerElement:()=>gm,checkConversionForErrors:()=>by,clamp:()=>ti,computeStrides:()=>Bt,createShuffledIndices:()=>d0,decodeString:()=>Ep,distSquared:()=>p0,encodeString:()=>wm,fetch:()=>b0,flatten:()=>Wt,getArrayFromDType:()=>dm,getTypedArrayFromDType:()=>ni,hasEncodingLoss:()=>fm,indexToLoc:()=>y0,inferDtype:()=>ri,inferFromImplicitShape:()=>um,isBoolean:()=>wy,isFunction:()=>qt,isInt:()=>J,isNumber:()=>yy,isScalarShape:()=>l0,isString:()=>Rt,isTypedArray:()=>Ie,isValidDtype:()=>mm,locToIndex:()=>w0,makeOnesTypedArray:()=>Ws,makeZerosNestedTypedArray:()=>g0,makeZerosTypedArray:()=>Pt,nearestDivisor:()=>ii,nearestLargerEven:()=>s0,now:()=>Cp,parseAxisParam:()=>z,randUniform:()=>c0,repeatedTry:()=>m0,rightPad:()=>ar,shuffle:()=>gy,sizeFromShape:()=>Z,sizeToSquarishShape:()=>h0,squeezeShape:()=>hm,sum:()=>a0,tanh:()=>u0,toNestedArray:()=>cr,toTypedArray:()=>Us});function gy(e){let t=e.length,n=0,r=0;for(;t>0;)r=Math.random()*t|0,t--,n=e[t],e[t]=e[r],e[r]=n}function ti(e,t,n){return Math.max(e,Math.min(t,n))}function s0(e){return e%2===0?e:e+1}function a0(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function c0(e,t){const n=Math.random();return t*n+(1-n)*e}function p0(e,t){let n=0;for(let r=0;r<e.length;r++){const i=Number(e[r])-Number(t[r]);n+=i*i}return n}function f(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function $(e,t,n=""){f(Le(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function lt(e){f(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Wt(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Ie(e)&&!n)for(let r=0;r<e.length;++r)Wt(e[r],t,n);else t.push(e);return t}function Z(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function l0(e){return e.length===0}function Le(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function J(e){return e%1===0}function u0(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function h0(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function d0(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return gy(t),t}function ar(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function m0(e,t=r=>0,n){return new Promise((r,i)=>{let o=0;const a=()=>{if(e()){r();return}o++;const s=t(o);if(n!=null&&o>=n){i();return}setTimeout(a,s)};a()})}function um(e,t){let n=1,r=-1;for(let o=0;o<e.length;++o)if(e[o]>=0)n*=e[o];else if(e[o]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${o}`);r=o}else if(e[o]<0)throw Error(`Shapes can not be < 0. Found ${e[o]} at dim ${o}`);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}`);const i=e.slice();return i[r]=t/n,i}function z(e,t){const n=t.length;return e=e==null?t.map((r,i)=>i):[].concat(e),f(e.every(r=>r>=-n&&r<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),f(e.every(r=>J(r)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(r=>r<0?n+r:r)}function hm(e,t){const n=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:z(t,e).sort();let a=0;for(let s=0;s<e.length;++s){if(o!=null){if(o[a]===s&&e[s]!==1)throw new Error(`Can't squeeze axis ${s} since its dim '${e[s]}' is not 1`);(o[a]==null||o[a]>s)&&e[s]===1&&(n.push(e[s]),r.push(s)),o[a]<=s&&a++}e[s]!==1&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function ni(e,t){let 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 throw new Error(`Unknown data type ${e}`);return n}function dm(e,t){let 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")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function by(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function mm(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function fm(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function Ie(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function gm(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function bm(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Rt(e){return typeof e=="string"||e instanceof String}function wy(e){return typeof e=="boolean"}function yy(e){return typeof e=="number"}function ri(e){return Array.isArray(e)?ri(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":yy(e)?"float32":Rt(e)?"string":wy(e)?"bool":"float32"}function qt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ii(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Bt(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function Us(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Wt(e)),se().getBool("DEBUG")&&by(e,t),f0(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"){const n=new Uint8Array(e.length);for(let r=0;r<n.length;++r)Math.round(e[r])!==0&&(n[r]=1);return n}else throw new Error(`Unknown data type ${t}`)}function xy(e,t,n){const r=new Array();if(t.length===1){const i=t[0];for(let o=0;o<i;o++)r[o]=n[e+o]}else{const i=t[0],o=t.slice(1),a=o.reduce((s,c)=>s*c);for(let s=0;s<i;s++)r[s]=xy(e+s*a,o,n)}return r}function cr(e,t){if(e.length===0)return t[0];const n=e.reduce((r,i)=>r*i);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return xy(0,e,t)}function f0(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Ws(e,t){const n=Pt(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function Pt(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 new Error(`Unknown data type ${t}`)}function g0(e,t){const n=e.reduce((r,i)=>r*i,1);if(t==null||t==="float32")return cr(e,new Float32Array(n));if(t==="int32")return cr(e,new Int32Array(n));if(t==="bool")return cr(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Cp(){return se().platform.now()}function qs(e){e.forEach(t=>{f(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function b0(e,t){return se().platform.fetch(e,t)}function wm(e,t="utf-8"){return t=t||"utf-8",se().platform.encode(e,t)}function Ep(e,t="utf-8"){return t=t||"utf-8",se().platform.decode(e,t)}function w0(e,t,n){if(t===0)return 0;if(t===1)return e[0];let r=e[e.length-1];for(let i=0;i<e.length-1;++i)r+=n[i]*e[i];return r}function y0(e,t,n){if(t===0)return[];if(t===1)return[e];const r=new Array(t);for(let 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}class Ly{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new L0())}profileKernel(e,t,n){let r;const i=()=>{r=n()},o=this.backendTimer.time(i);r.map(s=>{s.data().then(c=>{x0(c,s.dtype,e)})});const a={kernelName:e,outputs:r,inputs:t,timeMs:o.then(s=>s.kernelMs),extraInfo:o.then(s=>s.getExtraProfileInfo!=null?s.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:i,extraInfo:o}=e;n.forEach(a=>{Promise.all([a.data(),r,o]).then(s=>{this.logger.logKernelProfile(t,a,s[0],s[1],i,s[2])})})}}function x0(e,t,n){if(t!=="float32")return!1;for(let r=0;r<e.length;r++){const i=e[r];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class L0{logKernelProfile(e,t,n,r,i,o){const a=typeof r=="number"?ar(`${r}ms`,9):r.error,s=ar(e,25),c=t.rank,p=t.size,l=ar(t.shape.toString(),14);let u="";for(const m in i){const b=i[m];if(b!=null){const y=b.shape||t.shape,w=y.length;u+=`${m}: ${w}D ${w>0?y:""} `}}console.log(`%c${s} %c${a} %c${c}D ${l} %c${p} %c${u} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function vy(e,t,n){const r={},i={};for(let c=0;c<t.length;c++)r[t[c].id]=!0;for(let c=0;c<e.length;c++){const p=e[c],l=p.inputs;for(const u in l){const m=l[u];let b=!1;for(let y=0;y<t.length;y++)if(r[m.id]){p.outputs.forEach(w=>r[w.id]=!0),b=!0,i[p.id]=!0;break}if(b)break}}const o={};o[n.id]=!0;const a={};for(let c=e.length-1;c>=0;c--){const p=e[c],l=p.inputs;for(let u=0;u<p.outputs.length;u++)if(o[p.outputs[u].id]){for(const m in l)o[l[m].id]=!0,a[p.id]=!0;break}}const s=[];for(let c=0;c<e.length;c++){const p=e[c];if(i[p.id]&&a[p.id]){const l={};for(const m in p.inputs){const b=p.inputs[m];r[b.id]&&(l[m]=b)}const u=Object.assign({},p);u.inputs=l,u.outputs=p.outputs,s.push(u)}}return s}function Sy(e,t,n,r){for(let i=t.length-1;i>=0;i--){const o=t[i],a=[];if(o.outputs.forEach(c=>{const p=e[c.id];p!=null?a.push(p):a.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const s=o.gradient(a);for(const c in o.inputs){if(!(c in s))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(s)}.`);const p=n(()=>s[c]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${p.dtype}'`);const l=o.inputs[c];if(!Le(p.shape,l.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${c}' has shape '${p.shape}', which does not match the shape of the input '${l.shape}'`);if(e[l.id]==null)e[l.id]=p;else{const u=e[l.id];e[l.id]=r(u,p),u.dispose()}}}}const Ty=20,Bs=3,ym=7;function Iy(e,t,n,r){const i=Bt(t),o=v0(e,t,n,i),a=t.length,s=Op(e,t,n,i,o),c=["Tensor"];return r&&(c.push(` dtype: ${n}`),c.push(` rank: ${a}`),c.push(` shape: [${t}]`),c.push(" values:")),c.push(s.map(p=>" "+p).join(`
|
|
`)),c.join(`
|
|
`)}function v0(e,t,n,r){const i=Z(t),o=r[r.length-1],a=new Array(o).fill(0),s=t.length,c=n==="complex64"?js(e):e;if(s>1)for(let p=0;p<i/o;p++){const l=p*o;for(let u=0;u<o;u++)a[u]=Math.max(a[u],Ps(c[l+u],0,n).length)}return a}function Ps(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(ym))} + ${parseFloat(e[1].toFixed(ym))}j`:Rt(e)?r=`'${e}'`:n==="bool"?r=Ay(e):r=parseFloat(e.toFixed(ym)).toString(),ar(r,t)}function Ay(e){return e===0?"false":"true"}function Op(e,t,n,r,i,o=!0){const a=n==="complex64"?2:1,s=t[0],c=t.length;if(c===0){if(n==="complex64"){const w=js(e);return[Ps(w[0],0,n)]}return n==="bool"?[Ay(e[0])]:[e[0].toString()]}if(c===1){if(s>Ty){const L=Bs*a;let T=Array.from(e.slice(0,L)),A=Array.from(e.slice((s-Bs)*a,s*a));return n==="complex64"&&(T=js(T),A=js(A)),["["+T.map((_,N)=>Ps(_,i[N],n)).join(", ")+", ..., "+A.map((_,N)=>Ps(_,i[s-Bs+N],n)).join(", ")+"]"]}const w=n==="complex64"?js(e):Array.from(e);return["["+w.map((L,T)=>Ps(L,i[T],n)).join(", ")+"]"]}const p=t.slice(1),l=r.slice(1),u=r[0]*a,m=[];if(s>Ty){for(let w=0;w<Bs;w++){const L=w*u,T=L+u;m.push(...Op(e.slice(L,T),p,n,l,i,!1))}m.push("...");for(let w=s-Bs;w<s;w++){const L=w*u,T=L+u;m.push(...Op(e.slice(L,T),p,n,l,i,w===s-1))}}else for(let w=0;w<s;w++){const L=w*u,T=L+u;m.push(...Op(e.slice(L,T),p,n,l,i,w===s-1))}const b=c===2?",":"";m[0]="["+m[0]+b;for(let w=1;w<m.length-1;w++)m[w]=" "+m[w]+b;let y=`,
|
|
`;for(let w=2;w<c;w++)y+=`
|
|
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(o?"":y),m}function js(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class yr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Z(e),n!=null){const r=n.length;f(r===this.size,()=>`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new 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||dm(t,this.size),this.strides=Bt(e)}set(e,...t){t.length===0&&(t=[0]),f(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let 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}get rank(){return this.shape.length}toTensor(){return jt().makeTensor(this.values,this.shape,this.dtype)}}let jt=null,oi=null,S0=null;function Ny(e){jt=e}function _y(e){oi=e}function Ry(e){S0=e}class de{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Z(e),this.strides=Bt(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return oi.buffer(this.shape,this.dtype,e)}bufferSync(){return oi.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return cr(this.shape,e)}arraySync(){return cr(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=jt().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Ep(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=jt().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ep(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await jt().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;jt().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return oi.print(this,e)}clone(){return this.throwIfDisposed(),oi.clone(this)}toString(e=!1){const t=this.dataSync();return Iy(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),oi.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),jt().makeVariable(this,e,t,n)}}Object.defineProperty(de,Symbol.hasInstance,{value:e=>!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null});class Nn extends de{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Le(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);jt().disposeTensor(this),this.dataId=e.dataId,jt().incRef(this,null)}dispose(){jt().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Nn,Symbol.hasInstance,{value:e=>e instanceof de&&e.assign!=null&&e.assign instanceof Function});var al;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(al||(al={}));var xm;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(xm||(xm={}));var Lm;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Lm||(Lm={}));var vm;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(vm||(vm={}));var Sm;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Sm||(Sm={}));const T0={float32:vm,int32:xm,bool:Lm,complex64:Sm};function wr(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return T0[e][t]}function eS(e){return wr(e,"int32")}const Cf={};Oe(Cf,{assertTypesMatch:()=>Tm,getTensorsInContainer:()=>Gs,isTensorInList:()=>I0,makeTypesMatch:()=>V});function V(e,t){if(e.dtype===t.dtype)return[e,t];const n=wr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Tm(e,t){f(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function I0(e,t){return t.some(n=>n.id===e.id)}function Gs(e){const t=[],n=new Set();return Cy(e,t,n),t}function Cy(e,t,n){if(e==null)return;if(e instanceof de){t.push(e);return}if(!A0(e))return;const r=e;for(const i in r){const o=r[i];n.has(o)||(n.add(o),Cy(o,t,n))}}function A0(e){return Array.isArray(e)||typeof e=="object"}class Ey{constructor(){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}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class $s{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ey()}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],r=await this.initializeBackend(n).success;if(r){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new 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){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e),r=n?await t:t;if(!r)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Ly(this.backendInstance),!0}setupRegisteredKernels(){const e=na(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=na(e);t.forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(Promise.resolve(n)===n){const r=++this.pendingBackendInitId,i=n.then(o=>r<this.pendingBackendInitId?!1:(this.registry[e]=o,this.pendingBackendInit=null,!0)).catch(o=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.message)),!1));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new 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)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:i}=this.initializeBackend(n);if(i||r)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const 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]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let r;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,n){e();try{const r=n();return t(),r}catch(r){throw t(),r}}nextTensorId(){return $s.nextTensorId++}nextVariableId(){return $s.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},r=o=>({x:()=>{const a="float32",s={x:o},c={dtype:a};return g.runKernelFunc(p=>p.cast(o,a),s,null,Xn,c)}}),i=[];return this.addTapeNode(this.state.activeScope.name,n,[t],r,i,{}),t}runKernel(e,t,n,r,i){const o=null,a=null;return this.runKernelFunc(o,t,a,e,n,r,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let i=0;n.forEach(s=>{i+=s.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-i-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,r,i,o,a){let s,c=[];const p=this.isTapeOn();r==null&&(r=this.state.activeScope!=null?this.state.activeScope.name:"");const l=this.state.numBytes,u=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let m;const b=Fi(r,this.backendName);let y;if(b!=null)m=()=>{const L=this.backend.numDataIds();y=b.kernelFunc({inputs:t,attrs:i,backend:this.backend});const T=Array.isArray(y)?y:[y];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,L,T);const A=T.map(({dataId:_,shape:N,dtype:C})=>this.makeTensorFromDataId(_,N,C));if(p){let _=this.getTensorsForGradient(r,t,A);if(_==null){a==null&&(a=[]);const N=A.filter((C,F)=>a[F]);_=(o||[]).slice().concat(N)}c=this.saveTensorsForBackwardMode(_)}return A};else{const L=T=>{if(!p)return;c=T.map(A=>this.keep(this.clone(A)))};m=()=>{const T=this.backend.numDataIds();y=this.tidy(()=>e(this.backend,L));const A=Array.isArray(y)?y:[y];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,T,A),A}}let w;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?s=m():(w=this.profiler.profileKernel(r,t,()=>m()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(w),s=w.outputs)}),p&&this.addTapeNode(r,t,s,n,c,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-l,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-u,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(L=>t[L]!=null?t[L].shape:null),outputShapes:s.map(L=>L.shape),kernelTimeMs:w.timeMs,extraInfo:w.extraInfo}),Array.isArray(y)?s:s[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const r=ta(e);if(r!=null){const i=r.inputsToSave||[],o=r.outputsToSave||[];let a;r.saveAllInputs?(f(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(c=>t[c])):a=i.map(c=>t[c]);const s=n.filter((c,p)=>o[p]);return a.concat(s)}return null}makeTensor(e,t,n,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let i=e;n==="string"&&Rt(e[0])&&(i=e.map(s=>wm(s)));const o=r.write(i,t,n),a=new de(t,n,o,this.nextTensorId());if(this.incRef(a,r),n==="string"){const s=this.state.tensorInfo.get(o),c=bm(i);this.state.numBytes+=c-s.bytes,s.bytes=c}return a}makeTensorFromDataId(e,t,n,r){n=n||"float32";const i=new de(t,n,e,this.nextTensorId());return this.incRef(i,r),i}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));const i=new Nn(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}incRef(e,t){const 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++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*gm(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 Nn||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),n=t.refCount;n<=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--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const 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==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,i,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},s=ta(e);s!=null&&(r=s.gradFunc),r!=null&&(a.gradient=c=>(c=c.map((p,l)=>{if(p==null){const u=n[l],m=Pt(u.size,u.dtype);return this.makeTensor(m,u.shape,u.dtype)}return p}),r(c.length>1?c:c[0],i,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Gs(e),n=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const o=this.state.activeScope.track[i];!o.kept&&!n.has(o.id)&&o.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(i=>{!i.kept&&i.scopeId===r.id&&this.track(i)})}gradients(e,t,n,r=!1){if(f(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));f(i instanceof de,()=>"The result y returned by f() must be a tensor.");const o=vy(this.state.activeTape,t,i);if(!r&&o.length===0&&t.length>0)throw new 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",()=>{const a={};a[i.id]=n==null?N0(i.shape):n,Sy(a,o,c=>this.tidy(c),_0);const s=t.map(c=>a[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(const p of c.saved)p.dispose()}),this.state.activeTape=null),{value:i,grads:s}})}customGrad(e){return f(qt(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{f(t.every(i=>i instanceof de),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const r={};return t.forEach((i,o)=>{r[o]=i}),this.runKernelFunc((i,o)=>(n=e(...t,o),f(n.value instanceof de,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),f(qt(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),r,(i,o)=>{const a=n.gradFunc(i,o),s=Array.isArray(a)?a:[a];f(s.length===t.length,()=>"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(...)."),f(s.every(p=>p instanceof de),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const c={};return s.forEach((p,l)=>{c[l]=()=>p}),c})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}async time(e){const t=Cp(),n=await this.backend.time(e);return n.wallMs=Cp()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Ey();for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}$s.nextTensorId=0;$s.nextVariableId=0;function N0(e){const t=Ws(Z(e),"float32");return g.makeTensor(t,e,"float32")}function R0(){const e=cm();if(e._tfengine==null){const t=new Fh(e);e._tfengine=new $s(t)}return fy(e._tfengine.ENV),Ny(()=>e._tfengine),e._tfengine}const g=R0();function _0(e,t){const n={a:e,b:t};return g.runKernelFunc((r,i)=>{const o=r.add(e,t);return i([e,t]),o},n,null,Jn)}const ug={};Oe(ug,{isBrowser:()=>Im,isMobile:()=>E0});function C0(){return typeof navigator!="undefined"&&navigator!=null}function E0(){if(C0()){const e=navigator.userAgent||navigator.vendor||window.opera;return/(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))}return!1}function Im(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const nn=se();nn.registerFlag("DEBUG",()=>!1,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.")});nn.registerFlag("IS_BROWSER",()=>Im());nn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");nn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));nn.registerFlag("PROD",()=>!1);nn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>nn.getBool("DEBUG"));nn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);nn.registerFlag("IS_TEST",()=>!1);function Fe(e,t){let n=e;if(Ie(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Ie(n)&&t!=="string";)r.push(n.length),n=n[0];return Array.isArray(e)&&se().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Oy(e,r,[]),r}function Oy(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ie(e)){f(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}f(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),f(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let i=0;i<e.length;++i)Oy(e[i],r,n.concat(i))}function ky(e,t,n,r){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}function h(e,t,n,r="numeric"){if(e instanceof de)return ky(r,e.dtype,t,n),e;let i=ri(e);if(i!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(i=r),ky(r,i,t,n),e==null||!Ie(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const c=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${c}'`)}const o=Fe(e,i);!Ie(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,s=i!=="string"?Us(e,i):Wt(e,[],a);return g.makeTensor(s,o,i)}function rn(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const i=e;return i.map((o,a)=>h(o,`${t}[${a}]`,n),r)}function d(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));const i=(...o)=>{g.startScope(n);try{const a=r(...o);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),g.endScope(a),a}catch(a){throw g.endScope(null),a}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}function O0(e){const t=h(e,"x","abs"),n={x:t};return g.runKernelFunc((r,i)=>(i([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)),n,null,Mi)}const _e=d({abs_:O0});function k0(e){const t=h(e,"x","acos"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.acos(t);return i([t]),o},n,null,Ui)}const Mu=d({acos_:k0});function D0(e){const t=h(e,"x","acosh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.acosh(t);return i([t]),o},n,null,Wi)}const Fu=d({acosh_:D0});function F0(e,t){let n=h(e,"a","add"),r=h(t,"b","add");[n,r]=V(n,r);const i=(a,s)=>{const c=a.add(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,Jn)}const O=d({add_:F0});function M0(e){f(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),f(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>h(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!Le(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=(o,a)=>{const s=o.addN(t);return a(t),s},i=t;return g.runKernelFunc(r,i,null,qi)}const Du=d({addN_:M0});function Am(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Dy(e,t,n){const r=e.length+t.length,i=[];let o=0,a=0;for(let s=0;s<r;s++)n.indexOf(s)===-1?i.push(e[o++]):i.push(t[a++]);return i}function Nm(e,t){const n=[],r=e.length;for(let o=0;o<r;o++)t.indexOf(o)===-1&&n.push(e[o]);const i=t.map(o=>e[o]);return[n,i]}function fe(e,t){const n=t.map(r=>1);return Dy(e,n,t)}function U0(e,t,n){f(Am(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function he(e,t){if(Am(e,t))return null;const n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function pr(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function Ee(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function W0(e,t){const n=h(e,"x","reshape",null);t=um(t,n.size),f(n.size===Z(t),()=>"new shape and old shape must have the same number of elements.");const r={x:n},i={shape:t},o=(a,s)=>(s([n]),a.reshape(n,t));return g.runKernelFunc(o,r,null,$o,i)}const x=d({reshape_:W0});function q0(e,t){const n=h(e,"x","transpose");if(t==null&&(t=n.shape.map((o,a)=>a).reverse()),f(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(o=>{f(o>=0&&o<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();const r={x:n},i={perm:t};return g.runKernelFunc(o=>o.transpose(n,t),r,null,fs,i)}const X=d({transpose_:q0});function B0(e,t=null,n=!1){let r=h(e,"x","all","bool");const i=s=>{const c=z(t,r.shape);let p=c;const l=he(p,r.rank);l!=null&&(r=X(r,l),p=Ee(p.length,r.rank));const u=s.all(r,p);if(n){const m=fe(u.shape,c);return x(u,m)}return u},o={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(i,o,null,Wu,a)}const ku=d({all_:B0});function P0(e,t=null,n=!1){let r=h(e,"x","any","bool");const i=s=>{const c=z(t,r.shape);let p=c;const l=he(p,r.rank);l!=null&&(r=X(r,l),p=Ee(p.length,r.rank));const u=s.any(r,p);if(n){const m=fe(u.shape,c);return x(u,m)}return u},o={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(i,o,null,qu,a)}const Ou=d({any_:P0});function j0(e,t=0){let n=h(e,"x","argMax");const r=(a,s)=>{s([n]);let c=z(t,n.shape);const p=he(c,n.rank);return p!=null&&(n=X(n,p),c=Ee(c.length,n.rank)),a.argMax(n,c[0])},i={x:n},o={axis:t};return g.runKernelFunc(r,i,null,Bi,o)}const Eu=d({argMax_:j0});function G0(e,t=0){let n=h(e,"x","argMin");const r=(a,s)=>{s([n]),t==null&&(t=0);let c=z(t,n.shape);const p=he(c,n.rank);return p!=null&&(n=X(n,p),c=Ee(c.length,n.rank)),a.argMin(n,c[0])},i={x:n},o={axis:t};return g.runKernelFunc(r,i,null,Pi,o)}const Cu=d({argMin_:G0});function $0(e){const t=h(e,"x","asin"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.asin(t);return i([t]),o},n,null,ji)}const Ru=d({asin_:$0});function H0(e){const t=h(e,"x","asinh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.asinh(t);return i([t]),o},n,null,Gi)}const _u=d({asinh_:H0});function Y0(e){const t=h(e,"x","atan"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.atan(t);return i([t]),o},n,null,$i)}const Nu=d({atan_:Y0});function z0(e,t){let n=h(e,"a","atan2"),r=h(t,"b","atan2");[n,r]=V(n,r);const i=(a,s)=>{const c=a.atan2(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,Yi)}const Au=d({atan2_:z0});function V0(e){const t=h(e,"x","atanh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.atanh(t);return i([t]),o},n,null,Hi)}const Iu=d({atanh_:V0});function K0(e,t){const n=h(e,"x","cast");if(!mm(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const r={x:n},i={dtype:t};return g.runKernelFunc(o=>o.cast(n,t),r,null,Xn,i)}const R=d({cast_:K0});function J0(e,t,n,r,i="NHWC",o){const a=e[3],s=[...t,a],c=Sn(i);return We(e,s,n,o,r,null,null,c)}function Ct(e,t,n,r,i,o,a="channelsLast"){const[s,c]=kp(t);let p;if(a==="channelsLast")p=[s,c,e[3],e[3]];else if(a==="channelsFirst")p=[s,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return We(e,p,n,r,i,o,!1,a)}function on(e,t,n,r,i,o,a="NDHWC"){const[s,c,p]=_m(t);let l,u;if(a==="NDHWC")u="channelsLast",l=[s,c,p,e[4],e[4]];else if(a==="NCDHW")u="channelsFirst",l=[s,c,p,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return Tn(e,l,n,r,i,!1,u,o)}function We(e,t,n,r,i,o,a=!1,s="channelsLast"){let[c,p,l,u]=[-1,-1,-1,-1];if(s==="channelsLast")[c,p,l,u]=e;else if(s==="channelsFirst")[c,u,p,l]=e;else throw new Error(`Unknown dataFormat ${s}`);const[m,b,,y]=t,[w,L]=kp(n),[T,A]=kp(r),_=si(m,T),N=si(b,A),{padInfo:C,outHeight:F,outWidth:E}=X0(i,p,l,w,L,_,N,o,s),B=a?y*u:y;let q;return s==="channelsFirst"?q=[c,B,F,E]:s==="channelsLast"&&(q=[c,F,E,B]),{batchSize:c,dataFormat:s,inHeight:p,inWidth:l,inChannels:u,outHeight:F,outWidth:E,outChannels:B,padInfo:C,strideHeight:w,strideWidth:L,filterHeight:m,filterWidth:b,effectiveFilterHeight:_,effectiveFilterWidth:N,dilationHeight:T,dilationWidth:A,inShape:e,outShape:q,filterShape:t}}function Tn(e,t,n,r,i,o=!1,a="channelsLast",s){let[c,p,l,u,m]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[c,p,l,u,m]=e;else if(a==="channelsFirst")[c,m,p,l,u]=e;else throw new Error(`Unknown dataFormat ${a}`);const[b,y,w,,L]=t,[T,A,_]=_m(n),[N,C,F]=_m(r),E=si(b,N),B=si(y,C),q=si(w,F),{padInfo:P,outDepth:te,outHeight:ne,outWidth:pe}=Z0(i,p,l,u,T,A,_,E,B,q,s),Se=o?L*m:L;let qe;return a==="channelsFirst"?qe=[c,Se,te,ne,pe]:a==="channelsLast"&&(qe=[c,te,ne,pe,Se]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:l,inWidth:u,inChannels:m,outDepth:te,outHeight:ne,outWidth:pe,outChannels:Se,padInfo:P,strideDepth:T,strideHeight:A,strideWidth:_,filterDepth:b,filterHeight:y,filterWidth:w,effectiveFilterDepth:E,effectiveFilterHeight:B,effectiveFilterWidth:q,dilationDepth:N,dilationHeight:C,dilationWidth:F,inShape:e,outShape:qe,filterShape:t}}function Q0(e,t,n,r,i){r==null&&(r=Rm(e,t,n));const o=e[0],a=e[1],s=lr((o-t+2*r)/n+1,i);f(J(s),()=>`The output # of rows (${s}) must be an integer. Change the stride and/or zero pad parameters`);const c=lr((a-t+2*r)/n+1,i);return f(J(c),()=>`The output # of columns (${c}) must be an integer. Change the stride and/or zero pad parameters`),[s,c]}function eR(e,t,n,r,i,o){i==null&&(i=Rm(e,t,r));const a=e[0],s=e[1],c=e[2],p=lr((a-t+2*i)/r+1,o);f(J(p),()=>`The output # of depths (${p}) must be an integer. Change the stride and/or zero pad parameters`);const l=lr((s-t+2*i)/r+1,o);f(J(l),()=>`The output # of rows (${l}) must be an integer. Change the stride and/or zero pad parameters`);const u=lr((c-t+2*i)/r+1,o);return f(J(u),()=>`The output # of columns (${u}) must be an integer. Change the stride and/or zero pad parameters`),[p,l,u,n]}function Rm(e,t,n,r=1){const i=si(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)}function kp(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function _m(e){return typeof e=="number"?[e,e,e]:e}function si(e,t){return t<=1?e:e+(e-1)*(t-1)}function X0(e,t,n,r,i,o,a,s,c){let p,l,u;if(typeof e=="number"){const m=e===0?"VALID":"NUMBER";p={top:e,bottom:e,left:e,right:e,type:m};const b=Q0([t,n],o,r,e,s);l=b[0],u=b[1]}else if(e==="same"){l=Math.ceil(t/r),u=Math.ceil(n/i);const m=Math.max(0,(l-1)*r+o-t),b=Math.max(0,(u-1)*i+a-n),y=Math.floor(m/2),w=m-y,L=Math.floor(b/2),T=b-L;p={top:y,bottom:w,left:L,right:T,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-o+1)/r),u=Math.ceil((n-a+1)/i);else if(typeof e=="object"){const m=c==="channelsLast"?e[1][0]:e[2][0],b=c==="channelsLast"?e[1][1]:e[2][1],y=c==="channelsLast"?e[2][0]:e[3][0],w=c==="channelsLast"?e[2][1]:e[3][1],L=m===0&&b===0&&y===0&&w===0?"VALID":"EXPLICIT";p={top:m,bottom:b,left:y,right:w,type:L},l=lr((t-o+m+b)/r+1,s),u=lr((n-a+y+w)/i+1,s)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:l,outWidth:u}}function Z0(e,t,n,r,i,o,a,s,c,p,l){let u,m,b,y;if(typeof e=="number"){const w=e===0?"VALID":"NUMBER";u={top:e,bottom:e,left:e,right:e,front:e,back:e,type:w};const L=eR([t,n,r,1],s,1,i,e,l);m=L[0],b=L[1],y=L[2]}else if(e==="same"){m=Math.ceil(t/i),b=Math.ceil(n/o),y=Math.ceil(r/a);const w=(m-1)*i+s-t,L=(b-1)*o+c-n,T=(y-1)*a+p-r,A=Math.floor(w/2),_=w-A,N=Math.floor(L/2),C=L-N,F=Math.floor(T/2),E=T-F;u={top:N,bottom:C,left:F,right:E,front:A,back:_,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((t-s+1)/i),b=Math.ceil((n-c+1)/o),y=Math.ceil((r-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outDepth:m,outHeight:b,outWidth:y}}function lr(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 new Error(`Unknown roundingMode ${t}`)}}function ut(e){const[t,n,r]=kp(e);return t===1&&n===1&&r===1}function ae(e,t){return ut(e)||ut(t)}function Sn(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function tR(e,t,n,r,i){const o=h(e,"x","avgPool","float32"),a=1;f(ae(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let s=o,c=!1;o.rank===3&&(c=!0,s=x(o,[1,o.shape[0],o.shape[1],o.shape[2]])),f(s.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${s.rank}.`),i!=null&&f(J(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const p=(b,y)=>{const w=Ct(s.shape,t,n,1,r,i);return y([s]),w.filterWidth===1&&w.filterHeight===1&&Le(w.inShape,w.outShape)?s.clone():b.avgPool(s,w)},l={x:s},u={filterSize:t,strides:n,pad:r,dimRoundingMode:i};let m=g.runKernelFunc(p,l,null,zi,u);return m=R(m,o.dtype),c?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const Di=d({avgPool_:tR});function uS(){se().set("PROD",!0)}function hS(){se().set("DEBUG",!0)}function dS(){se().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function ge(e){se().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Ry(ge);function mS(){g.disposeVariables()}function fS(){return g}function gS(){return g.memory()}function bS(e){return g.profile(e)}function ce(e,t){return g.tidy(e,t)}function be(e){const t=Gs(e);t.forEach(n=>n.dispose())}function Dh(e){return g.keep(e)}function wS(e){return g.time(e)}function yS(e){return g.setBackend(e)}function xS(){return g.ready()}function LS(){return g.backendName}function vS(e){g.removeBackend(e)}function SS(e){return g.findBackend(e)}function TS(e){return g.findBackendFactory(e)}function IS(e,t,n=1){return g.registerBackend(e,t,n)}function AS(){return g.backend}function NS(e,t){se().setPlatform(e,t)}function nR(e,t,n,r,i,o="NDHWC",a){a==null?a=[1,1,1]:ge("dilations is deprecated, this field will be gone in v3.0.0.");const s=h(e,"x","avgPool3d","float32");let c=s,p=!1;s.rank===4&&(p=!0,c=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${c.rank}.`),f(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),f(ae(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&f(J(r),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const l=(y,w)=>{a==null&&(a=[1,1,1]);const L=on(c.shape,t,n,a,r,i,o);return w([c]),y.avgPool3d(c,L)},u={x:c},m={filterSize:t,strides:n,pad:r,dimRoundingMode:i,dataFormat:o,dilations:a};let b=g.runKernelFunc(l,u,null,Vi,m);return b=R(b,c.dtype),p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Tu=d({avgPool3d_:nR});function Cm(e,t){const n=e[0].length;e.forEach((i,o)=>{f(i.length===n,()=>`Error in concat${n}D: rank of tensors[${o}] must be the same as the rank of the rest (${n})`)}),f(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((i,o)=>{for(let a=0;a<n;a++)f(a===t||i[a]===r[a],()=>`Error in concat${n}D: Shape of tensors[${o}] (${i}) does not match the shape of the rest (${r}) along the non-concatenated axis ${o}.`)})}function Em(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}function ze(e,t,n,r){if(r==null&&(r=ri(e)),r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Ie(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new 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){qs(t);const i=Z(t),o=Z(n);f(i===o,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${o}`);for(let a=0;a<n.length;++a){const s=n[a],c=a===n.length-1?s!==Z(t.slice(a)):!0;f(n[a]===t[a]||!c,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Ie(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=r!=="string"?Us(e,r):Wt(e,[],!0),g.makeTensor(e,t,r)}function Qe(e,t,n){const r=Fe(e,n);return ze(e,t,r,n)}function rR(e,t=0){f(e.length>=1,()=>"Pass at least one tensor to concat");let n=rn(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(p=>{if(p.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${p.dtype}. `)});const r=z(t,n[0].shape)[0],i=Em(n.map(p=>p.shape),r);if(Z(i)===0)return Qe([],i);if(n=n.filter(p=>p.size>0),n.length===1)return n[0];const o=n.map(p=>p.shape);Cm(o,r);const a=(p,l)=>{const u=p.concat(n,r);return l(n),u},s=n,c={axis:t};return g.runKernelFunc(a,s,null,eo,c)}const re=d({concat_:rR});function iR(e,t,n=!1,r=!1){let i=h(e,"a","matMul"),o=h(t,"b","matMul");[i,o]=V(i,o),f(i.rank>=2&&o.rank>=2&&i.rank===o.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${i.rank} and ${o.rank}.`);const a=n?i.shape[i.rank-2]:i.shape[i.rank-1],s=r?o.shape[o.rank-1]:o.shape[o.rank-2],c=n?i.shape[i.rank-1]:i.shape[i.rank-2],p=r?o.shape[o.rank-2]:o.shape[o.rank-1],l=i.shape.slice(0,-2),u=o.shape.slice(0,-2),m=Z(l),b=Z(u);f(Le(l,u),()=>`Error in matMul: outer dimensions (${l}) and (${u}) of Tensors with shapes ${i.shape} and ${o.shape} must match.`),f(a===s,()=>`Error in matMul: inner shapes (${a}) and (${s}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${n} and transposeB=${r} must match.`);const y=i.shape.slice(0,-2).concat([c,p]),w=n?x(i,[m,a,c]):x(i,[m,c,a]),L=r?x(o,[b,p,s]):x(o,[b,s,p]),T=(C,F)=>(F([w,L]),C.batchMatMul(w,L,n,r)),A={a:w,b:L},_={transposeA:n,transposeB:r},N=g.runKernelFunc(T,A,null,Ki,_);return x(N,y)}const K=d({matMul_:iR});function oR(e,t){let n=h(e,"a","mul"),r=h(t,"b","mul");[n,r]=V(n,r);const i=(a,s)=>{const c=a.multiply(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,Fo)}const v=d({mul_:oR});function sR(e){const t=h(e,"x","sigmoid"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.sigmoid(t);return i([o]),o},n,null,rs)}const St=d({sigmoid_:sR});const kf={};Oe(kf,{assertParamsValid:()=>Om,computeFlatOffset:()=>cR,computeOutShape:()=>km,isSliceContinous:()=>aR,maskToAxes:()=>Hs,parseSliceParams:()=>Ys,startForAxis:()=>Wm,startIndicesWithElidedDims:()=>Fm,stopForAxis:()=>qm,stopIndicesWithElidedDims:()=>Mm,stridesForAxis:()=>Um,stridesWithElidedDims:()=>Dm});function Om(e,t,n){f(e.rank===t.length,()=>`Error in slice${e.rank}D: Length of begin ${t} must match the rank of the array (${e.rank}).`),f(e.rank===n.length,()=>`Error in slice${e.rank}D: Length of size ${n} must match the rank of the array (${e.rank}).`);for(let r=0;r<e.rank;++r)f(t[r]+n[r]<=e.shape[r],()=>`Error in slice${e.rank}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Hs(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function km(e,t,n){const r=[];for(let i=0;i<e.length;i++)r[i]=Math.ceil((t[i]-e[i])/n[i]);return r}function Dm(e,t,n,r){const i=[...e];for(let o=i.length;o<r.length;o++)i.push(1);for(let o=0;o<n;o++)o===0?i[t]=1:(i.splice(t,0,1),i.pop());return i}function Fy(e,t,n){return n<=e?n:n-(t-1)}function My(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function Fm(e,t,n,r,i){const o=[...i],a=My(n,t);for(let s=0;s<o.length;s++)if(a.indexOf(s)>-1)o[s]=0;else{const c=Fy(t,n,s);let p=r[c];e&1<<c&&(p=0),o[s]=p}return o}function Mm(e,t,n,r,i){const o=[...i],a=My(n,t);for(let s=0;s<o.length;s++)if(a.indexOf(s)>-1)o[s]=Number.MAX_SAFE_INTEGER;else{const c=Fy(t,n,s);let p=r[c];e&1<<c&&(p=Number.MAX_SAFE_INTEGER),o[s]=p}for(let s=0;s<o.length;s++){const c=i[s];o[s]<0&&(o[s]+=c),o[s]=ti(0,o[s],i[s])}return o}function Um(e,t,n){let r=e[t];return(n&1<<t||r==null)&&(r=1),r}function Wm(e,t,n,r,i,o){let a=t[i];const s=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(s>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const c=r[i];return a<0&&(a+=c),a=ti(0,a,c-1),a}function qm(e,t,n,r,i,o){let a=t[i];const s=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(s>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const c=r[i];return a<0&&(a+=c),s>0?a=ti(0,a,c):a=ti(-1,a,c-1),a}function aR(e,t,n){let r=n.length;for(let i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(let i=r+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function cR(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function Ys(e,t,n){let r;typeof t=="number"?r=[t,...new Array(e.rank-1).fill(0)]:t.length<e.rank?r=t.concat(new Array(e.rank-t.length).fill(0)):r=t.slice(),r.forEach(o=>{f(o!==-1,()=>"slice() does not support negative begin indexing.")});let i;return n==null?i=new Array(e.rank).fill(-1):typeof n=="number"?i=[n,...new Array(e.rank-1).fill(-1)]:n.length<e.rank?i=n.concat(new Array(e.rank-n.length).fill(-1)):i=n,i=i.map((o,a)=>o>=0?o:(f(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${a}.`),e.shape[a]-r[a])),[r,i]}function pR(e,t,n){const r=h(e,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");const[i,o]=Ys(r,t,n);Om(r,i,o);const a=(p,l)=>(l([r]),p.slice(r,i,o)),s={x:r},c={begin:t,size:n};return g.runKernelFunc(a,s,null,Qo,c)}const Y=d({slice_:pR});function lR(e){const t=h(e,"x","tanh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.tanh(t);return i([o]),o},n,null,ds)}const xr=d({tanh_:lR});function uR(e,t,n,r,i,o){const a=h(e,"forgetBias","basicLSTMCell"),s=h(t,"lstmKernel","basicLSTMCell"),c=h(n,"lstmBias","basicLSTMCell"),p=h(r,"data","basicLSTMCell"),l=h(i,"c","basicLSTMCell"),u=h(o,"h","basicLSTMCell"),m=re([p,u],1),b=K(m,s),y=O(b,c),w=y.shape[0],L=y.shape[1]/4,T=[w,L],A=Y(y,[0,0],T),_=Y(y,[0,L],T),N=Y(y,[0,L*2],T),C=Y(y,[0,L*3],T),F=O(v(St(A),xr(_)),v(l,St(O(a,N)))),E=v(xr(F),St(C));return[F,E]}const Su=d({basicLSTMCell_:uR});function hR(e,t,n){const r=h(e,"x","batchToSpaceND"),i=t.reduce((c,p)=>c*p);f(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),f(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),f(r.shape[0]%i===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=c=>c.batchToSpaceND(r,t,n),a={x:r},s={blockShape:t,crops:n};return g.runKernelFunc(o,a,null,Ji,s)}const Kn=d({batchToSpaceND_:hR});function Uy(e){let t;return e.rank===0||e.rank===1?t=x(e,[1,1,1,e.size]):e.rank===2?t=x(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function dR(e,t,n,r,i,o){o==null&&(o=.001);const a=h(e,"x","batchNorm"),s=h(t,"mean","batchNorm"),c=h(n,"variance","batchNorm");let p;i!=null&&(p=h(i,"scale","batchNorm"));let l;r!=null&&(l=h(r,"offset","batchNorm")),f(s.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),f(l==null||s.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),f(p==null||s.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const u=Uy(a),m=(L,T)=>(T([u,s,c,p]),L.batchNorm(u,Dp(s),Dp(c),Dp(l),Dp(p),o)),b={x:u,scale:p,offset:l,mean:s,variance:c},y={varianceEpsilon:o},w=g.runKernelFunc(m,b,null,bo,y);return x(w,a.shape)}function Dp(e){return e==null?null:e.rank===0?x(e,[e.size]):e.rank===1?e:e.rank===2?x(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?x(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Jt=d({batchNorm_:dR});function mR(e,t,n,r,i,o){const a=h(e,"x","batchNorm"),s=h(t,"mean","batchNorm"),c=h(n,"variance","batchNorm");let p;i!=null&&(p=h(i,"scale","batchNorm"));let l;return r!=null&&(l=h(r,"offset","batchNorm")),f(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),f(s.rank===2||s.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${s.rank}.`),f(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),Jt(a,s,c,l,p,o)}const vu=d({batchNorm2d_:mR});function fR(e,t,n,r,i,o){const a=h(e,"x","batchNorm"),s=h(t,"mean","batchNorm"),c=h(n,"variance","batchNorm");let p;i!=null&&(p=h(i,"scale","batchNorm"));let l;return r!=null&&(l=h(r,"offset","batchNorm")),f(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),f(s.rank===3||s.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${s.rank}.`),f(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),Jt(a,s,c,l,p,o)}const Lu=d({batchNorm3d_:fR});function gR(e,t,n,r,i,o){const a=h(e,"x","batchNorm"),s=h(t,"mean","batchNorm"),c=h(n,"variance","batchNorm");let p;i!=null&&(p=h(i,"scale","batchNorm"));let l;return r!=null&&(l=h(r,"offset","batchNorm")),f(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),f(s.rank===4||s.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${s.rank}.`),f(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${l.rank}.`),Jt(a,s,c,l,p,o)}const xu=d({batchNorm4d_:gR});function bR(e){const t=h(e,"x","clone",null),n=()=>g.makeTensorFromDataId(t.dataId,t.shape,t.dtype),r={x:t};return g.runKernelFunc(n,r,null,xo)}const At=d({clone_:bR});function wR(e,t){let n=h(e,"broadcastTo","x");const r=n.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const l=n.shape.slice();for(;l.length<t.length;)l.unshift(1);n=x(n,l)}const i=n.shape,o=Array.from(t);for(let l=t.length-1;l>=0;l--)if(i[l]===t[l])o[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);const a=o.map((l,u)=>l>1?u:-1).filter(l=>l>=0);if(a.length===0)return At(n);const s=l=>l.tile(n,o),c={x:n},p={shape:t,inputShape:i};return g.runKernelFunc(s,c,null,Xi,p)}const Ir=d({broadcastTo_:wR});function ke(e,t="float32",n){return t=t||"float32",qs(e),new yr(e,t,n)}function yR(e){const t=h(e,"x","ceil"),n={x:t};return g.runKernelFunc(r=>r.ceil(t),n,null,Zi)}const yu=d({ceil_:yR});function xR(e,t,n){const r=h(e,"x","clipByValue");f(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const i={x:r},o={clipValueMin:t,clipValueMax:n};return g.runKernelFunc((a,s)=>{const c=a.clip(r,t,n);return s([r]),c},i,null,Qi,o)}const wu=d({clipByValue_:xR});function LR(e,t){const n=h(e,"real","complex"),r=h(t,"imag","complex");$(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const i=a=>a.complex(n,r),o={real:n,imag:r};return g.runKernelFunc(i,o,null,ju)}const Ge=d({complex_:LR});function vR(e){return re(e,0)}const bu=d({concat1d_:vR});function SR(e,t){return re(e,t)}const gu=d({concat2d_:SR});function TR(e,t){return re(e,t)}const fu=d({concat3d_:TR});function IR(e,t){return re(e,t)}const mu=d({concat4d_:IR});function AR(e,t,n,r,i="NHWC",o=[1,1],a){const s=h(e,"x","conv2d"),c=h(t,"filter","conv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),a!=null&&f(J(r),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const u=i==="NHWC"?p.shape[3]:p.shape[1];f(u===c.shape[2],()=>`Error in conv2d: depth of input (${u}) must match input depth for filter ${c.shape[2]}.`),f(ae(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const m=(L,T)=>{const A=Sn(i),_=We(p.shape,c.shape,n,o,r,a,!1,A),N=L.conv2d(p,c,_);return T([p,c]),N},b={x:p,filter:c},y={strides:n,pad:r,dataFormat:i,dilations:o,dimRoundingMode:a},w=g.runKernelFunc(m,b,null,to,y);return l?x(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const It=d({conv2d_:AR});function NR(e,t,n,r,i="NWC",o=1,a){const s=h(e,"x","conv1d"),c=h(t,"filter","conv1d");let p=s,l=!1;s.rank===2&&(l=!0,p=x(s,[1,s.shape[0],s.shape[1]])),f(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),f(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),a!=null&&f(J(r),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(p.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${c.shape[1]}.`),f(ae(n,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`),f(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const u=x(c,[1,c.shape[0],c.shape[1],c.shape[2]]),m=x(p,[p.shape[0],1,p.shape[1],p.shape[2]]),b=[1,n],y=[1,o],w="NHWC",L=It(m,u,b,r,w,y,a);return l?x(L,[L.shape[2],L.shape[3]]):x(L,[L.shape[0],L.shape[2],L.shape[3]])}const du=d({conv1d_:NR});function _R(e,t,n,r,i,o="NHWC",a){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,c=t,p=!1;t.rank===3&&(p=!0,c=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]),s=[1,e[0],e[1],e[2]]),f(s.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${s.length}.`),f(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),f(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const l=o==="NHWC"?s[3]:s[1],u=o==="NHWC"?c.shape[3]:c.shape[1];f(l===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[2]}.`),f(u===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[3]}.`),a!=null&&f(J(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const m=(L,T)=>{const A=1,_=Sn(o),N=We(s,n.shape,r,A,i,a,!1,_),C=L.conv2dDerInput(c,n,N);return T([c,n]),C},b={dy:c,filter:n},y={strides:r,pad:i,dataFormat:o,dimRoundingMode:a,inputShape:s},w=g.runKernelFunc(m,b,null,no,y);return p?x(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const ai=d({conv2DBackpropInput_:_R});function RR(e,t,n,r,i,o){const a=h(e,"x","conv2dTranspose"),s=h(t,"filter","conv2dTranspose");return ai(n,a,s,r,i,"NHWC",o)}const hu=d({conv2dTranspose_:RR});function CR(e,t,n,r,i="NDHWC",o=[1,1,1]){const a=h(e,"x","conv3d"),s=h(t,"filter","conv3d");let c=a,p=!1;a.rank===4&&(p=!0,c=x(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),f(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),f(s.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${s.rank}.`),f(c.shape[4]===s.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${s.shape[3]}.`),f(ae(n,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),f(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const l=(y,w)=>{const L=Tn(c.shape,s.shape,n,o,r),T=y.conv3d(c,s,L);return w([c,s]),T},u={x:c,filter:s},m={strides:n,pad:r,dataFormat:i,dilations:o},b=g.runKernelFunc(l,u,null,ro,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const uu=d({conv3d_:CR});function ER(e,t,n,r,i){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,a=t,s=!1;t.rank===4&&(s=!0,a=x(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),o=[1,e[0],e[1],e[2],e[3]]);const c=o[4],p=a.shape[4];f(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),f(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),f(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),f(c===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[3]}.`),f(p===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`);const l=y=>{const w=1,L=Tn(o,n.shape,r,w,i);return y.conv3dDerInput(a,n,L)},u={dy:a},m={pad:i},b=g.runKernelFunc(l,u,null,Hu,m);return s?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Fp=d({conv3DBackpropInput_:ER});function OR(e,t,n,r,i){const o=h(e,"x","conv3dTranspose"),a=h(t,"filter","conv3dTranspose");return Fp(n,o,a,r,i)}const lu=d({conv3dTranspose_:OR});function kR(e){const t=h(e,"x","cos"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.cos(t);return i([t]),o},n,null,io)}const Vn=d({cos_:kR});function DR(e){const t=h(e,"x","cosh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.cosh(t);return i([t]),o},n,null,oo)}const ki=d({cosh_:DR});function FR(e,t=0,n=!1,r=!1){const i=h(e,"x","cumsum"),o=(c,p)=>{const l=he([t],i.rank);let u=i;l!=null&&(u=X(i,l));const m=Ee(1,i.rank)[0];let b=c.cumsum(u,m,n,r);if(p([i]),l!=null){const y=pr(l);b=X(b,y)}return b},a={x:i},s={axis:t,exclusive:n,reverse:r};return g.runKernelFunc(o,a,null,so,s)}const Oi=d({cumsum_:FR});function MR(e,t,n="NHWC"){const r=h(e,"x","depthToSpace"),i=n==="NHWC"?r.shape[1]:r.shape[2],o=n==="NHWC"?r.shape[2]:r.shape[3],a=n==="NHWC"?r.shape[3]:r.shape[1];f(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${i} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),f(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${o} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),f(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${r.shape}`);const s=l=>l.depthToSpace(r,t,n),c={x:r},p={blockSize:t,dataFormat:n};return g.runKernelFunc(s,c,null,zu,p)}const pu=d({depthToSpace_:MR});function UR(e,t,n,r,i="NHWC",o=[1,1],a){const s=h(e,"x","depthwiseConv2d"),c=h(t,"filter","depthwiseConv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),a!=null&&f(J(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const u=(w,L)=>{o==null&&(o=[1,1]),f(ae(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const T=We(p.shape,c.shape,n,o,r,a,!0),A=w.depthwiseConv2D(p,c,T);return L([p,c]),A},m={x:p,filter:c},b={strides:n,pad:r,dataFormat:i,dilations:o,dimRoundingMode:a},y=g.runKernelFunc(u,m,null,ao,b);return l?x(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const zn=d({depthwiseConv2d_:UR});function WR(e){const t=h(e,"x","diag"),n=i=>{const o=x(t,[t.size]),a=i.diag(o),s=[...e.shape,...e.shape];return x(a,s)},r={x:t};return g.runKernelFunc(n,r,null,Ju)}const cu=d({diag_:WR});function qR(e,t,n,r,i=[1,1],o="NHWC"){const a=h(e,"x","dilation2d"),s=h(t,"filter","dilation2d");f(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),f(s.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${s.rank}.`),f(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let c=a,p=!1;a.rank===3&&(c=x(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const l={x:c,filter:s},u={strides:n,pad:r,dilations:i},m=g.runKernel(co,l,u);return p?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const au=d({dilation2d_:qR});function BR(e,t){let n=h(e,"a","floorDiv"),r=h(t,"b","floorDiv");[n,r]=V(n,r);const i=(a,s)=>{const c=a.floorDiv(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,go)}const Ri=d({floorDiv_:BR});function PR(e,t){let n=h(e,"a","div"),r=h(t,"b","div");if([n,r]=V(n,r),n.dtype==="int32"&&r.dtype==="int32")return Ri(n,r);const i=(s,c)=>{const p=s.realDivide(n,r);return c([n,r]),p},o={a:n,b:r},a={};return g.runKernelFunc(i,o,null,po,a)}const M=d({div_:PR});function jR(e,t){const n=e.length,r=[];for(let i=0;i<n;i++){const o=n-1-i,a=e[o]||1,s=t[t.length-1-i]||1;s>1&&a===1&&r.unshift(o)}return r}function ie(e,t){const n=[];for(let r=0;r<t.length;r++){const i=e[e.length-r-1],o=t.length-r-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function H(e,t){const n=[],r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const s=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(s)}else n.unshift(o)}return n}function GR(e,t){let n=h(e,"a","equal"),r=h(t,"b","equal");[n,r]=V(n,r),H(n.shape,r.shape);const i=a=>a.equal(n,r),o={a:n,b:r};return g.runKernelFunc(i,o,null,eh)}const Kt=d({equal_:GR});function $R(e,t,n){const r=h(t,"a","where"),i=h(n,"b","where"),o=h(e,"condition","where","bool"),a=H(r.shape,i.shape),s=Ir(r,a),c=Ir(i,a);o.rank===1&&f(o.shape[0]===r.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&$(o.shape,c.shape,"Error in where: ");const p=(u,m)=>{const b=u.select(o,s,c);return m([o]),b},l={condition:o,t:s,e:c};return g.runKernelFunc(p,l,null,Xo)}const Ae=d({where_:$R});function HR(e){const t=h(e,"x","zerosLike"),n={x:t};return g.runKernelFunc(r=>r.zerosLike(t),n,null,ws)}const W=d({zerosLike_:HR});function YR(e,t){let n=h(e,"a","div"),r=h(t,"b","div");[n,r]=V(n,r);const i=M(n,r),o=W(i),a=Kt(r,o);return Ae(a,o,i)}const su=d({divNoNan_:YR});function zR(e,t){const n=h(e,"t1","dot"),r=h(t,"t2","dot");f((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=r.rank===1?r.size:r.shape[0];if(f(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank===1&&r.rank===1){const a=x(n,[1,-1]),s=x(r,[-1,1]),c=K(a,s);return x(c,[])}else if(n.rank===1&&r.rank===2){const a=x(n,[1,-1]),s=x(r,[r.shape[0],r.shape[1]]),c=K(a,s);return x(c,[c.size])}else if(n.rank===2&&r.rank===1){const a=x(r,[-1,1]),s=K(n,a);return x(s,[s.size])}else{const a=x(r,[r.shape[0],r.shape[1]]),s=K(n,a);return s}}const ou=d({dot_:zR});function VR(e){const t=h(e,"x","elu"),n=(i,o)=>{const a=i.elu(t);return o([a]),a},r={x:t};return g.runKernelFunc(n,r,null,lo)}const Ei=d({elu_:VR});function KR(e){let t=h(e,"x","erf");f(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=R(t,"float32"));const n={x:t};return g.runKernelFunc((r,i)=>{const o=r.erf(t);return i([t]),o},n,null,uo)}const iu=d({erf_:KR});function JR(e){const t=h(e,"x","exp"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.exp(t);return i([o]),o},n,null,ho)}const Ne=d({exp_:JR});function XR(e,t=0){const n=null,r=h(e,"x","expandDims",n);f(t<=r.rank,()=>"Axis must be <= rank of the tensor");const i=r.shape.slice();return t<0&&(f(-(r.rank+1)<=t,()=>`Axis must be in the interval [${-(r.rank+1)}, ${r.rank}]`),t=r.rank+t+1),i.splice(t,0,1),x(r,i)}const Ke=d({expandDims_:XR});function ZR(e){const t=h(e,"x","expm1"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.expm1(t);return i([t]),o},n,null,mo)}const ru=d({expm1_:ZR});function QR(e,t){const n=null,r=h(e,"x","tile",n);f(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);const i=(c,p)=>{const l=c.tile(r,t);return p([r]),l},o=[r],a={x:r},s={reps:t};return g.runKernelFunc(i,a,null,ms,s,o)}const Ht=d({tile_:QR});function e1(e,t,n,r="float32"){t==null&&(t=e);const i=ke([e,t],r),o=e<=t?e:t;for(let s=0;s<o;++s)i.set(1,s,s);const a=x(i.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Ht(Ke(a,0),[n[0],1,1]);if(n.length===2)return Ht(Ke(Ke(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Ht(Ke(Ke(Ke(a,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}const Ci=d({eye_:e1});function t1(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],i=e.size/r,o=e.as2D(i,r),a=n.fft(o);return a.reshape(e.shape)},t,null,th)}const Yn=d({fft_:t1});function Hn(e,t,n){const r={shape:e,value:t,dtype:n};return g.runKernelFunc(i=>i.fill(e,t,n),{},null,nh,r)}function n1(e){const t=h(e,"x","floor"),n={x:t};return g.runKernelFunc(r=>r.floor(t),n,null,fo)}const $n=d({floor_:n1});const Mp=30;function r1(e){return e<=Mp?e:ii(e,Math.floor(Math.sqrt(e)))}const Wy={};Oe(Wy,{collectGatherOpShapeInfo:()=>Bm,computeOutShape:()=>o1,segOpComputeOptimalWindowSize:()=>i1});function i1(e,t){let n=!1,r;for(e<=Mp?(r=e,n=!0):r=ii(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=ii(e,r+1);return r}function o1(e,t,n){const r=[],i=e.length;for(let o=0;o<i;o++)o!==t?r.push(e[o]):r.push(n);return r}function Bm(e,t,n){const r=e.shape[n],i=[];let o=1,a=1;for(let s=0;s<n;s++)i.push(e.shape[s]),o*=e.shape[s];for(let s=0;s<t.rank;s++)i.push(t.shape[s]);for(let s=n+1;s<e.rank;s++)i.push(e.shape[s]),a*=e.shape[s];return{batchSize:o,sliceSize:a,dimSize:r,outputShape:i}}function s1(e,t,n=0){const r=h(e,"x","gather"),i=h(t,"indices","gather","int32"),o={x:r,indices:i},a={axis:n},s=(c,p)=>{const l=z(n,r.shape)[0],u=Bm(r,i,l),m=c.gather(r,x(i,[i.size]),l);return p([r,i]),x(m,u.outputShape)};return g.runKernelFunc(s,o,null,wo,a)}const Gn=d({gather_:s1});function a1(e,t){let n=h(e,"a","greater"),r=h(t,"b","greater");[n,r]=V(n,r),H(n.shape,r.shape);const i=a=>a.greater(n,r),o={a:n,b:r};return g.runKernelFunc(i,o,null,oh)}const Ve=d({greater_:a1});function c1(e,t){let n=h(e,"a","greaterEqual"),r=h(t,"b","greaterEqual");[n,r]=V(n,r),H(n.shape,r.shape);const i=(a,s)=>{const c=a.greaterEqual(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,yo)}const ct=d({greaterEqual_:c1});function p1(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],i=e.size/r,o=x(e,[i,r]),a=n.ifft(o);return x(a,e.shape)},t,null,sh)}const cn=d({ifft_:p1});function l1(e){const t=h(e,"input","imag"),n=i=>i.imag(t),r={input:t};return g.runKernelFunc(n,r,null,ah)}const Vt=d({imag_:l1});function u1(e){const t=h(e,"input","real"),n=i=>i.real(t),r={input:t};return g.runKernelFunc(n,r,null,Th)}const kt=d({real_:u1});function h1(e,t){const n=h(e,"x","reverse"),r=a=>{const s=z(t,n.shape);if(n.rank===0)return At(n);const c=a.reverse(n,s);return x(c,n.shape)},i={x:n},o={dims:t};return g.runKernelFunc(r,i,null,Vo,o)}const Pe=d({reverse_:h1});function k(e,t){if((Ie(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&Ie(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],r=[];return ze(e,n,r,t)}function d1(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const i=x(e,[n,t]);r=cn(i)}else{const i=[n,2*(t-1)],o=x(kt(e),[n,t]),a=x(Vt(e),[n,t]),s=Pe(Y(o,[0,1],[n,t-2]),1),c=v(Pe(Y(a,[0,1],[n,t-2]),1),k(-1)),p=re([o,s],1),l=re([a,c],1),u=x(Ge(p,l),[i[0],i[1]]);r=cn(u)}if(r=kt(r),e.rank===3&&e.shape[0]!==0){const i=r,o=e.shape[0];r=x(r,[o,r.shape[0]/o,r.shape[1]]),i.dispose()}return r}const _i=d({irfft_:d1});function m1(e){const t=h(e,"x","isFinite"),n={x:t};return g.runKernelFunc(r=>r.isFinite(t),n,null,Lo)}const tu=d({isFinite_:m1});function f1(e){const t=h(e,"x","isInf"),n={x:t};return g.runKernelFunc(r=>r.isInf(t),n,null,vo)}const eu=d({isInf_:f1});function g1(e){const t=h(e,"x","isNaN"),n={x:t};return g.runKernelFunc(r=>r.isNaN(t),n,null,So)}const Ql=d({isNaN_:g1});function b1(e,t){let n=h(e,"a","maximum"),r=h(t,"b","maximum");[n,r]=V(n,r),n.dtype==="bool"&&(n=R(n,"int32"),r=R(r,"int32")),H(n.shape,r.shape);const i=(a,s)=>{const c=a.maximum(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,Ro)}const Tt=d({maximum_:b1});function w1(e,t=.2){const n=h(e,"x","leakyRelu");return Tt(v(k(t),n),n)}const Zl=d({leakyRelu_:w1});function y1(e,t){let n=h(e,"a","less"),r=h(t,"b","less");[n,r]=V(n,r),H(n.shape,r.shape);const i=a=>a.less(n,r),o={a:n,b:r};return g.runKernelFunc(i,o,null,ch)}const jn=d({less_:y1});function x1(e,t){let n=h(e,"a","lessEqual"),r=h(t,"b","lessEqual");[n,r]=V(n,r),H(n.shape,r.shape);const i=(a,s)=>{const c=a.lessEqual(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,ph)}const at=d({lessEqual_:x1});function Xl(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return g.runKernelFunc(i=>i.linspace(e,t,n),{},null,lh,r)}function L1(e,t=5,n=1,r=1,i=.5){const o=h(e,"x","localResponseNormalization");f(o.rank===4||o.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${o.rank}.`),f(J(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=o,s=!1;o.rank===3&&(s=!0,a=x(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const c=(m,b)=>{const y=m.localResponseNormalization4D(a,t,n,r,i);return b([a,y]),y},p={x:a},l={depthRadius:t,bias:n,alpha:r,beta:i},u=g.runKernelFunc(c,p,null,No,l);return s?x(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const Jl=d({localResponseNormalization_:L1});function v1(e){const t=h(e,"x","log"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.log(t);return i([t]),o},n,null,To)}const gt=d({log_:v1});function S1(e){const t=h(e,"x","log1p"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.log1p(t);return i([t]),o},n,null,Io)}const Ni=d({log1p_:S1});function aS(e){return f(qt(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const r=h(t,"x","tf.grad",null),i=n!=null?h(n,"dy","tf.grad"):null;return g.tidy(()=>{const{value:o,grads:a}=g.gradients(()=>e(r),[r],i);return i!=null&&$(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Up(a),a[0]})}}function cS(e){return f(qt(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{f(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=rn(t,"args","tf.grads",null),i=n!=null?h(n,"dy","tf.grads"):null;return g.tidy(()=>{const{value:o,grads:a}=g.gradients(()=>e(...r),r,i);return i!=null&&$(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Up(a),a})}}function pS(e){return f(qt(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{f(t instanceof de,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),f(n==null||n instanceof de,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:i}=g.gradients(()=>e(t),[t],n);return Up(r),{grad:r[0],value:i}}}function lS(e){return f(qt(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{f(Array.isArray(t)&&t.every(i=>i instanceof de),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),f(n==null||n instanceof de,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=g.gradients(()=>e(...t),t,n);return n!=null&&$(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Up(r.grads),r}}function kh(e,t){f(qt(e),()=>"The f passed in variableGrads(f) must be a function"),f(t==null||Array.isArray(t)&&t.every(p=>p instanceof Nn),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in g.registeredVariables)t.push(g.registeredVariables[p])}const r=n?t.filter(p=>!p.trainable):null,i=t.length;t=t.filter(p=>p.trainable),f(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:s}=g.gradients(e,t,null,o);f(s.some(p=>p!=null),()=>"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()."),f(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const c={};return t.forEach((p,l)=>{s[l]!=null&&(c[p.name]=s[l])}),r!=null&&r.forEach(p=>c[p.name]=null),{value:a,grads:c}}function $e(e){return g.customGrad(e)}function Up(e){const t=e.filter(n=>n==null).length;if(t>0)throw new 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.`)}function T1(e){const t=h(e,"x","neg"),n={x:t};return g.runKernelFunc(r=>r.neg(t),n,null,Mo)}const Q=d({neg_:T1});function I1(e){const t=h(e,"x","softplus"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.softplus(t);return i([t]),o},n,null,is)}const gi=d({softplus_:I1});function A1(e){const t=h(e,"x","logSigmoid"),n=$e(r=>{const i=Q(gi(Q(r))),o=a=>{const s=v(a,St(Q(r)));return s};return{value:i,gradFunc:o}});return n(t)}const Kl=d({logSigmoid_:A1});function N1(e,t=null,n=!1){const r=h(e,"x","max"),i=(s,c)=>{const p=z(t,r.shape);let l=p;const u=he(l,r.rank);let m=r;u!=null&&(m=X(r,u),l=Ee(l.length,m.rank));const b=s.max(m,l);u!=null&&m.dispose();let y=b;if(n){const w=fe(y.shape,z(t,r.shape));y=x(y,w),b.dispose()}return c([r,y]),y},o={x:r},a={reductionIndices:t,keepDims:n};return g.runKernelFunc(i,o,null,_o,a)}const st=d({max_:N1});function _1(e,t){let n=h(e,"a","sub"),r=h(t,"b","sub");[n,r]=V(n,r);const i=(a,s)=>{const c=a.subtract(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,us)}const D=d({sub_:_1});function R1(e,t=null,n=!1){let r=h(e,"x","sum");r.dtype==="bool"&&(r=R(r,"int32"));const i=(s,c)=>{c([r]);const p=z(t,r.shape),l=he(p,r.rank);let u=p,m=r;l!=null&&(m=X(r,l),u=Ee(u.length,r.rank));let b=s.sum(m,u);if(n){const y=fe(b.shape,p);b=x(b,y)}return b},o={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(i,o,null,ss,a)}const U=d({sum_:R1});function C1(e,t=-1){const n=h(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}`);const r=(a,s)=>{const c=!0,p=st(e,t,!0),l=D(e,p),u=D(R(l,"float32"),gt(U(Ne(l),t,c)));return s([u]),u},i={logits:n},o={axis:t};return g.runKernelFunc(r,i,null,Ao,o)}const Vl=d({logSoftmax_:C1});function E1(e,t=null,n=!1){const r=h(e,"x","logSumExp"),i=z(t,r.shape),o=st(r,i,!0),a=D(r,o),s=Ne(a),c=U(s,i),p=gt(c),l=O(x(o,p.shape),p);if(n){const u=fe(l.shape,i);return x(l,u)}return l}const Ai=d({logSumExp_:E1});function O1(e,t){const n=h(e,"a","logicalAnd","bool"),r=h(t,"b","logicalAnd","bool");H(n.shape,r.shape);const i={a:n,b:r};return g.runKernelFunc(o=>o.logicalAnd(n,r),i,null,uh)}const ft=d({logicalAnd_:O1});function k1(e){const t=h(e,"x","logicalNot","bool"),n={x:t};return g.runKernelFunc(r=>r.logicalNot(t),n,null,hh)}const Pn=d({logicalNot_:k1});function D1(e,t){const n=h(e,"a","logicalOr","bool"),r=h(t,"b","logicalOr","bool");H(n.shape,r.shape);const i={a:n,b:r};return g.runKernelFunc(o=>o.logicalOr(n,r),i,null,dh)}const Ii=d({logicalOr_:D1});function F1(e,t){const n=h(e,"a","logicalXor","bool"),r=h(t,"b","logicalXor","bool");return H(n.shape,r.shape),ft(Ii(e,t),Pn(ft(e,t)))}const zl=d({logicalXor_:F1});function M1(e,t,n,r,i){const o=h(e,"x","maxPool"),a=1;let s=o,c=!1;o.rank===3&&(c=!0,s=x(o,[1,o.shape[0],o.shape[1],o.shape[2]])),f(s.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.rank}.`),f(ae(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&f(J(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const p=(b,y)=>{const w=Ct(s.shape,t,n,1,r,i);let L;return w.filterWidth===1&&w.filterHeight===1&&Le(w.inShape,w.outShape)?L=s.clone():L=b.maxPool(s,w),y([s,L]),L},l={x:s},u={filterSize:t,strides:n,pad:r,dimRoundingMode:i},m=g.runKernelFunc(p,l,null,Co,u);return c?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const Ti=d({maxPool_:M1});function U1(e,t=[1,1,1],n,r,i,o="NDHWC",a){a==null?a=[1,1,1]:ge("dilations is deprecated, this field will be gone in v3.0.0.");const s=h(e,"x","maxPool3d");let c=s,p=!1;s.rank===4&&(p=!0,c=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${c.rank}.`),f(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),f(ae(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&f(J(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const l=(y,w)=>{a==null&&(a=[1,1,1]);const L=on(c.shape,t,n,a,r,i,o),T=y.maxPool3d(c,L);return w([c,T]),T},u={x:c},m={filterSize:t,strides:n,pad:r,dimRoundingMode:i,dataFormat:o,dilations:a},b=g.runKernelFunc(l,u,null,Eo,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Yl=d({maxPool3d_:U1});function W1(e,t,n,r,i=!1){const o=h(e,"x","maxPoolWithArgmax"),a={x:o},s={filterSize:t,strides:n,pad:r,includeBatchInIndex:i},c=g.runKernel(bh,a,s);return{result:c[0],indexes:c[1]}}const Hl=d({maxPoolWithArgmax_:W1});function Ue(e,t="float32"){if(t==="complex64"){const r=Ue(e,"float32"),i=Ue(e,"float32");return Ge(r,i)}const n=Pt(Z(e),t);return g.makeTensor(n,e,t)}function mt(e,t="float32"){if(t==="complex64"){const r=mt(e,"float32"),i=Ue(e,"float32");return Ge(r,i)}const n=Ws(Z(e),t);return g.makeTensor(n,e,t)}function q1(e,t=null,n=!1){const r=h(e,"x","mean"),i=z(t,r.shape),o=Nm(r.shape,i),a=o[1],s=Z(a),c=$e(p=>{const l=k(s),u=l.dtype===p.dtype?p:R(p,l.dtype),m=M(u,l),b=U(m,t,n),y=w=>{const L=p.shape.slice();i.forEach(_=>{L[_]=1});const T=x(w,L),A=M(v(T,mt(p.shape,"float32")),s);return A};return{value:b,gradFunc:y}});return c(r)}const an=d({mean_:q1});function B1(e,t=null,n=!1){const r=h(e,"x","min"),i=(s,c)=>{const p=z(t,r.shape);let l=p;const u=he(l,r.rank);let m=r;u!=null&&(m=X(r,u),l=Ee(l.length,r.rank));const b=s.min(m,l);u!=null&&m.dispose();let y=b;if(n){const w=fe(y.shape,p);y=x(b,w),b.dispose()}return c([r,y]),y},o={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(i,o,null,Oo,a)}const sn=d({min_:B1});function P1(e,t){let n=h(e,"a","minimum"),r=h(t,"b","minimum");[n,r]=V(n,r),n.dtype==="bool"&&(n=R(n,"int32"),r=R(r,"int32")),H(n.shape,r.shape);const i=(a,s)=>{const c=a.minimum(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,ko)}const Bn=d({minimum_:P1});function j1(e,t){let n=h(e,"a","mod"),r=h(t,"b","mod");[n,r]=V(n,r);const i=(a,s)=>{const c=a.mod(n,r);return s([n,r]),c},o={a:n,b:r};return g.runKernelFunc(i,o,null,Do)}const Si=d({mod_:j1});function G1(e){const t=h(e,"x","square"),n={},r=[t],i=[];return g.runKernelFunc((o,a)=>(a([t]),o.square(t)),{x:t},null,"Square",n,r,i)}const G=d({square_:G1});function $1(e,t=null,n=!1){e=h(e,"x","moments");const r=z(t,e.shape),i=an(e,r,n);let o=i.shape;n||(o=fe(i.shape,r));const a=G(D(R(e,"float32"),x(i,o))),s=an(a,r,n);return{mean:i,variance:s}}const $l=d({moments_:$1});function H1(e,t,n,r){const i=h(t,"data","multiRNNCell"),o=rn(n,"c","multiRNNCell"),a=rn(r,"h","multiRNNCell");let s=i;const c=[];for(let u=0;u<e.length;u++){const m=e[u](s,o[u],a[u]);c.push(m[0]),c.push(m[1]),s=m[1]}const p=[],l=[];for(let u=0;u<c.length;u+=2)p.push(c[u]),l.push(c[u+1]);return[p,l]}const Gl=d({multiRNNCell_:H1});function Y1(e,t,n,r=!1){const i=h(e,"logits","multinomial"),o=i.size,a=i.rank;if(o<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${o}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const s=a===1?x(i,[1,-1]):i,c=g.runKernelFunc(p=>p.multinomial(s,r,t,n),{logits2D:s});return a===1?x(c,[c.size]):c}const jl=d({multinomial_:Y1});function z1(e,t){let n=h(e,"a","notEqual"),r=h(t,"b","notEqual");[n,r]=V(n,r),H(n.shape,r.shape);const i=a=>a.notEqual(n,r),o={a:n,b:r};return g.runKernelFunc(i,o,null,wh)}const qn=d({notEqual_:z1});function V1(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i=h(e,"indices","oneHot","int32"),o=[...i.shape,t],a=(p,l)=>(l([i]),x(p.oneHot(x(i,[i.size]),t,n,r),o)),s={indices:i},c={depth:t,onValue:n,offValue:r};return g.runKernelFunc(a,s,null,Wo,c)}const Sr=d({oneHot_:V1});function K1(e){const t=h(e,"x","onesLike"),n=(i,o)=>{if(t.dtype==="complex64"){const a=ea(kt(t)),s=W(Vt(t));return Ge(a,s)}return i.onesLike(t)},r={x:t};return g.runKernelFunc(n,r,null,Uo)}const ea=d({onesLike_:K1});function J1(e,t){const n=h(e,"v1","outerProduct"),r=h(t,"v2","outerProduct");f(n.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const i=x(n,[-1,1]),o=x(r,[1,-1]);return K(i,o)}const Pl=d({outerProduct_:J1});function X1(e,t,n=0){const r=h(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i=(s,c)=>(c([r]),s.pad(r,t,n)),o={paddings:t,constantValue:n},a={x:r};return g.runKernelFunc(i,a,null,qo,o)}const ot=d({pad_:X1});function Z1(e,t,n=0){return f(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ot(e,[t],n)}const Bl=d({pad1d_:Z1});function Q1(e,t,n=0){return f(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ot(e,t,n)}const ql=d({pad2d_:Q1});function eC(e,t,n=0){return f(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ot(e,t,n)}const Wl=d({pad3d_:eC});function tC(e,t,n=0){return f(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ot(e,t,n)}const Ul=d({pad4d_:tC});function nC(e,t,n){const r=h(e,"x","spaceToBatchND");f(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),f(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),f(r.shape.reduce((s,c,p)=>p>0&&p<=t.length?s&&(c+n[p-1][0]+n[p-1][1])%t[p-1]===0:s,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const i=s=>s.spaceToBatchND(r,t,n),o={x:r},a={blockShape:t,paddings:n};return g.runKernelFunc(i,o,null,as,a)}const Un=d({spaceToBatchND_:nC});function oC(e,t,n,r,i,o){i==null&&(i=[1,1]),o==null&&(o=1),r===0&&(r="valid");const a=h(e,"x","maxPool");let s=a,c=!1;a.rank===3&&(c=!0,s=x(a,[1,a.shape[0],a.shape[1],a.shape[2]])),f(ae(o,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`);const p=Ct(s.shape,t,o,i,r),l=[p.dilationHeight,p.dilationWidth];let u;r==="same"?u=iC([p.filterHeight,p.filterWidth],l):u=[[0,0],[0,0]];const m=l[0]===1&&l[1]===1,[b,y]=rC([p.inHeight,p.inWidth],l,u),w=m?r:"valid",L=m?s:Un(s,l,b),T=n==="avg"?()=>Di(L,t,o,w):()=>Ti(L,t,o,w),A=T(),_=m?A:Kn(A,l,y);return c?x(_,[_.shape[1],_.shape[2],_.shape[3]]):_}function rC(e,t,n){const r=n.map(l=>l[0]),i=n.map(l=>l[1]),o=e.concat(r,i),a=t.map((l,u)=>(l-o[u]%l)%l),s=i.map((l,u)=>l+a[u]),c=t.map((l,u)=>[r[u],s[u]]),p=t.map((l,u)=>[0,a[u]]);return[c,p]}function iC(e,t){const n=e.map((a,s)=>a+(a-1)*(t[s]-1)),r=n.map(a=>a-1),i=r.map(a=>Math.floor(a/2)),o=r.map((a,s)=>a-i[s]);return r.map((a,s)=>[i[s],o[s]])}const Ml=d({pool_:oC});function sC(e,t){let n=h(e,"base","pow"),r=h(t,"exp","pow");[n,r]=V(n,r);const i={a:n,b:r},o=(a,s)=>{const c=a.pow(n,r);return s([n,r,c]),c};return g.runKernelFunc(o,i,null,Bo)}const je=d({pow_:sC});function aC(e,t){const n=h(e,"x","prelu"),r=h(t,"alpha","prelu"),i=(a,s)=>{const c=a.prelu(n,r);return s([n,r]),c},o={x:n,alpha:r};return g.runKernelFunc(i,o,null,Po)}const vi=d({prelu_:aC});function Fl(e,t=!1){console.log(e.toString(t))}function cC(e,t=null,n=!1){let r=h(e,"x","prod");const i=s=>{r.dtype==="bool"&&(r=R(r,"int32"));const c=z(t,r.shape),p=he(c,r.rank);let l=c,u=r;p!=null&&(u=X(r,p),l=Ee(l.length,r.rank));let m=s.prod(u,l);if(n){const b=fe(m.shape,c);m=x(m,b)}return m},o={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(i,o,null,vh,a)}const Dl=d({prod_:cC});function pC(e,t,n){const r=Z(e);let i=null;if(n==null||n==="float32")i=new Float32Array(r);else if(n==="int32")i=new Int32Array(r);else if(n==="bool")i=new Uint8Array(r);else throw new Error(`Unknown data type ${n}`);for(let o=0;o<r;o++)i[o]=t();return g.makeTensor(i,e,n)}const kl=d({rand_:pC});const Rf={};Oe(Rf,{TEST_EPSILON_FLOAT16:()=>qy,expectArrayBuffersEqual:()=>gC,expectArraysClose:()=>uC,expectArraysEqual:()=>dC,expectNumbersClose:()=>mC,expectPromiseToFail:()=>hC,expectValuesInRange:()=>fC,testEpsilon:()=>Pm});const lC=.001,qy=.1;function uC(e,t,n){return n==null&&(n=Pm()),jm(e,t,(r,i)=>Gm(r,i,n))}function Pm(){return g.backend.floatPrecision()===32?lC:qy}function jm(e,t,n){let r=!0;if((Ie(e)||Ie(t))&&(r=!1),Ie(e)&&Ie(t)&&(r=!0),r){const a=e.constructor.name,s=t.constructor.name;if(a!==s)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${s}`)}if(Array.isArray(e)&&Array.isArray(t)){const a=Fe(e),s=Fe(t);if(!Le(a,s))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${s}]`)}const i=Ie(e)?e:Wt(e),o=Ie(t)?t:Wt(t);if(i.length!==o.length)throw new Error(`Arrays have different lengths actual: ${i.length} vs expected: ${o.length}.
|
|
Actual: ${i}.
|
|
Expected: ${o}.`);for(let a=0;a<o.length;++a){const s=i[a],c=o[a];if(!n(s,c))throw new Error(`Arrays differ: actual[${a}] = ${s}, expected[${a}] = ${c}.
|
|
Actual: ${i}.
|
|
Expected: ${o}.`)}}function hC(e,t){e().then(()=>t.fail(),()=>t())}function dC(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Rt(e)||Rt(e[0])||Rt(t)||Rt(t[0])?jm(e,n,(r,i)=>r==i):jm(e,t,(r,i)=>Gm(r,i,0))}function mC(e,t,n){if(n==null&&(n=Pm()),!Gm(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Gm(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function fC(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function gC(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const Wp=Iv(Nf());class zs{constructor(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+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const o=i||Math.random();this.random=Wp.alea(o.toString())}nextValue(){if(!isNaN(this.nextVal)){const r=this.nextVal;return this.nextVal=NaN,r}let e,t,n=!1;for(;!n;){let r,i,o;do r=2*this.random()-1,i=2*this.random()-1,o=r*r+i*i;while(o>=1||o===0);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*i*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class By{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const i=r||Math.random();this.randu=Wp.alea(i.toString()),this.randn=new zs(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,i,o;for(;;){do r=this.randn.nextValue(),o=1+this.c*r;while(o<=0);if(o*=o*o,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-o+Math.log(o)),i=this.randu(),i<t||Math.log(i)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class Py{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Wp.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function bC(e,t,n=1,r="float32",i){if(n==null&&(n=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);const o=new By(t,n,r,i),a=ke(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}const Ol=d({randomGamma_:bC});function wC(e,t=0,n=1,r,i){if(r!=null&&r==="bool")throw new Error(`Unsupported data type ${r}`);const o=new zs(t,n,r,!1,i),a=ke(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}const El=d({randomNormal_:wC});function yC(e,t=0,n=1,r="float32",i){const o=ke(e,r),a=new Py(t,n,null,i);for(let s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}const Li=d({randomUniform_:yC});function ht(e,t){lt(e);const n=Fe(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const r=null;return ze(e,r,n,t)}function vr(e,t,n=1,r="float32"){if(n===0)throw new Error("Cannot have a step of zero");const i=()=>{const a=e===t,s=e<t&&n<0,c=t<e&&n>1;if(a||s||c)return Ue([0],r);const p=Math.abs(Math.ceil((t-e)/n)),l=Pt(p,r);t<e&&n===1&&(n=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+n;return ht(l,r)},o={start:e,stop:t,step:n,dtype:r};return g.runKernelFunc(i,{},null,Sh,o)}function xC(e){const t=h(e,"x","reciprocal"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.reciprocal(t);return i([t]),o},n,null,jo)}const Cl=d({reciprocal_:xC});function LC(e){const t=h(e,"x","relu"),n=(i,o)=>(o([t]),t.dtype==="bool"?R(t,"int32"):i.relu(t)),r={x:t};return g.runKernelFunc(n,r,null,Go)}const zt=d({relu_:LC});function vC(e){const t=h(e,"x","relu6"),n=(i,o)=>(o([t]),t.dtype==="bool"?R(t,"int32"):i.relu6(t)),r={x:t};return g.runKernelFunc(n,r,null,zo)}const xi=d({relu6_:vC});function SC(e){const t=h(e,"x","reverse");return f(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Pe(t,0)}const Rl=d({reverse1d_:SC});function TC(e,t){const n=h(e,"x","reverse");return f(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Pe(n,t)}const _l=d({reverse2d_:TC});function IC(e,t){const n=h(e,"x","reverse");return f(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Pe(n,t)}const Nl=d({reverse3d_:IC});function AC(e,t){const n=h(e,"x","reverse");return f(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Pe(n,t)}const Al=d({reverse4d_:AC});function $m(e,t,n=0){let r=[];if(typeof t=="number")f(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{const i=t.reduce((a,s)=>(s===-1&&(a+=1),a),0);f(i<=1,()=>"There should be only one negative value in split array.");const o=t.indexOf(-1);if(o!==-1){const a=t.reduce((s,c)=>c>0?s+c:s);t[o]=e.shape[n]-a}f(e.shape[n]===t.reduce((a,s)=>a+s),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function NC(e,t,n=0){const r=h(e,"x","split"),i=(s,c)=>{const p=z(n,r.shape)[0],l=$m(r,t,p);return s.split(r,l,p)},o={x:r},a={numOrSizeSplits:t,axis:n};return g.runKernelFunc(i,o,null,cs,a)}const Ot=d({split_:NC});function _C(e,t){f(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let i;if(t!=null&&t<n){const y=e.shape.map(L=>0),w=e.shape.map(L=>L);w[e.shape.length-1]=t,i=Y(e,y,w),n=t}else if(t!=null&&t>n){const y=e.shape.map(w=>w);y[e.shape.length-1]=t-n,i=re([e,Ue(y)],e.shape.length-1),n=t}else i=e;const o=W(i),a=x(Ge(i,o),[r,n]),s=Yn(a),c=Math.floor(n/2)+1,p=kt(s),l=Vt(s),u=Ot(p,[c,n-c],p.shape.length-1),m=Ot(l,[c,n-c],l.shape.length-1),b=i.shape.slice();return b[i.shape.length-1]=c,x(Ge(u[0],m[0]),b)}const Wn=d({rfft_:_C});function RC(e){const t=h(e,"x","round"),n={x:t};return g.runKernelFunc(r=>r.round(t),n,null,Ko)}const Il=d({round_:RC});function CC(e){const t=h(e,"x","rsqrt"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.rsqrt(t);return i([t]),o},n,null,Jo)}const yi=d({rsqrt_:CC});function EC(e){const t=h(e,"x","selu"),n=(i,o)=>{const a=i.selu(t);return o([t]),a},r={x:t};return g.runKernelFunc(n,r,null,Zo)}const Tl=d({selu_:EC});function OC(e,t,n,r,i,o=[1,1],a="NHWC"){const s=h(e,"x","separableConv2d"),c=h(t,"depthwiseFilter","separableConv2d"),p=h(n,"pointwiseFilter","separableConv2d");let l=s,u=!1;if(s.rank===3&&(u=!0,l=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");f(l.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`),f(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),f(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const m=c.shape[2],b=c.shape[3];f(p.shape[2]===m*b,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*b}, but got ${p.shape[2]}.`);const y=zn(l,c,r,i,a,o),w=1,L=It(y,p,w,"valid",a);return u?x(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Sl=d({separableConv2d_:OC});async function kC(e,t){const n=h(e,"x","setdiff1d"),r=h(t,"y","setdiff1d");f(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),f(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),f(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);const i=await n.data(),o=await r.data(),a=new Set(o);let s=0;for(let l=0;l<i.length;l++)a.has(i[l])||s++;const c=new yr([s],n.dtype),p=new yr([s],"int32");for(let l=0,u=0;l<i.length;l++)a.has(i[l])||(c.values[u]=i[l],p.values[u]=l,u++);return[c.toTensor(),p.toTensor()]}const vl=kC;function DC(e){const t=h(e,"x","sign"),n={x:t};return g.runKernelFunc(r=>r.sign(t),n,null,ns)}const Ll=d({sign_:DC});function FC(e){const t=h(e,"x","sin"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.sin(t);return i([t]),o},n,null,es)}const wi=d({sin_:FC});function MC(e){const t=h(e,"x","sinh"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.sinh(t);return i([t]),o},n,null,ts)}const bi=d({sinh_:MC});function UC(e,t,n){const r=h(e,"x","slice1d");return f(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),Y(r,[t],[n])}const xl=d({slice1d_:UC});function WC(e,t,n){const r=h(e,"x","slice2d");return f(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),Y(r,t,n)}const yl=d({slice2d_:WC});function qC(e,t,n){const r=h(e,"x","slice3d");return f(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),Y(r,t,n)}const wl=d({slice3d_:qC});function BC(e,t,n){const r=h(e,"x","slice4d");return f(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),Y(r,t,n)}const bl=d({slice4d_:BC});function PC(e,t=-1){const n=h(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}`);const r={logits:n},i={dim:t};return g.runKernelFunc((o,a)=>{const s=o.softmax(n,t);return a([s]),s},r,null,ps,i)}const gl=d({softmax_:PC});function jC(e){const t=h(e,"x","sqrt"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.sqrt(t);return i([t]),o},n,null,os)}const le=d({sqrt_:jC});function GC(e,t){let n=h(e,"a","squaredDifference"),r=h(t,"b","squaredDifference");[n,r]=V(n,r),H(n.shape,r.shape);const i=(s,c)=>{const p=s.squaredDifference(n,r);return c([n,r]),p},o={a:n,b:r},a={};return g.runKernelFunc(i,o,null,ls,a)}const Mn=d({squaredDifference_:GC});function $C(e,t){const n=h(e,"x","squeeze");return x(n,hm(n.shape,t).newShape)}const Fn=d({squeeze_:$C});function HC(e,t=0){const n=rn(e,"tensors","stack");if(f(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return Ke(n[0],t);const r=n[0].rank,i=n[0].shape,o=n[0].dtype;f(t<=r,()=>"Axis must be <= rank of the tensor"),n.forEach(s=>{$(i,s.shape,"All tensors passed to stack must have matching shapes"),f(o===s.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(s=>Ke(s,t));return re(a,t)}const dt=d({stack_:HC});function YC(e,t=0){const n=h(e,"x","step"),r={x:n},i={alpha:t};return g.runKernelFunc(o=>o.step(n,t),r,null,ys,i)}const vt=d({step_:YC});function zC(e,t,n,r,i=0,o=0,a=0,s=0,c=0){r==null&&(r=new Array(t.length));let p=h(e,"x","stridedSlice");const l=b=>{const y=Hs(a);if(y.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&s!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&c!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const w=p.rank-t.length,L=Hs(s),T=p.shape.slice();if(L.forEach(E=>{t[E]=0,n[E]=1,T.splice(E,0,1)}),p=x(p,T),y.length&&w>0){const E=y[0],B=w+1;t=Fm(i,E,B,t,p.shape),n=Mm(o,E,B,n,p.shape),r=Dm(r,E,B,p.shape)}else for(let E=0;E<p.rank;E++)t[E]=Wm(i,t,r,p.shape,E,a),n[E]=qm(o,n,r,p.shape,E,a),r[E]=Um(r,E,a);const A=Hs(c);A.forEach(E=>{n[E]=t[E]+1,r[E]=1});const _=km(t,n,r),N=_.filter((E,B)=>A.indexOf(B)===-1),C=r.every(E=>E===1);if(C)return x(Y(p,t,_),N);const F=b.stridedSlice(p,t,n,r);return x(F,N)},u={x:p},m={begin:t,end:n,strides:r,beginMask:i,endMask:o,ellipsisMask:a,newAxisMask:s,shrinkAxisMask:c};return g.runKernelFunc(l,u,null,Ch,m)}const fl=d({stridedSlice_:zC});function VC(e){const t=h(e,"x","tan"),n={x:t};return g.runKernelFunc((r,i)=>{const o=r.tan(t);return i([t]),o},n,null,hs)}const ml=d({tan_:VC});function Yt(e,t,n){if(lt(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=Fe(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ze(e,t,r,n)}function fi(e,t,n){if(lt(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=Fe(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function dl(e,t,n){if(lt(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=Fe(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function hl(e,t,n){if(lt(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=Fe(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function ul(e,t,n){if(lt(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=Fe(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,ze(e,t,r,n)}function KC(e,t=1,n=!0){const r=h(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const i=r.shape[r.shape.length-1];if(t>i)throw new Error(`'k' passed to topk() must be <= the last dimension (${i}) but got ${t}`);const o={x:r},a={k:t,sorted:n},[s,c]=g.runKernelFunc(p=>p.topk(r,t,n),o,null,Eh,a);return{values:s,indices:c}}const ll=d({topk_:KC});function JC(e,t=0,n=1,r,i){if(r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new zs(t,n,r,!0,i),a=ke(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}const pl=d({truncatedNormal_:JC});function XC(e,t,n){const r=h(e,"x","unsortedSegmentSum"),i=h(t,"segmentIds","unsortedSegmentSum","int32");f(J(n),()=>"numSegments must be of dtype int");const o={x:r,segmentIds:i},a={numSegments:n},s=(c,p)=>{const l=c.unsortedSegmentSum(r,i,n);return p([i]),l};return g.runKernelFunc(s,o,null,bs,a)}const mi=d({unsortedSegmentSum_:XC});function ZC(e,t=0){const n=h(e,"x","unstack");f(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`),t<0&&(t+=n.shape.length);const r={value:n},i={axis:t},o=a=>a.unstack(n,t);return g.runKernelFunc(o,r,null,gs,i)}const Dn=d({unstack_:ZC});function cl(e,t=!0,n,r){return g.makeVariable(e,t,n,r)}function qp(e,t){const n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(o);const r=ke(e,"int32"),i=ke([n.length,e.length],"int32");for(let o=0;o<n.length;o++){const a=r.indexToLoc(n[o]),s=o*e.length;i.values.set(a,s)}return i.toTensor()}async function QC(e){const t=h(e,"condition","whereAsync","bool"),n=await t.data(),r=qp(t.shape,n);return e!==t&&t.dispose(),r}const di=QC;async function eE(e,t,n){const r=h(e,"tensor","boolMask"),i=h(t,"mask","boolMask","bool"),o=n==null?0:n,a=i.rank,s=r.shape;f(a>0,()=>"mask cannot be scalar"),$(s.slice(o,o+a),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let w=o;w<o+a;w++)c*=s[w];const p=s.slice(0,o).concat([c],s.slice(o+a)),l=x(r,p),u=x(i,[-1]),m=await di(u),b=Fn(m,[1]),y=Gn(l,b,o);return e!==r&&r.dispose(),t!==i&&i.dispose(),b.dispose(),l.dispose(),u.dispose(),m.dispose(),y}const Qf=eE;function tE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","notEqualStrict"),r=h(t,"b","notEqualStrict");return $(n.shape,r.shape,"Error in notEqualStrict: "),qn(n,r)}function nE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","lessStrict"),r=h(t,"b","lessStrict");return $(n.shape,r.shape,"Error in lessStrict: "),jn(n,r)}function rE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","equalStrict"),r=h(t,"b","equalStrict");return $(n.shape,r.shape,"Error in equalStrict: "),Kt(n,r)}function iE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","lessEqualStrict"),r=h(t,"b","lessEqualStrict");return $(n.shape,r.shape,"Error in lessEqualStrict: "),at(n,r)}function oE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","greaterStrict"),r=h(t,"b","greaterStrict");return $(n.shape,r.shape,"Error in greaterStrict: "),Ve(n,r)}function sE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","greaterEqualStrict"),r=h(t,"b","greaterEqualStrict");return $(n.shape,r.shape,"Error in greaterEqualStrict: "),ct(n,r)}const Yf=d({equalStrict_:rE}),zf=d({greaterEqualStrict_:sE}),Vf=d({greaterStrict_:oE}),Kf=d({lessEqualStrict_:iE}),Jf=d({lessStrict_:nE}),Xf=d({notEqualStrict_:tE});function aE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","addStrict"),r=h(t,"b","addStrict");return $(n.shape,r.shape,"Error in addStrict: "),O(n,r)}function cE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","subStrict"),r=h(t,"b","subStrict");return $(n.shape,r.shape,"Error in subStrict: "),D(n,r)}function pE(e,t){return ge("strict variants of ops have been deprecated and will be removed in future"),$(e.shape,t.shape,"Error in powStrict: "),je(e,t)}function lE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","mul"),r=h(t,"b","mul");return $(n.shape,r.shape,"Error in multiplyStrict: "),v(n,r)}function uE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","div"),r=h(t,"b","div");return $(n.shape,r.shape,"Error in divideStrict: "),M(n,r)}function hE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","modStrict"),r=h(t,"b","modStrict");return $(n.shape,r.shape,"Error in modStrict: "),Si(n,r)}function dE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","minimumStrict"),r=h(t,"b","minimumStrict");return $(n.shape,r.shape,"Error in minimumStrict: "),Bn(n,r)}function mE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","maximumStrict"),r=h(t,"b","maximumStrict");return $(n.shape,r.shape,"Error in maximumStrict: "),Tt(n,r)}function fE(e,t){ge("strict variants of ops have been deprecated and will be removed in future");const n=h(e,"a","squaredDifferenceStrict"),r=h(t,"b","squaredDifferenceStrict");return $(n.shape,r.shape,"Error in squaredDifferenceStrict: "),Mn(n,r)}const eg=d({addStrict_:aE}),tg=d({divStrict_:uE}),ng=d({maximumStrict_:mE}),rg=d({minimumStrict_:dE}),ig=d({modStrict_:hE}),og=d({mulStrict_:lE}),sg=d({powStrict_:pE}),ag=d({squaredDifferenceStrict_:fE}),cg=d({subStrict_:cE});function gE(e,t="euclidean",n=null,r=!1){e=h(e,"x","norm");const i=jy(e,t,n);let o=i.shape;if(r){const a=z(n,e.shape);o=fe(i.shape,a)}return x(i,o)}function jy(e,t,n=null){if(e.rank===0)return _e(e);if(e.rank!==1&&n===null)return jy(x(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return U(_e(e),n);if(t===Infinity)return st(_e(e),n);if(t===-Infinity)return sn(_e(e),n);if(t==="euclidean"||t===2)return le(U(je(_e(e),k(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return st(U(_e(e),n[0]),n[1]-1);if(t===Infinity)return st(U(_e(e),n[1]),n[0]);if(t===-Infinity)return sn(U(_e(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return le(U(G(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Tr=d({norm_:gE});function bE(e,t,n,r,i=!0){const o=h(e,"v","movingAverage"),a=h(t,"x","movingAverage"),s=h(n,"decay","movingAverage");Tm(o,a),f(Le(o.shape,a.shape),()=>"Shape mismatch in v and x");const c=k(1),p=D(c,s);let l=v(D(a,o),p);if(i){f(r!=null,()=>"When using zeroDebias: true, step is required.");const u=h(r,"step","movingAverage");l=M(l,D(c,je(s,u)))}return O(o,l)}const Pf=d({movingAverage_:bE});const Df={};Oe(Df,{calculateShapes:()=>Gy,validateInput:()=>Bp,validateUpdateShape:()=>Hm});function Hm(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,o=`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 new Error(o+` update.rank < ${i}. `);if(e.length<r+(n.rank-i))throw new Error(o+` Output shape length < ${r+(n.rank-i)}`);if(n.rank!==i+e.length-r)throw new Error(o+` update.rank != ${i+e.length-r}`);for(let a=0;a<i;++a)if(n.shape[a]!==t.shape[a])throw new Error(o+` updates.shape[${a}] (${n.shape[a]}) != indices.shape[${a}] (${t.shape[a]}).`);for(let a=0;a<n.rank-i;++a)if(n.shape[a+i]!==e[a+r])throw new Error(o+` updates.shape[${a+i}] (${n.shape[a+i]}) != shape[${a+i}] (${e[a+i]})`)}function Bp(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Hm(n,t,e)}function Gy(e,t,n){const r=t.shape.length,i=r>1?t.shape[r-1]:1,o=n.length;let a=1;for(let u=i;u<o;++u)a*=n[u];const s=i<1?1:i,c=Z(t.shape)/s,p=[...Bt(n.slice(0,i)),1],l=Z(n);return{sliceRank:i,numUpdates:c,sliceSize:a,strides:p,outputSize:l}}function wE(e,t,n){const r=h(e,"indices","scatterND","int32"),i=h(t,"updates","scatterND");Bp(i,r,n);const o=c=>c.scatterND(r,i,n),a={indices:r,updates:i},s={shape:n};return g.runKernelFunc(o,a,null,Nh,s)}const Ff=d({scatterND_:wE});function $y(e,t,n,r){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const i=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(n.length!==o)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${o}.`);const a=t.size;if(!(t.rank===0||t.rank===1&&a===i))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${i}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function yE(e,t,n,r=0){const i=h(e,"sparseIndices","sparseToDense","int32"),o=h(t,"sparseValues","sparseToDense"),a=h(r,"defaultValue","sparseToDense",o.dtype);$y(i,o,n,a);const s={sparseIndices:i,sparseValues:o,defaultValue:a},c={outputShape:n};return g.runKernelFunc(p=>p.sparseToDense(i,o,n,a),s,null,Rh,c)}const Of=d({sparseToDense_:yE});function xE(e,t){const n=h(t,"indices","gatherND","int32"),r=h(e,"x","gatherND"),i=a=>a.gatherND(r,n),o={params:r,indices:n};return g.runKernelFunc(i,o,null,ih)}const $f=d({gatherND_:xE});function Hy(e,t){if(t==null)return e.shape.slice();if(Le(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let 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}function LE(e,t,n,r){const i=h(e,"x","dropout");if(f(i.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${i.dtype} tensor instead.`),f(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof de?i.clone():i;const o=Hy(i,n),a=1-t,s=M($n(O(Li(o,0,1,"float32",r),a)),a);return v(i,s)}const Hf=d({dropout_:LE});function Qs(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Lr(e,t,n){const r=1-e%2,i=new Float32Array(e);for(let o=0;o<e;++o){const a=2*Math.PI*o/(e+r-1);i[o]=t-n*Math.cos(a)}return ht(i,"float32")}async function vE(e,t,n=1){const r=h(e,"predictions","inTopK"),i=h(t,"targets","inTopK");f(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),f(r.rank-1===i.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${i.rank}`),$(r.shape.slice(0,r.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const o=r.shape[r.shape.length-1];f(n>0&&n<=o,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${o}), but got ${n}`);const a=await r.data(),s=await i.data(),[c,p]=[a.length/o,o],l=ni("bool",c);for(let u=0;u<c;u++){const m=u*p,b=a.subarray(m,m+p),y=[];for(let w=0;w<b.length;w++)y.push({value:b[w],index:w});y.sort((w,L)=>L.value-w.value),l[u]=0;for(let w=0;w<n;w++)if(y[w].index===s[u]){l[u]=1;break}}return e!==r&&r.dispose(),t!==i&&i.dispose(),Qe(l,i.shape,"bool")}const jf=vE;function SE(e,t,n,r,i,o="NHWC",a){let s=e;e.rank===3&&(s=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let c=t;c.rank===3&&(c=x(t,[1,t.shape[0],t.shape[1],t.shape[2]])),f(s.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${s.shape}.`),f(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),f(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const p=o==="NHWC"?s.shape[3]:s.shape[1],l=o==="NHWC"?c.shape[3]:c.shape[1];f(p===n[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${n[2]}.`),f(l===n[3],()=>`Error in conv2dDerFilter: depth of dy (${l}) must match output depth for filter (${n[3]}).`),a!=null&&f(J(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const u=y=>{const w=1,L=Sn(o),T=We(s.shape,n,r,w,i,a,!1,L);return y.conv2dDerFilter(s,c,T)},m={x:s,dy:c},b={strides:r,pad:i,dataFormat:o,dimRoundingMode:a};return g.runKernelFunc(u,m,null,Gu,b)}const ci=d({conv2DBackpropFilter_:SE});function ur(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return v(e,vt(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function hr(e,t){let n=t;const r=ie(e.shape,t.shape);return r.length>0&&(n=U(n,r)),x(n,e.shape)}function dr(e,t,n){if(t==="linear")return e;if(t==="relu")return zt(e);if(t==="elu")return Ei(e);if(t==="relu6")return xi(e);if(t==="prelu")return vi(e,n);throw new Error(`Unknown fused activation ${t}.`)}const mr=(e,t)=>{const n=e>0;return!n||t==="linear"};function TE({x:e,filter:t,strides:n,pad:r,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(c=c||"linear",mr(g.state.gradientDepth,c)===!1){let C=It(e,t,n,r,i,o,a);return s!=null&&(C=O(C,s)),dr(C,c,p)}const l=h(e,"x","conv2d"),u=h(t,"filter","conv2d");let m=l,b=!1;l.rank===3&&(b=!0,m=x(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(m.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${m.rank}.`),f(u.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${u.rank}.`),a!=null&&f(J(r),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(m.shape[3]===u.shape[2],()=>`Error in conv2d: depth of input (${m.shape[3]}) must match input depth for filter ${u.shape[2]}.`),f(ae(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),f(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const y=We(m.shape,u.shape,n,o,r,a);let w;s!=null&&(w=h(s,"bias","fused conv2d"),[w]=V(w,l),H(y.outShape,w.shape));let L;p!=null&&(L=h(p,"prelu weights","fused conv2d"));const T=(C,F)=>{const[E,B,q,P]=F,te=ur(C,q,c);f(ut(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const ne=ai(B.shape,te,E,n,r),pe=ci(B,te,E.shape,n,r),Se=[ne,pe];if(P!=null){const qe=hr(P,te);Se.push(qe)}return Se},A=C=>{const F=C.fusedConv2d({input:m,filter:u,convInfo:y,bias:w,activation:c,preluActivationWeights:L});return F},_={x:m,filter:u,bias:w,preluActivationWeights:L},N={strides:n,pad:r,dataFormat:i,dilations:o,dimRoundingMode:a,activation:c};if(s==null){const C=$e((F,E,B)=>{let q=g.runKernelFunc(A,_,null,oa,N);return B([E,F,q]),b&&(q=x(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:T}});return C(m,u)}else{const C=$e((F,E,B,q)=>{let P=g.runKernelFunc(A,_,null,oa,N);return q([E,F,P,B]),b&&(P=x(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:T}});return C(m,u,w)}}const IE=d({fusedConv2d_:TE});function AE(e,t,n,r){let i=e;e.rank===3&&(i=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let o=t;o.rank===3&&(o=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=c=>c.depthwiseConv2DDerFilter(i,o,r),s={x:i,dy:o};return g.runKernelFunc(a,s,null,Vu)}const Pp=d({depthwiseConv2dNativeBackpropFilter_:AE});function NE(e,t,n,r){let i=t,o=!1;t.rank===3&&(o=!0,i=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(i,n,r),s={dy:i},c=g.runKernelFunc(a,s,null,Ku);return o?x(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const jp=d({depthwiseConv2dNativeBackpropInput_:NE});function _E({x:e,filter:t,strides:n,pad:r,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(mr(g.state.gradientDepth,c)===!1){let C=zn(e,t,n,r,i,o,a);return s!=null&&(C=O(C,s)),dr(C,c,p)}const l=h(e,"x","depthwiseConv2d"),u=h(t,"filter","depthwiseConv2d");let m=l,b=!1;l.rank===3&&(b=!0,m=x(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(m.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`),f(u.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),f(m.shape[3]===u.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${m.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),o==null&&(o=[1,1]),f(ae(n,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),a!=null&&f(J(r),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${r}.`);const y=We(m.shape,u.shape,n,o,r,a,!0);let w;s!=null&&(w=h(s,"bias","fused conv2d"),[w]=V(w,l),H(y.outShape,w.shape));let L;p!=null&&(L=h(p,"prelu weights","fused depthwiseConv2d"));const T=(C,F)=>{f(ut(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[E,B,q,P]=F,te=ur(C,q,c),ne=jp(B.shape,te,E,y),pe=Pp(B,te,E.shape,y);if(P!=null){const Se=hr(w,te);return[ne,pe,Se]}return[ne,pe]},A=C=>{const F=C.fusedDepthwiseConv2D({input:m,filter:u,convInfo:y,bias:w,activation:c,preluActivationWeights:L});return F},_={x:m,filter:u,bias:w,preluActivationWeights:L},N={strides:n,pad:r,dataFormat:i,dilations:o,dimRoundingMode:a,activation:c};if(s==null){const C=$e((F,E,B)=>{let q=g.runKernelFunc(A,_,null,sa,N);return B([E,F,q]),b&&(q=x(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:T}});return C(m,u)}else{const C=$e((F,E,B,q)=>{let P=g.runKernelFunc(A,_,null,sa,N);return q([E,F,P,B]),b&&(P=x(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:T}});return C(m,u,w)}}const RE=d({fusedDepthwiseConv2d_:_E});function CE({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:i,activation:o="linear",preluActivationWeights:a}){if(mr(g.state.gradientDepth,o)===!1){let P=K(e,t,n,r);return i!=null&&(P=O(P,i)),dr(P,o,a)}let s=h(e,"a","fused matMul"),c=h(t,"b","fused matMul");[s,c]=V(s,c);const p=n?s.shape[s.rank-2]:s.shape[s.rank-1],l=r?c.shape[c.rank-1]:c.shape[c.rank-2],u=n?s.shape[s.rank-1]:s.shape[s.rank-2],m=r?c.shape[c.rank-2]:c.shape[c.rank-1],b=s.shape.slice(0,-2),y=c.shape.slice(0,-2),w=Z(b),L=Z(y);f(s.rank>=2&&c.rank>=2&&s.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${s.rank} and ${c.rank}.`),f(Le(b,y),()=>`Error in fused matMul: outer dimensions (${b}) and (${y}) of Tensors with shapes ${s.shape} and ${c.shape} must match.`),f(p===l,()=>`Error in fused matMul: inner shapes (${p}) and (${l}) of Tensors with shapes ${s.shape} and ${c.shape} and transposeA=${n} and transposeB=${r} must match.`);const T=s.shape.slice(0,-2).concat([u,m]),A=n?x(s,[w,p,u]):x(s,[w,u,p]),_=r?x(c,[L,m,l]):x(c,[L,l,m]);let N;i!=null&&(N=h(i,"bias","fused matMul"),[N]=V(N,s),H(T,N.shape));let C;a!=null&&(C=h(a,"prelu weights","fused matMul"));const F=(P,te)=>{const[ne,pe,Se,qe]=te,Gt=ur(x(P,Se.shape),Se,o);let gr,br;if(!n&&!r?(gr=K(Gt,pe,!1,!0),br=K(ne,Gt,!0,!1)):!n&&r?(gr=K(Gt,pe,!1,!1),br=K(Gt,ne,!0,!1)):n&&!r?(gr=K(pe,Gt,!1,!0),br=K(ne,Gt,!1,!1)):(gr=K(pe,Gt,!0,!0),br=K(Gt,ne,!0,!0)),i!=null){const vv=hr(qe,Gt);return[gr,br,vv]}else return[gr,br]},E=P=>{const te=P.fusedBatchMatMul({a:A,b:_,transposeA:n,transposeB:r,bias:N,activation:o,preluActivationWeights:C});return te},B={a:A,b:_,bias:N,preluActivationWeights:C},q={transposeA:n,transposeB:r,activation:o};if(i==null){const P=$e((te,ne,pe)=>{const Se=g.runKernelFunc(E,B,null,ia,q);return pe([te,ne,Se]),{value:x(Se,T),gradFunc:F}});return P(A,_)}else{const P=$e((te,ne,pe,Se)=>{const qe=g.runKernelFunc(E,B,null,ia,q);return Se([te,ne,qe,pe]),{value:x(qe,T),gradFunc:F}});return P(A,_,N)}}const EE=d({fusedMatMul_:CE});const nu={};Oe(nu,{conv2d:()=>IE,depthwiseConv2d:()=>RE,matMul:()=>EE});function OE(e){return Lr(e,.54,.46)}const Yy=d({hammingWindow_:OE});function kE(e){return Lr(e,.5,.5)}const Gp=d({hannWindow_:kE});function DE(e,t,n,r=!1,i=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(Y(e,o,t)),o+=n;if(r)for(;o<e.size;){const s=o+t-e.size,c=re([Y(e,o,t-s),Hn([s],i)]);a.push(c),o+=n}return a.length===0?Yt([],[0,t]):x(re(a),[a.length,t])}const $p=d({frame_:DE});function FE(e,t,n,r,i=Gp){r==null&&(r=Qs(t));const o=$p(e,t,n),a=v(o,i(t)),s=[];for(let c=0;c<o.shape[0];c++)s.push(Wn(Y(a,[c,0],[1,t]),r));return re(s)}const zy=d({stft_:FE});function ME(e,t,n,r,i,o){const a=h(e,"image","cropAndResize"),s=h(t,"boxes","cropAndResize","float32"),c=h(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;const p=s.shape[0];f(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),f(s.rank===2&&s.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${s.shape}.`),f(c.rank===1&&c.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${s.shape}.`),f(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),f(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),f(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const l=y=>y.cropAndResize(a,s,c,r,i,o),u={image:a,boxes:s,boxInd:c},m={method:i,extrapolationValue:o,cropSize:r},b=g.runKernelFunc(l,u,null,Yu,m);return b}const Vy=d({cropAndResize_:ME});function UE(e){const t=h(e,"image","flipLeftRight","float32");f(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},r=g.runKernel(rh,n,{});return r}const Ky=d({flipLeftRight_:UE});function WE(e,t,n=0,r=.5){const i=h(e,"image","rotateWithOffset","float32");f(i.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${i.rank}.`);const o={image:i},a={radians:t,fillValue:n,center:r},s=g.runKernel(Oh,o,a);return s}const Jy=d({rotateWithOffset_:WE});function Lt(e,t,n,r,i,o){r==null&&(r=.5),i==null&&(i=Number.NEGATIVE_INFINITY),o==null&&(o=0);const a=e.shape[0];return n=Math.min(n,a),f(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),f(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),f(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),f(t.rank===1,()=>"scores must be a 1D tensor"),f(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),f(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i,softNmsSigma:o}}function qE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY){const o=h(e,"boxes","nonMaxSuppression"),a=h(t,"scores","nonMaxSuppression"),s=Lt(o,a,n,r,i);n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold;const c={maxOutputSize:n,iouThreshold:r,scoreThreshold:i};return g.runKernelFunc(p=>p.nonMaxSuppression(o,a,n,r,i),{boxes:o,scores:a},null,yh,c)}const Xy=d({nonMaxSuppression_:qE});function Zy(e,t,n){const r=BE(e,t,n),i=r<0?-(r+1):r;e.splice(i,0,t)}function BE(e,t,n){return jE(e,t,n||PE)}function PE(e,t){return e>t?1:e<t?-1:0}function jE(e,t,n){let r=0,i=e.length,o=0,a=!1;for(;r<i;){o=r+(i-r>>>1);const s=n(t,e[o]);s>0?r=o+1:(i=o,a=!s)}return a?r:-r-1}function Hp(e,t,n,r,i){return Ym(e,t,n,r,i,0).selectedIndices}function Yp(e,t,n,r,i,o){return Ym(e,t,n,r,i,0,!1,o,!0)}function zp(e,t,n,r,i,o){return Ym(e,t,n,r,i,o,!0)}function Ym(e,t,n,r,i,o,a=!1,s=!1,c=!1){const p=[];for(let L=0;L<t.length;L++)t[L]>i&&p.push({score:t[L],boxIndex:L,suppressBeginIndex:0});p.sort(Qy);const l=o>0?-.5/o:0,u=[],m=[];for(;u.length<n&&p.length>0;){const L=p.pop(),{score:T,boxIndex:A,suppressBeginIndex:_}=L;if(T<i)break;let N=!1;for(let C=u.length-1;C>=_;--C){const F=GE(e,A,u[C]);if(F>=r){N=!0;break}if(L.score=L.score*$E(r,l,F),L.score<=i)break}L.suppressBeginIndex=u.length,N||(L.score===T?(u.push(A),m.push(L.score)):L.score>i&&Zy(p,L,Qy))}const b=u.length,y=n-b;s&&y>0&&(u.push(...new Array(y).fill(0)),m.push(...new Array(y).fill(0)));const w={selectedIndices:ht(u,"int32")};return a&&(w.selectedScores=ht(m,"float32")),c&&(w.validOutputs=k(b,"int32")),w}function GE(e,t,n){const r=e.subarray(t*4,t*4+4),i=e.subarray(n*4,n*4+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),p=Math.min(i[0],i[2]),l=Math.min(i[1],i[3]),u=Math.max(i[0],i[2]),m=Math.max(i[1],i[3]),b=(s-o)*(c-a),y=(u-p)*(m-l);if(b<=0||y<=0)return 0;const w=Math.max(o,p),L=Math.max(a,l),T=Math.min(s,u),A=Math.min(c,m),_=Math.max(T-w,0)*Math.max(A-L,0);return _/(b+y-_)}function $E(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Qy(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function HE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY){const o=h(e,"boxes","nonMaxSuppressionAsync"),a=h(t,"scores","nonMaxSuppressionAsync"),s=Lt(o,a,n,r,i);n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold;const c=await Promise.all([o.data(),a.data()]),p=c[0],l=c[1],u=Hp(p,l,n,r,i);return o!==e&&o.dispose(),a!==t&&a.dispose(),u}const ex=HE;function YE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=h(e,"boxes","nonMaxSuppression"),s=h(t,"scores","nonMaxSuppression"),c=Lt(a,s,n,r,i,o);n=c.maxOutputSize,r=c.iouThreshold,i=c.scoreThreshold,o=c.softNmsSigma;const p={boxes:a,scores:s},l={maxOutputSize:n,iouThreshold:r,scoreThreshold:i,softNmsSigma:o},u=g.runKernel(Lh,p,l);return{selectedIndices:u[0],selectedScores:u[1]}}const tx=d({nonMaxSuppressionWithScore_:YE});async function zE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=h(e,"boxes","nonMaxSuppressionAsync"),s=h(t,"scores","nonMaxSuppressionAsync"),c=Lt(a,s,n,r,i,o);n=c.maxOutputSize,r=c.iouThreshold,i=c.scoreThreshold,o=c.softNmsSigma;const p=await Promise.all([a.data(),s.data()]),l=p[0],u=p[1],m=zp(l,u,n,r,i,o);return a!==e&&a.dispose(),s!==t&&s.dispose(),m}const nx=zE;function VE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=h(e,"boxes","nonMaxSuppression"),s=h(t,"scores","nonMaxSuppression"),c=Lt(a,s,n,r,i,null),p=c.maxOutputSize,l=c.iouThreshold,u=c.scoreThreshold,m={boxes:a,scores:s},b={maxOutputSize:p,iouThreshold:l,scoreThreshold:u,padToMaxOutputSize:o},y=g.runKernel(xh,m,b);return{selectedIndices:y[0],validOutputs:y[1]}}const rx=d({nonMaxSuppressionPadded_:VE});async function KE(e,t,n,r=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=h(e,"boxes","nonMaxSuppressionAsync"),s=h(t,"scores","nonMaxSuppressionAsync"),c=Lt(a,s,n,r,i,null),p=c.maxOutputSize,l=c.iouThreshold,u=c.scoreThreshold,[m,b]=await Promise.all([a.data(),s.data()]),y=Yp(m,b,p,l,u,o);return a!==e&&a.dispose(),s!==t&&s.dispose(),y}const ix=KE;function JE(e,t,n=!1){const r=h(e,"images","resizeBilinear");f(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let i=r,o=!1;r.rank===3&&(o=!0,i=x(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c=(m,b)=>(b([i]),m.resizeBilinear(i,a,s,n)),p={images:i},l={alignCorners:n,size:t},u=g.runKernelFunc(c,p,null,Yo,l);return o?x(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const ox=d({resizeBilinear_:JE});function XE(e,t,n=!1){const r=h(e,"images","resizeNearestNeighbor");f(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),f(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let i=r,o=!1;r.rank===3&&(o=!0,i=x(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c={images:i},p={alignCorners:n,size:t},l=(m,b)=>(b([i]),m.resizeNearestNeighbor(i,a,s,n)),u=g.runKernelFunc(l,c,null,Ho,p);return o?x(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const sx=d({resizeNearestNeighbor_:XE});function ZE(e,t,n){f(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),f(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const r=h(e,"a","bandPart");f(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const i=r.shape,[o,a]=r.shape.slice(-2);if(!(t<=o))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${o}).`);if(!(n<=a))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`);t<0&&(t=o),n<0&&(n=a);const s=x(vr(0,o,1,"int32"),[-1,1]),c=vr(0,a,1,"int32"),p=D(s,c),l=ft(at(p,k(+t,"int32")),ct(p,k(-n,"int32"))),u=Ue([o,a],r.dtype);return x(dt(Dn(x(r,[-1,o,a])).map(m=>Ae(l,m,u))),i)}const ax=d({bandPart_:ZE});function QE(e){let t;if(Array.isArray(e)){t=!1,f(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const i=e[0].shape[0];for(let o=1;o<e.length;++o)f(e[o].shape[0]===i,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[o].shape[0]} vs. ${i})`)}else t=!0,e=Ot(e,e.shape[0],0).map(i=>Fn(i,[0]));f(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let i=0;i<e.length;++i)n.push(g.tidy(()=>{let o=r[i];if(i>0)for(let a=0;a<i;++a){const s=v(U(v(n[a],o)),n[a]);o=D(o,s)}return M(o,Tr(o,"euclidean"))}));return t?dt(n,0):n}const cx=d({gramSchmidt_:QE});function eO(e,t=!1){if(f(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return px(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((c,p)=>c*p),r=Dn(x(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];r.forEach(c=>{const[p,l]=px(c,t);i.push(p),o.push(l)});const a=x(dt(i,0),e.shape),s=x(dt(o,0),e.shape);return[a,s]}}function px(e,t=!1){return g.tidy(()=>{f(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let i=Ci(n),o=At(e);const a=Yt([[1]],[1,1]);let s=At(a);const c=n>=r?r:n;for(let p=0;p<c;++p){const l=o,u=s,m=i;[s,o,i]=g.tidy(()=>{const b=Y(o,[p,p],[n-p,1]),y=Tr(b),w=Y(o,[p,p],[1,1]),L=Ae(Ve(w,0),Yt([[-1]]),Yt([[1]])),T=D(w,v(L,y)),A=M(b,T);A.shape[0]===1?s=At(a):s=re([a,Y(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);const _=Q(M(K(L,T),y)),N=Y(o,[p,0],[n-p,r]),C=v(_,s),F=X(s);if(p===0)o=D(N,K(C,K(F,N)));else{const q=D(N,K(C,K(F,N)));o=re([Y(o,[0,0],[p,r]),q],0)}const E=X(C),B=Y(i,[0,p],[n,i.shape[1]-p]);if(p===0)i=D(B,K(K(B,s),E));else{const q=D(B,K(K(B,s),E));i=re([Y(i,[0,0],[n,p]),q],1)}return[s,o,i]}),be([l,u,m])}return!t&&n>r&&(i=Y(i,[0,0],[n,r]),o=Y(o,[0,0],[r,r])),[i,o]})}const lx=d({qr_:eO});var ue;(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"})(ue||(ue={}));function tO(e,t,n=ue.SUM_BY_NONZERO_WEIGHTS){const r=h(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=h(t,"weights","computeWeightedLoss"));const o=i==null?r:v(r,i);if(n===ue.NONE)return o;if(n===ue.SUM)return U(o);if(n===ue.MEAN){if(i==null)return an(o);{const a=r.size/i.size,s=M(U(o),U(i));return a>1?M(s,k(a)):s}}if(n===ue.SUM_BY_NONZERO_WEIGHTS){if(i==null)return M(U(o),k(r.size));{const a=v(i,mt(r.shape)),s=R(U(qn(a,k(0))),"float32");return M(U(o),s)}}throw Error(`Unknown reduction: ${n}`)}const Me=d({computeWeightedLoss_:tO});function nO(e,t,n,r=ue.SUM_BY_NONZERO_WEIGHTS){const i=h(e,"labels","absoluteDifference"),o=h(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=h(n,"weights","absoluteDifference")),$(i.shape,o.shape,"Error in absoluteDifference: ");const s=_e(D(i,o));return Me(s,a,r)}const ux=d({absoluteDifference_:nO});function rO(e,t,n,r,i=ue.SUM_BY_NONZERO_WEIGHTS){const o=h(e,"labels","cosineDistance"),a=h(t,"predictions","cosineDistance");let s=null;r!=null&&(s=h(r,"weights","cosineDistance")),$(o.shape,a.shape,"Error in cosineDistance: ");const c=k(1),p=D(c,U(v(o,a),n,!0));return Me(p,s,i)}const hx=d({cosineDistance_:rO});function iO(e,t,n,r=ue.SUM_BY_NONZERO_WEIGHTS){let i=h(e,"labels","hingeLoss");const o=h(t,"predictions","hingeLoss");let a=null;n!=null&&(a=h(n,"weights","hingeLoss")),$(i.shape,o.shape,"Error in hingeLoss: ");const s=k(1);i=D(v(k(2),i),s);const c=zt(D(s,v(i,o)));return Me(c,a,r)}const dx=d({hingeLoss_:iO});function oO(e,t,n,r=1,i=ue.SUM_BY_NONZERO_WEIGHTS){const o=h(e,"labels","huberLoss"),a=h(t,"predictions","huberLoss");let s=null;n!=null&&(s=h(n,"weights","huberLoss")),$(o.shape,a.shape,"Error in huberLoss: ");const c=k(r),p=_e(D(a,o)),l=Bn(p,c),u=D(p,l),m=O(v(k(.5),G(l)),v(c,u));return Me(m,s,i)}const mx=d({huberLoss_:oO});function sO(e,t,n,r=1e-7,i=ue.SUM_BY_NONZERO_WEIGHTS){const o=h(e,"labels","logLoss"),a=h(t,"predictions","logLoss");let s=null;n!=null&&(s=h(n,"weights","logLoss")),$(o.shape,a.shape,"Error in logLoss: ");const c=k(1),p=k(r),l=Q(v(o,gt(O(a,p)))),u=v(D(c,o),gt(O(D(c,a),p))),m=D(l,u);return Me(m,s,i)}const fx=d({logLoss_:sO});function aO(e,t,n,r=ue.SUM_BY_NONZERO_WEIGHTS){const i=h(e,"labels","meanSquaredError"),o=h(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=h(n,"weights","meanSquaredError")),$(i.shape,o.shape,"Error in meanSquaredError: ");const s=Mn(i,o);return Me(s,a,r)}const gx=d({meanSquaredError_:aO});function cO(e,t){const n=h(e,"labels","sigmoidCrossEntropyWithLogits"),r=h(t,"logits","sigmoidCrossEntropyWithLogits");$(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=zt(r),o=v(r,n),a=Ni(Ne(Q(_e(r))));return O(D(i,o),a)}function pO(e,t,n,r=0,i=ue.SUM_BY_NONZERO_WEIGHTS){let o=h(e,"multiClassLabels","sigmoidCrossEntropy");const a=h(t,"logits","sigmoidCrossEntropy");let s=null;if(n!=null&&(s=h(n,"weights","sigmoidCrossEntropy")),$(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){const p=k(r),l=k(1),u=k(.5);o=O(v(o,D(l,p)),v(u,p))}const c=cO(o,a);return Me(c,s,i)}const bx=d({sigmoidCrossEntropy_:pO});function lO(e,t,n=-1){if(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}`);const r=$e((i,o,a)=>{const s=!0,c=Ai(o,[n],s),p=D(R(o,"float32"),c);a([i,p]);const l=Q(v(p,i)),u=U(l,[n]),m=(b,y)=>{const[w,L]=y,T=fe(b.shape,[n]);return[v(x(b,T),D(R(w,"float32"),Ne(L))),v(x(b,T),D(Ne(L),R(w,"float32")))]};return{value:u,gradFunc:m}});return r(e,t)}function uO(e,t,n,r=0,i=ue.SUM_BY_NONZERO_WEIGHTS){let o=h(e,"onehotLabels","softmaxCrossEntropy");const a=h(t,"logits","softmaxCrossEntropy");let s=null;if(n!=null&&(s=h(n,"weights","softmaxCrossEntropy")),$(o.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){const p=k(r),l=k(1),u=k(o.shape[1]);o=O(v(o,D(l,p)),M(p,u))}const c=lO(o,a);return Me(c,s,i)}const wx=d({softmaxCrossEntropy_:uO});const zm={};Oe(zm,{abs:()=>_e,acos:()=>Mu,acosh:()=>Fu,add:()=>O,addN:()=>Du,addStrict:()=>eg,all:()=>ku,any:()=>Ou,argMax:()=>Eu,argMin:()=>Cu,asin:()=>Ru,asinh:()=>_u,atan:()=>Nu,atan2:()=>Au,atanh:()=>Iu,avgPool:()=>Di,avgPool3d:()=>Tu,basicLSTMCell:()=>Su,batchNorm:()=>Jt,batchNorm2d:()=>vu,batchNorm3d:()=>Lu,batchNorm4d:()=>xu,batchToSpaceND:()=>Kn,booleanMaskAsync:()=>Qf,broadcastTo:()=>Ir,buffer:()=>ke,cast:()=>R,ceil:()=>yu,clipByValue:()=>wu,clone:()=>At,complex:()=>Ge,concat:()=>re,concat1d:()=>bu,concat2d:()=>gu,concat3d:()=>fu,concat4d:()=>mu,conv1d:()=>du,conv2d:()=>It,conv2dTranspose:()=>hu,conv3d:()=>uu,conv3dTranspose:()=>lu,cos:()=>Vn,cosh:()=>ki,cosineWindow:()=>Lr,cumsum:()=>Oi,depthToSpace:()=>pu,depthwiseConv2d:()=>zn,diag:()=>cu,dilation2d:()=>au,div:()=>M,divNoNan:()=>su,divStrict:()=>tg,dot:()=>ou,dropout:()=>Hf,elu:()=>Ei,enclosingPowerOfTwo:()=>Qs,equal:()=>Kt,equalStrict:()=>Yf,erf:()=>iu,exp:()=>Ne,expandDims:()=>Ke,expm1:()=>ru,eye:()=>Ci,fft:()=>Yn,fill:()=>Hn,floor:()=>$n,floorDiv:()=>Ri,fused:()=>nu,gather:()=>Gn,gatherND:()=>$f,greater:()=>Ve,greaterEqual:()=>ct,greaterEqualStrict:()=>zf,greaterStrict:()=>Vf,ifft:()=>cn,imag:()=>Vt,image:()=>Wf,inTopKAsync:()=>jf,irfft:()=>_i,isFinite:()=>tu,isInf:()=>eu,isNaN:()=>Ql,leakyRelu:()=>Zl,less:()=>jn,lessEqual:()=>at,lessEqualStrict:()=>Kf,lessStrict:()=>Jf,linalg:()=>qf,linspace:()=>Xl,localResponseNormalization:()=>Jl,log:()=>gt,log1p:()=>Ni,logSigmoid:()=>Kl,logSoftmax:()=>Vl,logSumExp:()=>Ai,logicalAnd:()=>ft,logicalNot:()=>Pn,logicalOr:()=>Ii,logicalXor:()=>zl,losses:()=>Bf,matMul:()=>K,max:()=>st,maxPool:()=>Ti,maxPool3d:()=>Yl,maxPoolWithArgmax:()=>Hl,maximum:()=>Tt,maximumStrict:()=>ng,mean:()=>an,min:()=>sn,minimum:()=>Bn,minimumStrict:()=>rg,mod:()=>Si,modStrict:()=>ig,moments:()=>$l,movingAverage:()=>Pf,mul:()=>v,mulStrict:()=>og,multiRNNCell:()=>Gl,multinomial:()=>jl,neg:()=>Q,norm:()=>Tr,notEqual:()=>qn,notEqualStrict:()=>Xf,oneHot:()=>Sr,ones:()=>mt,onesLike:()=>ea,op:()=>d,outerProduct:()=>Pl,pad:()=>ot,pad1d:()=>Bl,pad2d:()=>ql,pad3d:()=>Wl,pad4d:()=>Ul,pool:()=>Ml,pow:()=>je,powStrict:()=>sg,prelu:()=>vi,print:()=>Fl,prod:()=>Dl,rand:()=>kl,randomGamma:()=>Ol,randomNormal:()=>El,randomUniform:()=>Li,range:()=>vr,real:()=>kt,reciprocal:()=>Cl,relu:()=>zt,relu6:()=>xi,reshape:()=>x,reverse:()=>Pe,reverse1d:()=>Rl,reverse2d:()=>_l,reverse3d:()=>Nl,reverse4d:()=>Al,rfft:()=>Wn,round:()=>Il,rsqrt:()=>yi,scalar:()=>k,scatterND:()=>Ff,selu:()=>Tl,separableConv2d:()=>Sl,setdiff1dAsync:()=>vl,sigmoid:()=>St,sign:()=>Ll,signal:()=>Uf,sin:()=>wi,sinh:()=>bi,slice:()=>Y,slice1d:()=>xl,slice2d:()=>yl,slice3d:()=>wl,slice4d:()=>bl,softmax:()=>gl,softplus:()=>gi,spaceToBatchND:()=>Un,sparseToDense:()=>Of,spectral:()=>Mf,split:()=>Ot,sqrt:()=>le,square:()=>G,squaredDifference:()=>Mn,squaredDifferenceStrict:()=>ag,squeeze:()=>Fn,stack:()=>dt,step:()=>vt,stridedSlice:()=>fl,sub:()=>D,subStrict:()=>cg,sum:()=>U,tan:()=>ml,tanh:()=>xr,tensor:()=>Qe,tensor1d:()=>ht,tensor2d:()=>Yt,tensor3d:()=>fi,tensor4d:()=>dl,tensor5d:()=>hl,tensor6d:()=>ul,tile:()=>Ht,topk:()=>ll,transpose:()=>X,truncatedNormal:()=>pl,unsortedSegmentSum:()=>mi,unstack:()=>Dn,variable:()=>cl,where:()=>Ae,whereAsync:()=>di,zeros:()=>Ue,zerosLike:()=>W});const Mf={fft:Yn,ifft:cn,rfft:Wn,irfft:_i},Uf={hammingWindow:Yy,hannWindow:Gp,frame:$p,stft:zy},Wf={flipLeftRight:Ky,resizeNearestNeighbor:sx,resizeBilinear:ox,rotateWithOffset:Jy,cropAndResize:Vy,nonMaxSuppression:Xy,nonMaxSuppressionAsync:ex,nonMaxSuppressionWithScore:tx,nonMaxSuppressionWithScoreAsync:nx,nonMaxSuppressionPadded:rx,nonMaxSuppressionPaddedAsync:ix},qf={bandPart:ax,gramSchmidt:cx,qr:lx},Bf={absoluteDifference:ux,computeWeightedLoss:Me,cosineDistance:hx,hingeLoss:dx,huberLoss:mx,logLoss:fx,meanSquaredError:gx,sigmoidCrossEntropy:bx,softmaxCrossEntropy:wx};_y(zm);const Vs={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Vp=4;async function dO(e,t){const n=[],r=[],i=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a<i.length;++a){const s=i[a],c=Array.isArray(e)?e[a].tensor:e[s];if(c.dtype!=="float32"&&c.dtype!=="int32"&&c.dtype!=="bool"&&c.dtype!=="string"&&c.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${s}': ${c.dtype}`);const p={name:s,shape:c.shape,dtype:c.dtype};if(c.dtype==="string"){const l=new Promise(async u=>{const m=await c.bytes(),b=m.reduce((L,T)=>L+T.length,0)+Vp*m.length,y=new Uint8Array(b);let w=0;for(let L=0;L<m.length;L++){const T=m[L],A=new Uint8Array(new Uint32Array([T.length]).buffer);y.set(A,w),w+=Vp,y.set(T,w),w+=T.length}u(y)});r.push(l)}else r.push(c.data());t!=null&&(p.group=t),n.push(p)}const o=await Promise.all(r);return{data:hO(o),specs:n}}function Vm(e,t){const n={};let r,i=0;for(const o of t){const a=o.name,s=o.dtype,c=o.shape,p=Z(c);let l;if("quantization"in o){const u=o.quantization;if(u.dtype==="uint8"||u.dtype==="uint16"){if(!("min"in u&&"scale"in u))throw new Error(`Weight ${o.name} with quantization ${u.dtype} doesn't have corresponding metadata min and scale.`)}else if(u.dtype==="float16"){if(s!=="float32")throw new Error(`Weight ${o.name} is quantized with ${u.dtype} which only supports weights of type float32 not ${s}.`)}else throw new Error(`Weight ${o.name} has unknown quantization dtype ${u.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const m=Vs[u.dtype],b=e.slice(i,i+p*m),y=u.dtype==="uint8"?new Uint8Array(b):new Uint16Array(b);if(s==="float32")if(u.dtype==="uint8"||u.dtype==="uint16"){l=new Float32Array(y.length);for(let w=0;w<y.length;w++){const L=y[w];l[w]=L*u.scale+u.min}}else if(u.dtype==="float16")r===void 0&&(r=mO()),l=r(y);else throw new Error(`Unsupported quantization type ${u.dtype} for weight type float32.`);else if(s==="int32"){if(u.dtype!=="uint8"&&u.dtype!=="uint16")throw new Error(`Unsupported quantization type ${u.dtype} for weight type int32.`);l=new Int32Array(y.length);for(let w=0;w<y.length;w++){const L=y[w];l[w]=Math.round(L*u.scale+u.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);i+=p*m}else if(s==="string"){const u=Z(o.shape);l=[];for(let m=0;m<u;m++){const b=new Uint32Array(e.slice(i,i+Vp))[0];i+=Vp;const y=new Uint8Array(e.slice(i,i+b));l.push(y),i+=b}}else{const u=Vs[s],m=e.slice(i,i+p*u);if(s==="float32")l=new Float32Array(m);else if(s==="int32")l=new Int32Array(m);else if(s==="bool")l=new Uint8Array(m);else if(s==="complex64"){l=new Float32Array(m);const b=new Float32Array(l.length/2),y=new Float32Array(l.length/2);for(let T=0;T<b.length;T++)b[T]=l[T*2],y[T]=l[T*2+1];const w=Qe(b,c,"float32"),L=Qe(y,c,"float32");n[a]=Ge(w,L)}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);i+=p*u}s!=="complex64"&&(n[a]=Qe(l,c,s))}return n}function hO(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(o=>{if(t+=o.byteLength,n.push(o.byteLength===o.buffer.byteLength?o:new o.constructor(o)),!(o instanceof Float32Array||o instanceof Int32Array||o instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${o.constructor.name}`)});const r=new Uint8Array(t);let i=0;return n.forEach(o=>{r.set(new Uint8Array(o.buffer),i),i+=o.byteLength}),r.buffer}const fO=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function yx(e){return fO?Buffer.byteLength(e):new Blob([e]).size}function Ks(e){if(e.length===1)return e[0];let t=0;e.forEach(i=>{t+=i.byteLength});const n=new Uint8Array(t);let r=0;return e.forEach(i=>{n.set(new Uint8Array(i),r),r+=i.byteLength}),n.buffer}function Km(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const n=e.split(t);return n[n.length-1]}function Js(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date(),modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:yx(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:yx(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function gO(){const e=n=>{let r=n<<13,i=0;for(;(r&8388608)===0;)i-=8388608,r<<=1;return r&=~8388608,i+=947912704,r|i},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function bO(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function wO(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function mO(){const e=gO(),t=bO(),n=wO();return r=>{const i=new ArrayBuffer(4*r.length),o=new Uint32Array(i);for(let a=0;a<r.length;a++){const s=r[a],c=e[n[s>>10]+(s&1023)]+t[s>>10];o[a]=c}return new Float32Array(i)}}class ve{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return ve.instance==null&&(ve.instance=new ve()),ve.instance}static registerSaveRouter(e){ve.getInstance().saveRouters.push(e)}static registerLoadRouter(e){ve.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return ve.getHandlers(e,"save")}static getLoadHandlers(e,t){return ve.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[],i=t==="load"?ve.getInstance().loadRouters:ve.getInstance().saveRouters;return i.forEach(o=>{const a=o(e,n);a!==null&&r.push(a)}),r}}const yO=e=>ve.registerSaveRouter(e),xO=e=>ve.registerLoadRouter(e),LO=e=>ve.getSaveHandlers(e),vO=(e,t)=>ve.getLoadHandlers(e,t);const pi="://";class Et{constructor(){this.managers={}}static getInstance(){return Et.instance==null&&(Et.instance=new Et()),Et.instance}static registerManager(e,t){f(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(pi)&&(e=e.slice(0,e.indexOf(pi))),f(e.length>0,()=>"scheme must not be an empty string.");const n=Et.getInstance();f(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function Kp(e){if(e.indexOf(pi)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Et.getSchemes().join(",")}`);return{scheme:e.split(pi)[0],path:e.split(pi)[1]}}async function xx(e,t,n=!1){f(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=ve.getLoadHandlers(e);f(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),f(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const i=r[0],o=ve.getSaveHandlers(t);f(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),f(o.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const a=o[0],s=Kp(e).scheme,c=Kp(e).path,p=s===Kp(e).scheme,l=await i.load();n&&p&&await Et.getManager(s).removeModel(c);const u=await a.save(l);return n&&!p&&await Et.getManager(s).removeModel(c),u.modelArtifactsInfo}async function Lx(){const e=Et.getSchemes(),t={};for(const n of e){const r=await Et.getManager(n).listModels();for(const i in r){const o=n+pi+i;t[o]=r[i]}}return t}async function vx(e){const t=Kp(e),n=Et.getManager(t.scheme);return n.removeModel(t.path)}async function Sx(e,t){const n=!1;return xx(e,t,n)}async function Tx(e,t){const n=!0;return xx(e,t,n)}const SO="model",TO=".json",IO=".weights.bin";function Ix(e){return new Promise(t=>setTimeout(t)).then(e)}class li{constructor(e){if(!se().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(li.URL_SCHEME)&&(e=e.slice(li.URL_SCHEME.length)),(e==null||e.length===0)&&(e=SO),this.modelTopologyFileName=e+TO,this.weightDataFileName=e+IO}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const 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"})),o=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(o.download=this.modelTopologyFileName,o.href=i,await Ix(()=>o.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await Ix(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Js(e)}}}}li.URL_SCHEME="downloads://";class AO{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,r)=>{const i=new FileReader();i.onload=o=>{const a=JSON.parse(o.target.result),s=a.modelTopology;if(s==null){r(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:s});const c=a.weightsManifest;if(c==null){r(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(c,t)}catch(b){r(b);return}const l=[],u=[],m=[];c.forEach(b=>{b.paths.forEach(y=>{u.push(y),m.push(null)}),l.push(...b.weights)}),c.forEach(b=>{b.paths.forEach(y=>{const w=new FileReader();w.onload=L=>{const T=L.target.result,A=u.indexOf(y);m[A]=T,m.indexOf(null)===-1&&n({modelTopology:s,weightSpecs:l,weightData:Ks(m),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},w.onerror=L=>r(`Failed to weights data from file of path '${y}'.`),w.readAsArrayBuffer(p[y])})})},i.onerror=o=>r(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),i.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],r=t.map(o=>Km(o.name)),i={};for(const o of e)o.paths.forEach(a=>{const s=Km(a);if(n.indexOf(s)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(n.push(s),r.indexOf(s)===-1)throw new Error(`Weight file with basename '${s}' is not provided.`);i[a]=t[r.indexOf(s)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return i}}const _O=e=>se().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(li.URL_SCHEME))?NO(e.slice(li.URL_SCHEME.length)):null;ve.registerSaveRouter(_O);function NO(e="model"){return new li(e)}function RO(e){return new AO(e)}function Jm(e,t,n,r){a(e),n=n==null?0:n,r=r==null?1:r,s(n,r);let i=0;const o=c=>(c.then(p=>{const l=n+ ++i/e.length*(r-n);return t(l),p}),c);function a(c){f(c!=null&&Array.isArray(c)&&c.length>0,()=>"promises must be a none empty array")}function s(c,p){f(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${c}`),f(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),f(p>=c,()=>`startFraction must be no more than endFraction, but got startFraction ${c} and endFraction ${p}`)}return Promise.all(e.map(o))}async function Xm(e,t){t==null&&(t={});const n=t.fetchFunc==null?se().platform.fetch:t.fetchFunc,r=e.map(u=>n(u,t.requestInit,{isBinary:!0})),i=0,o=.5,a=t.onProgress==null?await Promise.all(r):await Jm(r,t.onProgress,i,o),s=a.map(u=>u.arrayBuffer()),c=.5,p=1,l=t.onProgress==null?await Promise.all(s):await Jm(s,t.onProgress,c,p);return l}async function CO(e,t="",n,r){const i=a=>Xm(a,{requestInit:r}),o=Ax(i);return o(e,t,n)}function Ax(e){return async(t,n="",r)=>{const i=t.map(()=>!1),o={},a=r!=null?r.map(()=>!1):[],s=[];if(t.forEach((b,y)=>{let w=0;b.weights.forEach(L=>{const T="quantization"in L?L.quantization.dtype:L.dtype,A=Vs[T]*Z(L.shape),_=()=>{i[y]=!0,o[y]==null&&(o[y]=[]),o[y].push({manifestEntry:L,groupOffset:w,sizeBytes:A})};r!=null?r.forEach((N,C)=>{N===L.name&&(_(),a[C]=!0)}):_(),s.push(L.name),w+=A})}),!a.every(b=>b)){const b=r.filter((y,w)=>!a[w]);throw new Error(`Could not find weights in manifest with names: ${b.join(", ")}.
|
|
Manifest JSON has weights with names: ${s.join(", ")}.`)}const c=i.reduce((b,y,w)=>(y&&b.push(w),b),[]),p=[];c.forEach(b=>{t[b].paths.forEach(y=>{const w=n+(n.endsWith("/")?"":"/")+y;p.push(w)})});const l=await e(p),u={};let m=0;return c.forEach(b=>{const y=t[b].paths.length;let w=0;for(let N=0;N<y;N++)w+=l[m+N].byteLength;const L=new ArrayBuffer(w),T=new Uint8Array(L);let A=0;for(let N=0;N<y;N++){const C=new Uint8Array(l[m+N]);T.set(C,A),A+=C.byteLength}const _=o[b];_.forEach(N=>{const C=L.slice(N.groupOffset,N.groupOffset+N.sizeBytes),F=Vm(C,[N.manifestEntry]);for(const E in F)u[E]=F[E]}),m+=y}),u}}const EO="application/octet-stream",OO="application/json";class Zm{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc!=null?(f(typeof t.fetchFunc=="function",()=>"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):this.fetch=se().platform.fetch,f(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&f(e.length===2,()=>`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 new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData();const 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:OO}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:EO}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Js(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new 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.`);let t;try{t=await e.json()}catch(l){let u=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?u+=" 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.":u+=" Please make sure the server is serving valid JSON for this request.",new Error(u)}const n=t.modelTopology,r=t.weightsManifest,i=t.generatedBy,o=t.convertedBy,a=t.format,s=t.userDefinedMetadata;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let c,p;if(r!=null){const l=await this.loadWeights(r);[c,p]=l}return{modelTopology:n,weightSpecs:c,weightData:p,userDefinedMetadata:s,generatedBy:i,convertedBy:o,format:a}}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=kO(t),i=this.weightPathPrefix||n,o=[];for(const c of e)o.push(...c.weights);const a=[];e.forEach(c=>{c.paths.forEach(p=>{a.push(i+p+r)})});const s=await Xm(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Ks(s)]}}Zm.URL_SCHEME_REGEX=/^https?:\/\//;function kO(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),i=n>t?e.substring(n):"";return[r+"/",i]}function Qm(e){return e.match(Zm.URL_SCHEME_REGEX)!=null}const Nx=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>Qm(r)):n=Qm(e),n)return ef(e,t)}return null};ve.registerSaveRouter(Nx);ve.registerLoadRouter(Nx);function ef(e,t){return new Zm(e,t)}function DO(e,t){return ef(e,t)}class tf{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class FO{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function MO(e,t,n,r){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new tf(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 tf({modelTopology:e}))}else return 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 tf({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function UO(e){return new FO(e)}const lg={};Oe(lg,{browserFiles:()=>RO,browserHTTPRequest:()=>DO,concatenateArrayBuffers:()=>Ks,copyModel:()=>Sx,decodeWeights:()=>Vm,encodeWeights:()=>dO,fromMemory:()=>MO,getLoadHandlers:()=>vO,getModelArtifactsInfoForJSON:()=>Js,getSaveHandlers:()=>LO,http:()=>ef,isHTTPScheme:()=>Qm,listModels:()=>Lx,loadWeights:()=>CO,moveModel:()=>Tx,registerLoadRouter:()=>xO,registerSaveRouter:()=>yO,removeModel:()=>vx,weightsLoaderFactory:()=>Ax,withSaveHandler:()=>UO});function WO(e,t,n){const r=h(e,"labels","confusionMatrix"),i=h(t,"predictions","confusionMatrix");f(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),f(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),f(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),f(r.shape[0]===i.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${i.shape[0]}. Labels and predictions should have the same number of elements.`),f(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const o=Sr(R(r,"int32"),n),a=Sr(R(i,"int32"),n),s=X(o);return R(K(s,a),"int32")}const qO=d({confusionMatrix_:WO});const pg={};Oe(pg,{confusionMatrix:()=>qO});const Zf={};Oe(Zf,{fromPixels:()=>jO,toPixels:()=>PO});let ui;function BO(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,i=!1,o=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)o=!0;else if(e.getContext!=null)a=!0;else throw new 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}`);if(i){const b=2;if(i&&e.readyState<b)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const s=Fi(ra,g.backendName);if(s!=null){const b={pixels:e},y={numChannels:t};return g.runKernel(ra,b,y)}const[c,p]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let l;a?l=e.getContext("2d").getImageData(0,0,c,p).data:r||n?l=e.data:(o||i)&&(ui==null&&(ui=document.createElement("canvas").getContext("2d")),ui.canvas.width=c,ui.canvas.height=p,ui.drawImage(e,0,0,c,p),l=ui.getImageData(0,0,c,p).data);let u;if(t===4)u=new Int32Array(l);else{const b=c*p;u=new Int32Array(b*t);for(let y=0;y<b;y++)for(let w=0;w<t;++w)u[y*t+w]=l[y*4+w]}const m=[p,c,t];return fi(u,m,"int32")}async function PO(e,t){let n=h(e,"img","toPixels");if(!(e instanceof de)){const L=n;n=R(L,"int32"),L.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[r,i]=n.shape.slice(0,2),o=n.rank===2?1:n.shape[2];if(o>4||o===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${o}`);const a=await n.data(),s=sn(n),c=st(n),p=await Promise.all([s.data(),c.data()]),l=p[0],u=p[1],m=l[0],b=u[0];if(s.dispose(),c.dispose(),n.dtype==="float32"){if(m<0||b>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [${m} - ${b}].`)}else if(n.dtype==="int32"){if(m<0||b>255)throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [${m} - ${b}].`)}else throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const y=n.dtype==="float32"?255:1,w=new Uint8ClampedArray(i*r*4);for(let L=0;L<r*i;++L){let T,A,_,N;o===1?(T=a[L]*y,A=a[L]*y,_=a[L]*y,N=255):o===3?(T=a[L*3]*y,A=a[L*3+1]*y,_=a[L*3+2]*y,N=255):o===4&&(T=a[L*4]*y,A=a[L*4+1]*y,_=a[L*4+2]*y,N=a[L*4+3]*y);const C=L*4;w[C+0]=Math.round(T),w[C+1]=Math.round(A),w[C+2]=Math.round(_),w[C+3]=Math.round(N)}if(t!=null){t.width=i,t.height=r;const L=t.getContext("2d"),T=new ImageData(w,i,r);L.putImageData(T,0,0)}return n!==e&&n.dispose(),w}const jO=d({fromPixels_:BO});const Gf={};Oe(Gf,{prepareAndValidate:()=>_x});function _x(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new 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 new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const n=t.shape,r=n[n.length-1];let i=1;for(let p=0;p<n.length-1;++p)i*=n[p];const o=e.shape,a=n.slice();a.pop();let s=1;for(let p=r;p<e.rank;++p)s*=o[p],a.push(o[p]);const c=[...Bt(e.shape).map(p=>p/s),1].slice(0,r);return[a,i,s,c]}const Ef={};Oe(Ef,{Serializable:()=>nf,SerializationMap:()=>fr,registerClass:()=>Xe});class nf{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class fr{constructor(){this.classNameMap={}}static getMap(){return fr.instance==null&&(fr.instance=new fr()),fr.instance}static register(e){fr.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Xe(e){f(e.className!=null,()=>"Class being registered does not have the static className property defined."),f(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),f(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),fr.register(e)}const Qv="2.3.0";class Ze extends nf{minimize(e,t=!1,n){const{value:r,grads:i}=this.computeGradients(e,n);if(n!=null){const o=n.map(a=>({name:a.name,tensor:i[a.name]}));this.applyGradients(o)}else this.applyGradients(i);return be(i),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return kh(e,t)}dispose(){this.iterations_!=null&&be(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:k(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Ze,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class kn extends Ze{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const i=g.registeredVariables[n],o=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:ce(()=>W(i).variable(o))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:ce(()=>W(i).variable(o))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;ce(()=>{const p=O(v(s,this.rho),v(G(a),1-this.rho)),l=v(M(le(O(c,this.epsilon)),le(O(s,this.epsilon))),a),u=O(v(c,this.rho),v(G(l),1-this.rho));s.assign(p),c.assign(u);const m=O(v(l,-this.learningRate),i);i.assign(m)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(be(this.accumulatedGrads.map(e=>e.variable)),be(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}kn.className="Adadelta";Xe(kn);class On extends Ze{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const i=g.registeredVariables[n];if(this.accumulatedGrads[r]==null){const s=!1;this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:ce(()=>Hn(i.shape,this.initialAccumulatorValue).variable(s))}}const o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;const a=this.accumulatedGrads[r].variable;ce(()=>{const s=O(a,G(o));a.assign(s);const c=O(v(M(o,le(O(s,g.backend.epsilon()))),-this.learningRate),i);i.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&be(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}On.className="Adagrad";Xe(On);class En extends Ze{constructor(e,t,n,r=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],ce(()=>{this.accBeta1=k(t).variable(),this.accBeta2=k(n).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ce(()=>{const n=D(1,this.accBeta1),r=D(1,this.accBeta2);t.forEach((i,o)=>{const a=g.registeredVariables[i],s=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:ce(()=>W(a).variable(s))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:ce(()=>W(a).variable(s))});const c=Array.isArray(e)?e[o].tensor:e[i];if(c==null)return;const p=this.accumulatedFirstMoment[o].variable,l=this.accumulatedSecondMoment[o].variable,u=O(v(p,this.beta1),v(c,1-this.beta1)),m=O(v(l,this.beta2),v(G(c),1-this.beta2)),b=M(u,n),y=M(m,r);p.assign(u),l.assign(m);const w=O(v(M(b,O(le(y),this.epsilon)),-this.learningRate),a);a.assign(w)}),this.accBeta1.assign(v(this.accBeta1,this.beta1)),this.accBeta2.assign(v(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&be(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),ce(()=>{this.accBeta1.assign(je(this.beta1,this.iterations_+1)),this.accBeta2.assign(je(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}En.className="Adam";Xe(En);class Cn extends Ze{constructor(e,t,n,r=null,i=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],ce(()=>{this.iteration=k(0).variable(),this.accBeta1=k(t).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ce(()=>{const n=D(1,this.accBeta1),r=M(-this.learningRate,O(v(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=g.registeredVariables[i],s=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:W(a).variable(s)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:W(a).variable(s)});const c=Array.isArray(e)?e[o].tensor:e[i];if(c==null)return;const p=this.accumulatedFirstMoment[o].variable,l=this.accumulatedWeightedInfNorm[o].variable,u=O(v(p,this.beta1),v(c,1-this.beta1)),m=v(l,this.beta2),b=_e(c),y=Tt(m,b);p.assign(u),l.assign(y);const w=O(v(M(r,n),M(u,O(y,this.epsilon))),a);a.assign(w)}),this.iteration.assign(O(this.iteration,1)),this.accBeta1.assign(v(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&be(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}Cn.className="Adamax";Xe(Cn);class $t extends Ze{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const i=Array.isArray(e)?e[r].tensor:e[n];if(i==null)return;const o=g.registeredVariables[n];ce(()=>{const a=O(v(this.c,i),o);o.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Dh(k(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}$t.className="SGD";Xe($t);class Rn extends $t{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=k(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const i=g.registeredVariables[n];if(this.accumulations[r]==null){const s=!1;this.accumulations[r]={originalName:`${n}/momentum`,variable:ce(()=>W(i).variable(s))}}const o=this.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;ce(()=>{let s;const c=O(v(this.m,o),a);this.useNesterov?s=O(v(this.c,O(a,v(c,this.m))),i):s=O(v(this.c,c),i),o.assign(c),i.assign(s)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&be(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}Rn.className="Momentum";Xe(Rn);class _n extends Ze{constructor(e,t=.9,n=0,r=null,i=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,r==null&&(this.epsilon=g.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const i=g.registeredVariables[n],o=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:ce(()=>W(i).variable(o))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:ce(()=>W(i).variable(o))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:ce(()=>W(i).variable(o))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedMeanSquares[r].variable,c=this.accumulatedMoments[r].variable;ce(()=>{const p=O(v(s,this.decay),v(G(a),1-this.decay));if(this.centered){const l=this.accumulatedMeanGrads[r].variable,u=O(v(l,this.decay),v(a,1-this.decay)),m=M(v(a,this.learningRate),le(D(p,O(G(u),this.epsilon)))),b=O(v(c,this.momentum),m);s.assign(p),l.assign(u),c.assign(b);const y=D(i,b);i.assign(y)}else{const l=O(v(s,this.decay),v(G(a),1-this.decay)),u=O(v(c,this.momentum),M(v(a,this.learningRate),le(O(l,this.epsilon))));s.assign(l),c.assign(u);const m=D(i,u);i.assign(m)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&be(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&be(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&be(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}_n.className="RMSProp";Xe(_n);class In{static sgd(e){return new $t(e)}static momentum(e,t,n=!1){return new Rn(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,i=!1){return new _n(e,t,n,r,i)}static adam(e=.001,t=.9,n=.999,r=null){return new En(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new kn(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,i=0){return new Cn(e,t,n,r,i)}static adagrad(e,t=.1){return new On(e,t)}}Rn,$t,kn,On,_n,Cn,En;const tS={sgd:In.sgd,momentum:In.momentum,adadelta:In.adadelta,adagrad:In.adagrad,rmsprop:In.rmsprop,adamax:In.adamax,adam:In.adam};const GO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function _S(){return new Promise(e=>GO(()=>e()))}function $O(e,t,n){const r=n*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[r,i]}function HO(e,t,n,r=!0){let i=[];if(r)i=i.concat(t.slice(0)),i.push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);const o=t.length;for(let a=0;a<o;++a)i=i.concat([e[a+1]/t[a],t[a]]);i=i.concat(e.slice(o+1))}return i}function YO(e,t,n=!0){const r=[];if(n){r.push(t);for(let i=t+1;i<e;++i)i<=2*t?(r.push(i),r.push(i-(t+1))):r.push(i)}else{const i=[],o=[];for(let a=1;a<e;++a)a>=t*2+1||a%2===1?o.push(a):i.push(a);r.push(...i),r.push(0),r.push(...o)}return r}function zO(e,t,n,r=!0){const i=[];r?i.push(e[0]/n):i.push(e[0]*n);for(let o=1;o<e.length;++o)o<=t.length?r?i.push(t[o-1]*e[o]):i.push(e[o]/t[o-1]):i.push(e[o]);return i}function VO(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function KO(e,t,n){const r=e.slice(0,1);for(let i=0;i<n;++i)r.push(e[i+1]-t[i][0]-t[i][1]);return r}const rf=1.7580993408473768,of=1.0507009873554805;const JO=.3275911,XO=.254829592,ZO=-.284496736,QO=1.421413741,ek=-1.453152027,tk=1.061405429;function nk(...e){se().getBool("IS_TEST")||console.warn(...e)}function rk(...e){se().getBool("IS_TEST")||console.log(...e)}function ik(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(e.length*2);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function ok(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function sk(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let 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}}function ak(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let 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}}function ck(e,t){const n=e[t*2],r=e[t*2+1];return{real:n,imag:r}}function pk(e,t,n,r){e[r*2]=t,e[r*2+1]=n}function lk(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let i=0;i<Math.ceil(e/2);i++){const o=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(o),r[i]=Math.sin(o)}return{real:n,imag:r}}function uk(e,t,n){const r=(n?2:-2)*Math.PI*(e/t),i=Math.cos(r),o=Math.sin(r);return{real:i,imag:o}}const dg={};Oe(dg,{ERF_A1:()=>XO,ERF_A2:()=>ZO,ERF_A3:()=>QO,ERF_A4:()=>ek,ERF_A5:()=>tk,ERF_P:()=>JO,PARALLELIZE_THRESHOLD:()=>Mp,SELU_SCALE:()=>of,SELU_SCALEALPHA:()=>rf,applyActivation:()=>dr,assertAndGetBroadcastShape:()=>H,assertAxesAreInnerMostDims:()=>U0,assertParamsConsistent:()=>Cm,assignToTypedArray:()=>pk,axesAreInnerMostDims:()=>Am,calculateShapes:()=>Gy,castTensor:()=>hk,combineLocations:()=>Dy,complexWithEvenIndex:()=>sk,complexWithOddIndex:()=>ak,computeConv2DInfo:()=>We,computeConv3DInfo:()=>Tn,computeDefaultPad:()=>Rm,computeDilation2DInfo:()=>J0,computeOptimalWindowSize:()=>r1,computeOutAndReduceShapes:()=>Nm,computeOutShape:()=>Em,computePool2DInfo:()=>Ct,computePool3DInfo:()=>on,convertConv2DDataFormat:()=>Sn,eitherStridesOrDilationsAreOne:()=>ae,expandShapeToKeepDim:()=>fe,exponent:()=>uk,exponents:()=>lk,getAxesPermutation:()=>he,getBroadcastDims:()=>jR,getComplexWithIndex:()=>ck,getFusedBiasGradient:()=>hr,getFusedDyActivation:()=>ur,getImageCenter:()=>$O,getInnerMostAxes:()=>Ee,getPermuted:()=>YO,getReductionAxes:()=>ie,getReshaped:()=>HO,getReshapedPermuted:()=>zO,getSliceBeginCoords:()=>VO,getSliceSize:()=>KO,getUndoAxesPermutation:()=>pr,linspaceImpl:()=>mk,log:()=>rk,mergeRealAndImagArrays:()=>ik,prepareAndValidate:()=>_x,prepareSplitSize:()=>$m,reshapeTensor:()=>dk,segment_util:()=>Wy,shouldFuse:()=>mr,splitRealAndImagArrays:()=>ok,tupleValuesAreOne:()=>ut,upcastType:()=>wr,validateInput:()=>Bp,validateUpdateShape:()=>Hm,warn:()=>nk});function hk(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const r=Ue(e.shape),i=R(e,"float32"),o=n.complex(i,r);return r.dispose(),i.dispose(),o}if(!fm(e.dtype,t))return g.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const r=n.real(e),i=R(r,t);return r.dispose(),i}if(t==="int32")return n.int(e);if(t==="bool"){const r=k(0,e.dtype),i=n.notEqual(e,r);return r.dispose(),i}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function dk(e,t){return g.makeTensorFromDataId(e.dataId,t,e.dtype)}function mk(e,t,n){const r=(t-e)/(n-1),i=Pt(n,"float32");i[0]=e;for(let o=1;o<i.length;o++)i[o]=i[o-1]+r;return ht(i,"float32")}function Rx(e,t,n){const r=new Array(e.rank).fill(0),i=e.shape.slice();return t.map(o=>{const a=[...i];a[n]=o;const s=Y(e,r,a);return r[n]+=o,s})}function Cx(e,t){const n=new Array(e.rank);for(let i=0;i<n.length;i++)n[i]=e.shape[i]*t[i];const r=ke(n,e.dtype);for(let i=0;i<r.values.length;++i){const o=r.indexToLoc(i),a=new Array(e.rank);for(let c=0;c<a.length;c++)a[c]=o[c]%e.shape[c];const s=e.locToIndex(a);r.values[i]=e.values[s]}return r.toTensor()}function Ex(e,t,n,r,i){const o=t[t.length-1],[a,s]=[e.length/o,o],c=ni(n,a*r),p=ni("int32",a*r);for(let u=0;u<a;u++){const m=u*s,b=e.subarray(m,m+s),y=[];for(let A=0;A<b.length;A++)y.push({value:b[A],index:A});y.sort((A,_)=>_.value-A.value);const w=u*r,L=c.subarray(w,w+r),T=p.subarray(w,w+r);for(let A=0;A<r;A++)L[A]=y[A].value,T[A]=y[A].index}const l=t.slice();return l[l.length-1]=r,[Qe(c,l,n),Qe(p,l,"int32")]}const hg={};Oe(hg,{nonMaxSuppressionV3Impl:()=>Hp,nonMaxSuppressionV4Impl:()=>Yp,nonMaxSuppressionV5Impl:()=>zp,split:()=>Rx,tile:()=>Cx,topkImpl:()=>Ex,whereImpl:()=>qp});const fk=1e-7,gk=1e-4;class RS{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap(),this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class CS{time(e){return I("time")}read(e){return I("read")}readSync(e){return I("readSync")}numDataIds(){return I("numDataIds")}disposeData(e){return I("disposeData")}write(e,t,n){return I("write")}move(e,t,n,r){return I("move")}memory(){return I("memory")}floatPrecision(){return I("floatPrecision")}epsilon(){return this.floatPrecision()===32?fk:gk}batchMatMul(e,t,n,r){return I("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:r,bias:i,activation:o,preluActivationWeights:a}){return I("fusedBatchMatMul")}slice(e,t,n){return I("slice")}stridedSlice(e,t,n,r){return I("stridedSlice")}unstack(e,t){return I("unstack")}reverse(e,t){return I("reverse")}concat(e,t){return I("concat")}neg(e){return I("neg")}add(e,t){return I("add")}addN(e){return I("addN")}subtract(e,t){return I("subtract")}multiply(e,t){return I("multiply")}realDivide(e,t){return I("realDivide")}floorDiv(e,t){return I("floorDiv")}sum(e,t){return I("sum")}prod(e,t){return I("prod")}unsortedSegmentSum(e,t,n){return I("unsortedSegmentSum")}argMin(e,t){return I("argMin")}argMax(e,t){return I("argMax")}equal(e,t){return I("equal")}notEqual(e,t){return I("notEqual")}less(e,t){return I("less")}lessEqual(e,t){return I("lessEqual")}greater(e,t){return I("greater")}greaterEqual(e,t){return I("greaterEqual")}logicalNot(e){return I("logicalNot")}logicalAnd(e,t){return I("logicalAnd")}logicalOr(e,t){return I("logicalOr")}where(e){return I("where")}select(e,t,n){return I("select")}topk(e,t,n){return I("topk")}min(e,t){return I("min")}minimum(e,t){return I("minimum")}mod(e,t){return I("mod")}max(e,t){return I("max")}maximum(e,t){return I("maximum")}all(e,t){return I("all")}any(e,t){return I("any")}squaredDifference(e,t){return I("squaredDifference")}ceil(e){return I("ceil")}floor(e){return I("floor")}round(e){return I("round")}sign(e){return I("sign")}isNaN(e){return I("isNaN")}isInf(e){return I("isInf")}isFinite(e){return I("isFinite")}pow(e,t){return I("pow")}exp(e){return I("exp")}expm1(e){return I("expm1")}softmax(e,t){return I("softmax")}log(e){return I("log")}log1p(e){return I("log1p")}sqrt(e){return I("sqrt")}rsqrt(e){return I("rsqrt")}square(e){return I("square")}reciprocal(e){return I("reciprocal")}relu(e){return I("relu")}relu6(e){return I("relu6")}prelu(e,t){return I("prelu")}elu(e){return I("elu")}eluDer(e,t){return I("eluDer")}selu(e){return I("selu")}int(e){return I("int")}clip(e,t,n){return I("clip")}abs(e){return I("abs")}complexAbs(e){return I("complexAbs")}sigmoid(e){return I("sigmoid")}softplus(e){return I("softplus")}sin(e){return I("sin")}cos(e){return I("cos")}tan(e){return I("tan")}asin(e){return I("asin")}acos(e){return I("acos")}atan(e){return I("atan")}atan2(e,t){return I("atan2")}sinh(e){return I("sinh")}cosh(e){return I("cosh")}tanh(e){return I("tanh")}asinh(e){return I("asinh")}acosh(e){return I("acosh")}atanh(e){return I("atanh")}erf(e){return I("erf")}step(e,t){return I("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:r,activation:i,preluActivationWeights:o}){return I("fusedConv2d")}conv2d(e,t,n){return I("conv2d")}conv2dDerInput(e,t,n){return I("conv2dDerInput")}conv2dDerFilter(e,t,n){return I("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:r,activation:i,preluActivationWeights:o}){return I("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return I("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return I("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return I("depthwiseConv2DDerFilter")}conv3d(e,t,n){return I("conv3d")}conv3dDerInput(e,t,n){return I("conv3dDerInput")}conv3dDerFilter(e,t,n){return I("conv3dDerFilter")}maxPool(e,t){return I("maxPool")}maxPoolBackprop(e,t,n,r){return I("maxPoolBackprop")}avgPool(e,t){return I("avgPool")}avgPoolBackprop(e,t,n){return I("avgPoolBackprop")}avgPool3d(e,t){return I("avgPool3d")}avgPool3dBackprop(e,t,n){return I("avgPool3dBackprop")}maxPool3d(e,t){return I("maxPool3d")}maxPool3dBackprop(e,t,n,r){return I("maxPool3dBackprop")}reshape(e,t){return I("reshape")}cast(e,t){return I("cast")}tile(e,t){return I("tile")}pad(e,t,n){return I("pad")}transpose(e,t){return I("transpose")}gather(e,t,n){return I("gather")}gatherND(e,t){return I("gatherND")}scatterND(e,t,n){return I("scatterND")}batchToSpaceND(e,t,n){return I("batchToSpaceND")}spaceToBatchND(e,t,n){return I("spaceToBatchND")}resizeBilinear(e,t,n,r){return I("resizeBilinear")}resizeBilinearBackprop(e,t,n){return I("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,r){return I("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return I("resizeNearestNeighborBackprop")}batchNorm(e,t,n,r,i,o){return I("batchNorm")}localResponseNormalization4D(e,t,n,r,i){return I("localResponseNormalization4D")}LRNGrad(e,t,n,r,i,o,a){return I("LRNGrad")}multinomial(e,t,n,r){return I("multinomial")}oneHot(e,t,n,r){return I("oneHot")}cumsum(e,t,n,r){return I("cumsum")}nonMaxSuppression(e,t,n,r,i){return I("nonMaxSuppression")}fft(e){return I("fft")}ifft(e){return I("ifft")}complex(e,t){return I("complex")}real(e){return I("real")}imag(e){return I("imag")}cropAndResize(e,t,n,r,i,o){return I("cropAndResize")}depthToSpace(e,t,n){return I("depthToSpace")}split(e,t,n){return I("split")}sparseToDense(e,t,n,r){return I("sparseToDense")}diag(e){return I("diag")}fill(e,t,n){return I("fill")}onesLike(e){return I("onesLike")}zerosLike(e){return I("zerosLike")}linspace(e,t,n){return I("linspace")}dispose(){return I("dispose")}}function I(e){throw new Error(`'${e}' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}const Ox={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,vt(R(n,"float32"),-1))}}};const kx={kernelName:Ui,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=G(R(n,"float32")),i=le(D(k(1),r));return Q(M(e,i))}}}};const Dx={kernelName:Wi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=le(D(G(R(n,"float32")),1));return M(e,r)}}}};const Fx={kernelName:Jn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{let s=e;const c=ie(n.shape,i);return c.length>0&&(s=U(s,c)),x(s,n.shape)},a=()=>{let s=e;const c=ie(r.shape,i);return c.length>0&&(s=U(s,c)),x(s,r.shape)};return{a:o,b:a}}};const Mx={kernelName:qi,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((r,i)=>{n[i]=()=>e.clone()}),n}};const Ux={kernelName:Bi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const Wx={kernelName:Pi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const qx={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,le(D(k(1),G(R(n,"float32")))))}}};const Bx={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=le(O(k(1),G(R(n,"float32"))));return M(e,r)}}}};const Px={kernelName:Yi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{const s=O(G(n),G(r));let c=v(e,M(r,s));const p=ie(n.shape,i);return p.length>0&&(c=U(c,p)),x(c,n.shape)},a=()=>{const s=O(G(n),G(r));let c=Q(v(e,M(n,s)));const p=ie(r.shape,i);return p.length>0&&(c=U(c,p)),x(c,r.shape)};return{a:o,b:a}}};const jx={kernelName:$i,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,O(G(R(n,"float32")),1))}}};const Gx={kernelName:Hi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,D(k(1),G(R(n,"float32"))))}}};function bk(e,t,n,r,i=[1,1,1],o,a){const s=h(e,"dy","avgPool3dBackprop"),c=h(t,"input","avgPool3dBackprop");let p=s,l=c,u=!1;c.rank===4&&(u=!0,p=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]]),l=x(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),f(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),f(l.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${l.rank}.`),f(ae(r,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`),a!=null&&f(J(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=L=>{const T=on(l.shape,n,r,i,o,a);return L.avgPool3dBackprop(p,l,T)},b={dy:p,input:l},y={filterSize:n,strides:r,dilations:i,pad:o,dimRoundingMode:a},w=g.runKernelFunc(m,b,null,Pu,y);return u?x(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const $x=d({avgPool3dBackprop_:bk});const Hx={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:i,strides:o,dilations:a,pad:s,dimRoundingMode:c}=n,p=a==null?[1,1,1]:a;return{x:()=>$x(e,r,i,o,p,s,c)}}};function wk(e,t,n,r,i){const o=h(e,"dy","avgPoolBackprop"),a=h(t,"input","avgPoolBackprop");f(a.rank===o.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${o.rank})`);let s=a,c=o,p=!1;a.rank===3&&(p=!0,s=x(a,[1,a.shape[0],a.shape[1],a.shape[2]]),c=x(o,[1,o.shape[0],o.shape[1],o.shape[2]])),f(c.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),f(s.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${s.rank}.`);const l=y=>{const w=Ct(s.shape,n,r,1,i);return y.avgPoolBackprop(c,s,w)},u={dy:c,input:s},m={filterSize:n,strides:r,pad:i},b=g.runKernelFunc(l,u,null,Bu,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Yx=d({avgPoolBackprop_:wk});const zx={kernelName:zi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:i,strides:o,pad:a}=n;return{x:()=>Yx(e,r,i,o,a)}}};const Vx={kernelName:Ki,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,i]=t,{transposeA:o,transposeB:a}=n;return!o&&!a?{a:()=>K(e,i,!1,!0),b:()=>K(r,e,!0,!1)}:!o&&a?{a:()=>K(e,i,!1,!1),b:()=>K(e,r,!0,!1)}:o&&!a?{a:()=>K(i,e,!1,!0),b:()=>K(r,e,!1,!1)}:{a:()=>K(i,e,!0,!0),b:()=>K(e,r,!0,!0)}}};const Kx={kernelName:Ji,gradFunc:(e,t,n)=>{const{blockShape:r,crops:i}=n;return{x:()=>Un(e,r,i)}}};const Jx={kernelName:Xi,gradFunc:(e,t,n)=>{const r=n,i=r.inputShape,o=r.shape,a=Array.from(o);for(let c=i.length-1;c>=0;c--)if(i[c]===o[c])a[c]=1;else if(i[c]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${o}].`);const s=[];for(let c=0;c<a.length;c++)a[c]>1&&s.push(c);return{x:()=>U(e,s,!0)}}};const Xx={kernelName:Xn,gradFunc:e=>({x:()=>e.clone()})};const Zx={kernelName:Zi,gradFunc:e=>({x:()=>W(e)})};const Qx={kernelName:Qi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:i,clipValueMax:o}=n;return{x:()=>Ae(ft(ct(r,i),at(r,o)),e,W(e))}}};const eL={kernelName:eo,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map(c=>c.shape),{axis:i}=n,o=z(i,t[0].shape)[0],a=r.map(c=>c[o]),s=Ot(e,a,o);return s.map(c=>()=>c)}};const tL={kernelName:to,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,i]=t,{dilations:o,strides:a,pad:s,dataFormat:c}=n;return f(ut(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>ai(r.shape,e,i,a,s,c),filter:()=>ci(r,e,i.shape,a,s,c)}}};const nL={kernelName:no,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,i]=t,{strides:o,pad:a,dataFormat:s,dimRoundingMode:c}=n;return{dy:()=>It(e,i,o,a,s,1,c),filter:()=>ci(e,r,i.shape,o,a,s,c)}}};function yk(e,t,n,r,i){let o=e;e.rank===4&&(o=x(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=x(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),f(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),f(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),f(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),f(o.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${n[3]}.`),f(a.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`);const s=l=>{const u=1,m=Tn(o.shape,n,r,u,i);return l.conv3dDerFilter(o,a,m)},c={x:o,y:a},p={strides:r,pad:i};return g.runKernelFunc(s,c,null,$u,p)}const rL=d({conv3DBackpropFilter_:yk});const iL={kernelName:ro,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:i,pad:o}=n;f(ut(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const[a,s]=t;return{x:()=>Fp(a.shape,e,s,i,o),filter:()=>rL(a,e,s.shape,i,o)}}};const oL={kernelName:io,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Q(wi(R(n,"float32"))),e)}}};const sL={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(bi(R(n,"float32")),e)}}};const aL={kernelName:so,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:i,exclusive:o,reverse:a}=n;return{x:()=>{const s=he([i],r.rank);let c=Oi(e,i,o,!a);return s!=null&&(c=X(c,s)),c}}}};const cL={kernelName:ao,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:i,pad:o,dimRoundingMode:a}=n,s=r==null?[1,1]:r;f(ut(s),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[c,p]=t;f(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),f(c.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),f(ae(i,s),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${s}'.`),a!=null&&f(J(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const l=We(c.shape,p.shape,i,s,o,a,!0);return{x:()=>jp(c.shape,e,p,l),filter:()=>Pp(c,e,p.shape,l)}}};const pL={kernelName:co,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,i]=t,o={x:r,filter:i,dy:e},a={x:r,filter:i,dy:e};return{x:()=>g.runKernel(Xu,o,n),filter:()=>g.runKernel(Zu,a,n)}}};const lL={kernelName:po,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{const s=M(e,R(r,"float32")),c=ie(n.shape,i);return c.length>0?x(U(s,c),n.shape):s},a=()=>{let s=v(e,R(n,"float32"));const c=ie(r.shape,i);c.length>0&&(s=x(U(s,c),r.shape));const p=G(r);return Q(M(s,R(p,"float32")))};return{a:o,b:a}}};const uL={kernelName:lo,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r=o=>o.eluDer(e,n),i={dy:e,y:n};return{x:()=>g.runKernelFunc(r,i,null,Qu)}}};const hL={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(Ne(Q(G(n))),2/Math.sqrt(Math.PI));return{x:()=>v(e,r)}}};const dL={kernelName:ho,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,n)}}};const mL={kernelName:mo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Ne(n))}}};const fL={kernelName:fo,gradFunc:e=>({x:()=>W(e)})};const gL={kernelName:go,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{const s=M(e,R(r,"float32")),c=ie(n.shape,i);return c.length>0?x(U(s,c),n.shape):s},a=()=>{let s=v(e,R(n,"float32"));const c=ie(r.shape,i);c.length>0&&(s=x(U(s,c),r.shape));const p=G(r);return Q(M(s,R(p,"float32")))};return{a:o,b:a}}};const bL={kernelName:bo,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[i,o,a,s]=t,c=s==null?k(1):s,p=ie(o.shape,i.shape),l=[];if(o.rank===1){for(let N=0;N<i.shape.length-1;++N)l.push(i.shape[N]);l.push(1)}const u=D(i,o),m=v(e,c),b=yi(O(a,k(r))),y=v(v(v(b,b),b),k(-.5)),w=()=>o.rank===1?x(v(v(e,Ht(x(b,[1,1,1,o.shape[0]]),l)),c),i.shape):x(v(v(e,b),c),i.shape),L=()=>{let N=v(v(b,k(-1)),m);return o.rank===1&&(N=U(N,p)),x(N,o.shape)},T=()=>{let N=v(v(y,u),m);return o.rank===1&&(N=U(N,p)),x(N,o.shape)},A=()=>{const N=v(u,b);let C=v(e,N);return o.rank===1&&(C=U(C,p)),x(C,o.shape)},_=()=>{let N=e;return o.rank===1&&(N=U(N,p)),x(N,o.shape)};return{x:w,mean:L,variance:T,scale:A,offset:_}}};const xL={kernelName:wo,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,i]=t,{axis:o}=n,a=z(o,r.shape)[0],s=()=>{const c=r.shape,p=i.size,l=c.slice(0,a),u=l.length,m=c.slice(o,c.length).slice(1),b=m.length,y=wL(0,u),w=wL(u+1,u+1+b),L=yL([l,[p],m]),T=x(e,L),A=x(i,[p]),_=yL([[u],y,w]),N=X(T,_);let C=mi(N,A,r.shape[a]);const F=pr(_);return C=X(C,F),C};return{x:s,indices:()=>i}}};function wL(e,t){const n=[];for(let r=e;r<t;++r)n.push(r);return n}function yL(e){const t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}const LL={kernelName:yo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>W(n),b:()=>W(r)}}};const vL={kernelName:xo,gradFunc:e=>({x:()=>R(e,"float32")})};const SL={kernelName:Lo,gradFunc:e=>({x:()=>W(e)})};const TL={kernelName:vo,gradFunc:e=>({x:()=>W(e)})};const IL={kernelName:So,gradFunc:e=>({x:()=>W(e)})};const AL={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,O(n,1))}}};const NL={kernelName:To,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,R(n,"float32"))}}};const _L={kernelName:Ao,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:i}=n;return{logits:()=>{const o=!0,a=Ne(r);return D(e,v(U(e,i,o),a))}}}};function xk(e,t,n,r=5,i=1,o=1,a=.5){const s=l=>l.LRNGrad(n,e,t,r,i,o,a),c={x:e,y:t,dy:n},p={depthRadius:r,bias:i,alpha:o,beta:a};return g.runKernelFunc(s,c,null,mh,p)}const RL=d({localResponseNormalizationBackprop_:xk});const CL={kernelName:No,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,i]=t,{depthRadius:o,bias:a,alpha:s,beta:c}=n;return{x:()=>RL(r,i,e,o,a,s,c)}}};function Jp(e,t,n,r,i){return t.rank<n.rank&&(t=x(t,fe(t.shape,r))),e.rank<n.rank&&(e=x(e,fe(e.shape,r))),{x:()=>{const o=v(e,R(Kt(n,t),e.dtype));return i==null?o:X(o,i)}}}const sf={kernelName:_o,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:i}=r,[o,a]=t,s=z(i,o.shape),c=he(s,o.rank),p=Jp(e,a,o,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=X(l)),l}}}};const EL={kernelName:Ro,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=()=>v(e,R(ct(n,r),"float32")),o=()=>v(e,R(jn(n,r),"float32"));return{a:i,b:o}}};function Lk(e,t,n,r,i,o=[1,1,1],a,s){const c=h(e,"dy","maxPool3dBackprop"),p=h(t,"input","maxPool3dBackprop"),l=h(n,"output","maxPool3dBackprop");let u=c,m=p,b=l,y=!1;p.rank===4&&(y=!0,u=x(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),m=x(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]]),b=x(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),f(u.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${u.rank}.`),f(m.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),f(b.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${b.rank}.`),f(ae(i,o),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`),s!=null&&f(J(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${s} but got pad ${a}.`);const w=_=>{const N=on(m.shape,r,i,o,a,s);return _.maxPool3dBackprop(u,m,b,N)},L={dy:u,input:m,output:b},T={filterSize:r,strides:i,dilations:o,pad:a,dimRoundingMode:s},A=g.runKernelFunc(w,L,null,gh,T);return y?x(A,[A.shape[1],A.shape[2],A.shape[3],A.shape[4]]):A}const OL=d({maxPool3dBackprop_:Lk});const kL={kernelName:Eo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,i]=t,{filterSize:o,strides:a,dilations:s,pad:c,dimRoundingMode:p}=n,l=s==null?[1,1,1]:s;return{x:()=>OL(e,r,i,o,a,l,c,p)}}};function vk(e,t,n,r,i,o,a){const s=h(e,"dy","maxPoolBackprop"),c=h(t,"input","maxPoolBackprop"),p=h(n,"output","maxPoolBackprop");f(c.rank===s.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${s.rank})`),f(s.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${s.rank}.`),f(c.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${c.rank}.`),a!=null&&f(J(o),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const l=b=>{const y=Ct(c.shape,r,i,1,o,a);return b.maxPoolBackprop(s,c,p,y)},u={dy:s,input:c,output:p},m={filterSize:r,strides:i,pad:o,dimRoundingMode:a};return g.runKernelFunc(l,u,null,fh,m)}const DL=d({maxPoolBackprop_:vk});const FL={kernelName:Co,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,i]=t,{filterSize:o,strides:a,pad:s}=n;return{x:()=>DL(e,r,i,o,a,s)}}};const ML={kernelName:Oo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:i}=r,[o,a]=t,s=z(i,o.shape),c=he(s,o.rank),p=Jp(e,a,o,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=X(l)),l}}}};const UL={kernelName:ko,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=()=>v(e,R(at(n,r),"float32")),o=()=>v(e,R(Ve(n,r),"float32"));return{a:i,b:o}}};const WL={kernelName:Do,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{const s=ie(n.shape,i);return s.length>0?x(U(e,s),n.shape):e},a=()=>{const s=v(e,Q($n(M(n,r)))),c=ie(r.shape,i);return c.length>0?x(U(s,c),r.shape):s};return{a:o,b:a}}};const qL={kernelName:Fo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{const s=v(e,R(r,"float32")),c=ie(n.shape,i);return c.length>0?x(U(s,c),n.shape):s},a=()=>{const s=v(e,R(n,"float32")),c=ie(r.shape,i);return c.length>0?x(U(s,c),r.shape):s};return{a:o,b:a}}};const BL={kernelName:Mo,gradFunc:e=>({x:()=>Q(e)})};const PL={kernelName:Wo,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Ue(n.shape,"float32")}}};const jL={kernelName:Uo,gradFunc:e=>({x:()=>W(e)})};const af={kernelName:qo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>Y(e,o,r.shape)}}};const GL={kernelName:Bo,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,i]=t,o=n,a=r,s=H(o.shape,a.shape),c=()=>{const l=R(a,"float32");let u=v(e,v(l,je(o,D(l,k(1)))));const m=ie(o.shape,s);return m.length>0&&(u=U(u,m)),x(u,o.shape)},p=()=>{const l=Ve(o,0),u=Ae(l,gt(o),W(o));let m=v(e,v(i,u));const b=ie(a.shape,s);return b.length>0&&(m=U(m,b)),x(m,a.shape)};return{a:c,b:p}}};const $L={kernelName:Po,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,i=Ve(n,0);return{x:()=>Ae(i,e,v(e,r)),alpha:()=>{let o=Ae(i,W(e),v(e,n));const a=ie(r.shape,e.shape);return a.length>0&&(o=U(o,a)),x(o,r.shape)}}}};const HL={kernelName:jo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,Q(G(n)))}}};const YL={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(at(n,6),vt(n));return{x:()=>v(e,R(r,"float32"))}}};const zL={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,R(vt(n),"float32"))}}};const VL={kernelName:$o,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>x(e,n.shape)}}};const KL={kernelName:Yo,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,i=s=>{const{alignCorners:c}=n;return s.resizeBilinearBackprop(e,r,c)},o={images:r},a=()=>g.runKernelFunc(i,o,null,Ah,n);return{images:a}}};const JL={kernelName:Ho,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,i=s=>{const{alignCorners:c}=n;return s.resizeNearestNeighborBackprop(e,r,c)},o={images:r},a=()=>g.runKernelFunc(i,o,null,Ih,n);return{images:a}}};const XL={kernelName:Vo,gradFunc:(e,t,n)=>{const{dims:r}=n,i=z(r,e.shape);return{x:()=>Pe(e,i)}}};const ZL={kernelName:Ko,gradFunc:e=>({x:()=>W(e)})};const QL={kernelName:Jo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Q(M(e,v(je(n,1.5),2)))}}};const ev={kernelName:Xo,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>R(W(n),"float32"),t:()=>v(e,R(n,e.dtype)),e:()=>v(e,R(Pn(n),e.dtype))}}};const tv={kernelName:Zo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=Ve(n,k(0)),i=k(rf),o=k(of),a=v(e,o),s=v(v(e,i),Ne(R(n,"float32")));return Ae(r,a,s)}}}};const nv={kernelName:rs,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(n,D(k(1),n)))}}};const rv={kernelName:ns,gradFunc:e=>({x:()=>W(e)})};const iv={kernelName:es,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Vn(R(n,"float32")),e)}}};const ov={kernelName:ts,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(ki(R(n,"float32")),e)}}};const sv={kernelName:Qo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:i,size:o}=n,a=r.shape,[s,c]=Ys(r,i,o),p=[];for(let l=0;l<e.rank;l++)p.push([s[l],a[l]-s[l]-c[l]]);return{x:()=>ot(e,p)}}};const av={kernelName:ps,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:i}=n,o=!0,a=v(e,r);return{logits:()=>D(a,v(U(a,[i],o),r))}}};const cv={kernelName:is,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,St(n))}}};const cf={kernelName:as,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:i}=n;return{x:()=>Kn(e,r,i)}}};const pf={kernelName:cs,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>re(e,r)}}};const pv={kernelName:os,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,v(le(R(n,"float32")),2))}}};const lv={kernelName:_h,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(R(n,"float32"),2))}}};const uv={kernelName:ls,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=k(2),o=()=>v(e,v(i,D(n,r))),a=()=>v(e,v(i,D(r,n)));return{a:o,b:a}}};const hv={kernelName:ys,gradFunc:e=>({x:()=>W(e)})};const dv={kernelName:us,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,i=H(n.shape,r.shape),o=()=>{let s=e;const c=ie(n.shape,i);return c.length>0&&(s=U(s,c)),x(s,n.shape)},a=()=>{let s=e;const c=ie(r.shape,i);return c.length>0&&(s=U(s,c)),x(Q(s),r.shape)};return{a:o,b:a}}};const mv={kernelName:ss,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,i=r.shape.slice(),{axis:o}=n,a=z(o,r.shape);a.forEach(p=>{i[p]=1});const s=x(e,i),c=v(s,mt(r.shape,"float32"));return{x:()=>c}}};const fv={kernelName:hs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>M(e,G(Vn(n)))}}};const gv={kernelName:ds,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(D(k(1),G(n)),e)}}};const bv={kernelName:ms,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:i}=n,o=()=>{let a=W(r);if(r.rank===1)for(let s=0;s<i[0];++s)a=O(a,Y(e,[s*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(let s=0;s<i[0];++s)for(let c=0;c<i[1];++c)a=O(a,Y(e,[s*r.shape[0],c*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(let s=0;s<i[0];++s)for(let c=0;c<i[1];++c)for(let p=0;p<i[2];++p)a=O(a,Y(e,[s*r.shape[0],c*r.shape[1],p*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else if(r.rank===4)for(let s=0;s<i[0];++s)for(let c=0;c<i[1];++c)for(let p=0;p<i[2];++p)for(let l=0;l<i[3];++l)a=O(a,Y(e,[s*r.shape[0],c*r.shape[1],p*r.shape[2],l*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);return a};return{x:o}}};const wv={kernelName:fs,gradFunc:(e,t,n)=>{const r=n,{perm:i}=r,o=pr(i);return{x:()=>X(e,o)}}};const yv={kernelName:gs,gradFunc:(e,t,n)=>{const r=n,{axis:i}=r;return{value:()=>dt(e,i)}}};const xv={kernelName:bs,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,r=()=>Sk(e,n);return{x:r}}};function Sk(e,t){const n=Tt(t,W(t)),r=Gn(e,n);let i=ct(t,k(0,"int32"));const o=r.rank-i.rank;for(let s=0;s<o;++s)i=Ke(i,s+1);i=ft(i,mt(r.shape,"bool"));const a=W(r);return Ae(i,r,a)}const Lv={kernelName:ws,gradFunc:e=>({x:()=>W(e)})};const Tk=[Ox,kx,Dx,Fx,Mx,Ux,Wx,qx,Bx,Px,jx,Gx,Hx,zx,Vx,Kx,Jx,Xx,Zx,Qx,eL,nL,tL,iL,oL,sL,aL,cL,pL,lL,uL,hL,dL,mL,gL,fL,bL,xL,LL,vL,SL,TL,IL,AL,NL,_L,CL,sf,sf,EL,kL,FL,ML,UL,WL,qL,BL,PL,jL,af,af,GL,$L,HL,YL,zL,VL,KL,JL,XL,ZL,QL,ev,tv,nv,rv,iv,ov,sv,av,cv,cf,cf,pf,pf,pv,uv,lv,hv,dv,mv,fv,gv,bv,wv,yv,xv,Lv];for(const e of Tk)Uu(e);return dy();})();
|
|
/*! *****************************************************************************
|
|
Copyright (c) Microsoft Corporation.
|
|
|
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
purpose with or without fee is hereby granted.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
PERFORMANCE OF THIS SOFTWARE.
|
|
***************************************************************************** */
|
|
/**
|
|
* @license
|
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google Inc. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/** @license See the LICENSE file. */
|
|
//# sourceMappingURL=face-api.min.js.map
|